nb-wrangler is a command-line tool suite that streamlines the curation of
JupyterLab notebooks and their runtime environments. It automates the process of
defining, building, and testing the environments (and data) that notebooks need,
ensuring that notebooks have the correct dependencies to run successfully.
A single codebase ships two command-line tools:
nbw— the wrangler itself: define a spec (notebook repositories, selected notebooks, package lists, reference data), curate it into a locked environment, test it, and reinstall it reproducibly.hubenv— Persistent Platform Environments: create, archive ("can"), restore, inspect, and remove live mamba environments on the science platforms and locally, tracking each one as a shelf in the pantry.hubenvverbs are thin wrappers over the same underlying machinery asnbw; they share one code base and one spec schema.
Key features include:
- Environment Management: Bootstraps its own dedicated Conda environments, isolated from your system's Python.
- Dependency Resolution: Compiles
requirements.txtfiles from multiple notebooks into a single, consistent set of versioned dependencies. - Automated Testing: Tests notebooks and their package imports to verify the environment.
- Data Management: Manages the data required to run notebooks.
- Image Building: Integrates with build pipelines to automatically create container images.
- Local Installs: Works equally well doing local installs with no Docker overhead or learning curve.
The project uses micromamba for environment management and uv for fast pip
package installation.
Note that while nb-wrangler was conceived as a way to streamline notebook
Docker image creation for JupyterHub, at it's core nb-wrangler is merely defining:
- A set of notebooks particularly relevant to a science platform.
- Any supporting data required to run those notebooks.
- A Python environment capable of running the entire set of notebooks.
- Tests to help verify the system is built correctly and correctly runs those notebooks.
- Standard methods to locally install the notebooks, data, and Python environment and run the tests.
None of the above even builds Docker images directly. Production specs and the
automated image-build pipelines have moved to the sister repository
spacetelescope/nb-wrangler-images,
whose GitHub Actions build and publish the mission images
(ghcr.io/spacetelescope/nb-wrangler-images). nbw still supports injecting a
spec into the classic science-platform-images
(SPI) repository layout as a transitional path for older build processes.
Two other points are worthy of note:
- nb-wrangler can support easy installation of custom environments directly on the science platform that were not first pre-installed in the platform Docker image. This can be exploited to set up shared global or team installations areas as well as personalized environments.
- The network distribution and installation protocols used equally enable off-platform laptop users to set up the same environment locally in an easy manner.
nb-wrangler now supports pip installs into existing mamba environments:
pip install nb-wranglerThis is a relatively new feature and because the wrangler itself works by creating multiple
environments it is not always as reliable as the bootstrap method described below. If you do
use this method it's advisable to create a dedicated nbwrangler environment to install to.
hubenv's table-formatted commands additionally need the optional extra:
pip install 'nb-wrangler[hubenv]' (this only adds tabulate).
To get started, bootstrap nb-wrangler to create the necessary environments and directories (by default in $HOME/.nbw-live):
curl https://raw.githubusercontent.com/spacetelescope/nb-wrangler/refs/heads/main/nb-wrangler >nb-wrangler
chmod +x nb-wrangler
./nb-wrangler bootstrap [<wrangler-spec>.yaml]Advanced: If you specify the optional wrangler spec then the bootstrap will use the wrangler source code from the repository and/or ref specified in the spec, whether it is the production version or a dev version specified under dev_overrides. This is important when doing wrangler development to enable you to work off your own fork or a branch.
After bootstrapping, you can activate and/or reactivate the nbwrangler environment with:
source ./nb-wrangler environmentThis command sets up the shell environment and activates the nbwrangler Python environment so
that it (temporarily) replaces any other Python you had activated previously and is ready to
start executing wrangler commands. It should be mentioned that when the wrangler creates target
environments from the spec it will install them indepdently to this nbwrangler environment which
is intended only to support the tool itself.
The data download mechanisms in nb-wrangler utilize wget under the hood to fetch data URL's. If
your system does not already have it installed, you need to install it before you can do much. On Linux (including the science platforms) wget is almost certainly there but
if not it should be an easy package install. On OS-X wget is an easy install via brew and also
via mamba. Before working on data tasks, it's worth verifying wget is available on your PATH.
This is viable but the exact environment settings and required workflows are still being formalized.
If you're curious contact octarine@stsci.edu and we will work out platform and image appropriate instructions for doing in-situ development of platform environments using nb-wrangler.
The nb-wrangler workflow is divided into two main phases: curation and reinstallation. Throughout the examples below you'll see the command nbw which is the modern pre-installed method of running nb-wrangler vs. manually installing the command nb-wrangler.
Curation is the process of defining the notebooks, Python packages, and data
required for a specific environment. This is done by creating a nbw-spec.yaml
file that describes the desired environment. Typically notebook repository
maintainers perform these steps in addition their fundamental roles of producing
correct notebooks, pip requirements, and installable data.
The main curation workflows are:
--spec-init FILENAME: Generate a basic defaultspec.yamltemplate to get started.--curate: Compiles notebook requirements, creates the mamba environment, and installs pip dependencies.--data-curate: Gathers data requirements from notebook repositories and adds them to the spec.--test, --test-imports, --test-notebooks: Tests the notebook imports and notebooks themselves in the context of the environment and data installation.
Example:
# Curate the software environment
nbw spec.yaml --curate
# Test environment basics rapidly
nbw spec.yaml --test-imports
# Curate the data dependencies
nbw spec.yaml --data-curate
# Run each notebook headless using papermill
nbw spec.yaml --test-notebooks
# Activate your new "target" environment! Here kernel-name == mamba environment you are curating
source ./nb-wrangler activate <your-kernel-name>
# Deactivate your current environment
source ./nb-wrangler deactivateThe curation process involves:
- Choosing notebooks: Selecting the notebooks to be included in the environment.
- Resolving dependencies: Identifying and resolving any conflicts between Python packages.
- Defining data sources: Specifying the data required by the notebooks.
- Testing: Building the environment and testing the notebooks to ensure they run correctly.
Reinstallation is the process of creating a new environment from a completed spec.yaml file. This is useful for reproducing an environment on a different machine or for a different user.
The main reinstallation workflows are:
--reinstall: Recreates the software environment from a spec.--data-reinstall: Installs the data required by the notebooks.--test, --test-imports, --test-notebooks: Tests the notebook imports and notebooks themselves within the defined environment and data.
--reinstall and --data-reinstall require the spec's out section to already
hold the compiled outputs (they read the locked, precompiled spec rather than
re-curating it), and they never mutate the source spec: an unchanged save is a
byte-for-byte no-op that preserves the existing hash and date.
Example:
# Reinstall the software environment
nbw spec.yaml --reinstall
# Reinstall the data
nbw spec.yaml --data-reinstall
# Run both import and notebook tests
nbw spec.yaml --test-all
# Activate your new "target" environment! Here kernel-name == mamba environment you are curating
source ./nb-wrangler activate <your-kernel-name>
# Deactivate your current environment
source ./nb-wrangler deactivateFor both curation and reinstallation there is the assumption that tests may fail and it may be necessary to circle back to earlier steps, make fixes, and iterate.
For more information on notebooks and environment curation see Managing Notebook Selection and Environment For more information on supporting data see Managing Notebook Reference Data
To streamline development with custom branches without altering your core spec.yaml, nb-wrangler supports dev_overrides.
- The
dev_overridessection inspec.yamlallows you to temporarily specify development branches for repositories. - Use the
--devflag (or rely on implicit activation for curation workflows) to apply these overrides. - Use the
--prodflag to explicitly disable these overrides and force production settings. - Use
--spec-disable-dev-overridesto deactivate thedev_overridessection when preparing for production.
By default, nb-wrangler uses --prod mode (production, no dev overrides). Set the NBW_OVERRIDES_MODE environment variable to change the default behavior:
# Default to development mode for all workflows
export NBW_OVERRIDES_MODE="--dev"
# Explicitly set production mode (same as default)
export NBW_OVERRIDES_MODE="--prod"CLI flags (--dev, --prod) always override the environment variable. For example, even if NBW_OVERRIDES_MODE=--dev is set, running with --prod will disable dev overrides.
For more details, see the Spec Format documentation.
Every spec carries a spec_sha256 integrity hash computed by a single canonical
routine, shared by nbw and hubenv by construction. Validation accepts both
the canonical (0.10+) digest and the legacy (pre-0.10) digest, so specs stamped
under either algorithm keep validating. New stamps use the canonical digest
unless --spec-legacy-sha256 selects the legacy form (useful in mixed pipelines
that still run older releases). Spec writes are atomic, content-aware (a save
of unchanged content is a byte-for-byte no-op), and --spec-readonly refuses any
save that would modify the source spec. See "Spec Save and Integrity Contract"
in the Spec Format documentation.
nb-wrangler can inject the package and test requirements from a spec into the classic Science Platform Images (SPI) repository layout. This is a transitional feature to support older build processes.
See the SPI Injection documentation for more details.
nbw provides a wide range of command-line options to customize its behavior. Here are some of the most common ones, grouped by function:
Workflows are commands that execute an ordered sequence of steps to accomplish some end-to-end task:
--curate: Run the full curation workflow to define notebooks and Python environment.--reinstall: Reinstall an environment from a (precompiled) spec.--reset-curation: Delete installation artifacts like the environment, install caches, and spec updates.--data-curate: Curate data dependencies.--data-reinstall: Reinstall data dependencies.--data-reset-curation: Delete data downloads and spec data info so a follow-on--data-curatere-evaluates all data inputs.--inject-spi: Inject a spec into the SPI repository.
--env-init: Create and kernelize the target environment.--env-delete: Delete the target environment.--env-archive-delete: Delete the "code" portions of the pantry for the current spec (environment archives).--env-pack: Pack the target environment into an archive file.--env-unpack: Unpack an environment from an archive.--env-register: Register the environment as a Jupyter kernel.--env-unregister: Unregister the environment from Jupyter.--env-activate: Print a shell snippet (foreval/source) that activates the spec's environment by absolute path, including any data exports.--env-deactivate: Print a shell snippet (foreval/source) that deactivates the current mamba environment.--env-compact: Compact the wrangler installation by deleting package caches.--env-archive-format: Override format for environment pack/unpack.--env-print-name: Print the environment name for the spec.--env-kernel-cleanup: Scans the user's kernel registry for 'dead' kernels (kernels pointing to non-existent environments) and removes them.
--packages-compile: Compile package requirements.--packages-install: Install packages into the environment.--packages-uninstall: Uninstall packages from the environment.--packages-omit-spi: Don't include 'common' SPI packages.--packages-ignore-versions: Remove version constraints from notebook requirements.txt files before environment compilation.
-t,--test-all: Run all tests (--test-importsand--test-notebooks).--test-imports: Test package imports.--test-notebooks [REGEX]: Test notebook execution. Can optionally take a comma-separated list of regex patterns to select specific notebooks.--test-notebooks-exclude [REGEX]: Exclude notebooks from testing using a comma-separated list of regex patterns.--test-copy-shared [GLOB]: Copy Python modules matching a glob pattern to the runtime directory where an individual import test is running with respect to a particular notebook.--test-isolate-notebook: Isolate notebook tests by copying the notebook directory into a temporary directory (default: test in place).--jobs INT: Number of parallel jobs for notebook testing.--timeout INT: Timeout in seconds for notebook tests.
--data-collect: Collect data archive and installation info and add to spec.--data-list: List data archives.--data-download: Download data archives to the pantry.--data-update: Update metadata for data archives (e.g., length and hash).--data-validate: Validate pantry archives against the spec.--data-unpack: Unpack data archives.--data-pack: Pack live data directories into archive files.--data-reset-spec: Clear the 'data' sub-section of the 'out' section of the spec.--data-delete [archived|unpacked|both]: Delete data archives and/or unpacked files.--data-env-vars-mode [pantry|spec]: Define where to locate unpacked data.--data-print-exports: Print shell exports for data environment variables.--data-env-vars-no-auto-add: Do not automatically add data environment variables to the runtime environment.--data-select [REGEX]: Regex to select specific data archives.--data-no-validation: Skip data validation.--data-no-unpack-existing: Skip unpack if the target directory exists.--data-symlinks: Create symlinks from install locations to the pantry data directory.--data-no-symlinks: Do not create symlinks during --data-unpack.--data-clean-symlinks: Remove stale symlinks at install locations that no longer point to a valid target.
--spec-init FILENAME: Generate a basic defaultspec.yamltemplate file.--spec-reset: Reset the spec file to its original state (preservesout.data).--spec-add: Add the spec to the pantry (a local collection of specs); creates a 'shelf' for one complete environment.--spec-list: List available specs in the pantry.--spec-select [REGEX]: Select a spec from the pantry by regex.--spec-validate: Validate the spec file.--spec-update-hash: Update spec SHA256 hash.--spec-ignore-hash: Do not add or verify the spec hash.--spec-legacy-sha256: Stampspec_sha256with the pre-canonical (0.9.x) digest; validation always accepts both forms.--spec-readonly: Treat the source spec as read-only; any modification (content change or hash repair) is refused.--spec-disable-dev-overrides: Deactivate thedev_overridessection of the spec (forces--prodmode).--print-wrangler-repo: Print the nb-wrangler repository URL associated with this spec.--print-wrangler-ref: Print the nb-wrangler repository ref associated with this spec.--print-repo-tags: Print out the repositories sections of the spec with one URL and reference per line, usinggit ls-remote --tagsto resolve version-prefix refs (e.g.2026.2→ highest2026.2.ztag) without cloning.--spec-name: Generate a name suitable for referring to this image/spec/build and print to stdout.
--verbose: Enable DEBUG log output.-q,--quiet: Suppress all log output to stderr; only stdout will be visible.--quiet-downloads: Reduce download progress output (downloader output is captured and only shown, on failure, along with the error — handy for CI).--debug: Drop into debugger on exceptions.--profile: Run with cProfile and print stats.--reset-log: Delete the log file.--log-times [MODE]: Include timestamps in log messages (valid modes: absolute, elapsed, both, none).--color [MODE]: Colorize log output.--version: Print the version of nb-wrangler to stdout and stop.--mamba-cmd,--pip-cmd: Override the mamba/pip executables regardless of env var or spec settings.--favor-commands [environment|spec]: Discriminate between env vars and spec settings forMAMBA_CMD/PIP_CMDwhen both are defined.
These flags automate Docker builds and git operations during an --inject-spi workflow. See the SPI Injection documentation for examples.
--spi-image-name: Print the image name corresponding to the current spec to stdout and exit.--spi-inject-reqs: Copy the appropriate requirements fields from the wrangler spec into locations in the SPI repo clone.--spi-prune-docker: Prune old Docker images before a build to free space. Only removes SPI images.--spi-image-build: Trigger a Docker build in the SPI repo. REQUIRED prior to the switches below.--spi-run-lab: Run Jupyter Lab in a Docker container for the SPI deployment based on the current spec. Choose "Shutdown Jupyter Lab" from the lab File menu to exit cleanly when you're done.--spi-image-test [PARAMS]: Run the image-test script for the SPI deployment.PARAMSis an optional single string of parameters passed to the nested image-test invocation; it is split on whitespace into individual arguments (quote each parameter and any attached value, e.g."\"--test-notebooks --dev\""). If present without a value, an empty parameter list is used. You must specify either no parameters (--test-imports) or one of--test-imports,--test-notebooks,--test-allas your first parameter in the string. Use the form--spi-image-test='parameters...'for it to parse correctly with parameters.--spi-image-scan: Run the image-scan script for the SPI deployment, scanning the built Docker image for security vulnerabilities.
(The former --spi-branch, --spi-commit-message, --spi-push-branch, and
--spi-pr git-workflow flags are obsolete and no longer accepted; production
spec submission happens through nb-wrangler-images.)
These parameters are used to interact with the public image repo, currently spacetelescope GHCR nb-wrangler-images.
--docker-pull IMAGE: Pull a Docker image from a registry.--docker-cat IMAGE: Extract and print /spec.yaml from a Docker image to stdout.--docker-list SPEC_GLOB: List all spec names matching the spec-glob from the registry.
--clone-repos: Clone notebook repos to the directory indicated by --repos-dir.--repos-dir PATH: Directory where notebook and other repos will be cloned.--delete-repos: Delete --repo-dir and clones after processing.--repos-clean [PATTERN]: Clean up specified patterns in cloned repos (defaults to pycache).--overwrite-local-changes: In any cloned repo, overwrite local uncommitted changes to match the requested ref.--stash-local-changes: In any cloned repo, stash local uncommitted changes before matching the requested ref.--use-dirty-repos: In any cloned repo, use the current state as-is even if it has local changes.
For a full list of options, run nbw --help.
nb-wrangler uses several input formats to define the environment:
- Notebook (
.ipynb): Jupyter notebooks. - Wrangler Spec (
spec.yaml): The main YAML file that defines the notebook repositories and Python environment. See the spec format documentation for details on the current spec format (version 2.3), which uses arepositoriesdictionary, namedselected_notebooksblocks, top-level package lists, optionalassets,environment_vars,test_environment_vars, and nestedsystem.commandsoverrides. - Notebook Repo: A Git repository containing Jupyter notebooks. e.g., TIKE Content, Roman Notebooks
- nb-wrangler-images: The GitHub repository where production wrangler specs and the automated image-build pipelines now live. nb-wrangler-images
- Science Platform Images (
SPI): The GitHub repository where code for the classic science platform Docker images is kept. Science Platform Images - Refdata Spec (
refdata_dependencies.yaml): A YAML file in a notebook repository that specifies data dependencies. See the refdata dependencies documentation. - Requirements (
requirements.txt): A file specifying Python package dependencies for a notebook in its directory. - Supporting Python (
.py): Any supporting Python files (.py) included in a notebook's directory.
The goal of nb-wrangler is to combine these inputs, resolve any conflicts, and create a unified environment capable of running all specified notebooks.
Secondary goals, include but are not limited to:
- Collecting, freezing, distributing, and re-installing data associated with notebook repos.
- Initializing notebook and terminal environment variables as spec'ed, partcularly regarding spec'ed/installed data which may be installed in a shared location.
- Building Docker images for curators or science platform admins or pipelines.
- Testiing environments (importing all requested package) and notebooks.
- Automating any/all of these tasks for notebook repos / curators and the science platforms.
