Skip to main content

TemplateBuilder

Builder class for adding instructions to an E2B template. All methods return self to allow method chaining.

copy

Copy files or directories from the local filesystem into the template. Arguments:
  • src: Source file(s) or directory path(s) to copy
  • dest: Destination path in the template
  • force_upload: Force upload even if files are cached
  • user: User and optionally group (user:group) to own the files
  • mode: File permissions in octal format (e.g., 0o755)
  • resolve_symlinks: Whether to resolve symlinks
Returns: TemplateBuilder class Example

copy_items

Copy multiple files or directories using a list of copy items. Arguments:
  • items: List of CopyItem dictionaries with src, dest, and optional parameters
Returns: TemplateBuilder class Example

remove

Remove files or directories in the template. Arguments:
  • path: File(s) or directory path(s) to remove
  • force: Force removal without prompting
  • recursive: Remove directories recursively
  • user: User to run the command as
Returns: TemplateBuilder class Example

rename

Rename or move a file or directory in the template. Arguments:
  • src: Source path
  • dest: Destination path
  • force: Force rename without prompting
  • user: User to run the command as
Returns: TemplateBuilder class Example

make_dir

Create directory(ies) in the template. Arguments:
  • path: Directory path(s) to create
  • mode: Directory permissions in octal format (e.g., 0o755)
  • user: User to run the command as
Returns: TemplateBuilder class Example
Create a symbolic link in the template. Arguments:
  • src: Source path (target of the symlink)
  • dest: Destination path (location of the symlink)
  • user: User to run the command as
  • force: Force symlink without prompting
Returns: TemplateBuilder class Example

run_cmd

Run a shell command during template build. Arguments:
  • command: Command string or list of commands to run (joined with &&)
  • user: User to run the command as
Returns: TemplateBuilder class Example

set_workdir

Set the working directory for subsequent commands in the template. Arguments:
  • workdir: Path to set as the working directory
Returns: TemplateBuilder class Example

set_user

Set the user for subsequent commands in the template. Arguments:
  • user: Username to set
Returns: TemplateBuilder class Example

pip_install

Install Python packages using pip. Arguments:
  • packages: Package name(s) to install. If None, runs ‘pip install .’ in the current directory
  • g: Install packages globally (default: True). If False, installs for user only
Returns: TemplateBuilder class Example

npm_install

Install Node.js packages using npm. Arguments:
  • packages: Package name(s) to install. If None, installs from package.json
  • g: Install packages globally
  • dev: Install packages as dev dependencies
Returns: TemplateBuilder class Example

bun_install

Install Bun packages using bun. Arguments:
  • packages: Package name(s) to install. If None, installs from package.json
  • g: Install packages globally
  • dev: Install packages as dev dependencies
Returns: TemplateBuilder class Example

apt_install

Install system packages using apt-get. Arguments:
  • packages: Package name(s) to install
  • no_install_recommends: Whether to install recommended packages
Returns: TemplateBuilder class Example

add_mcp_server

Install MCP servers using mcp-gateway. Note: Requires a base image with mcp-gateway pre-installed (e.g., mcp-gateway). Arguments:
  • servers: MCP server name(s)
Returns: TemplateBuilder class Example

git_clone

Clone a git repository into the template. Arguments:
  • url: Git repository URL
  • path: Destination path for the clone
  • branch: Branch to clone
  • depth: Clone depth for shallow clones
  • user: User to run the command as
Returns: TemplateBuilder class Example

beta_dev_container_prebuild

Prebuild a devcontainer from the specified directory during the build process. Arguments:
  • devcontainer_directory: Path to the devcontainer directory
Returns: TemplateBuilder class Example

beta_set_dev_container_start

Start a devcontainer from the specified directory and set it as the start command. This method returns TemplateFinal, which means it must be the last method in the chain. Arguments:
  • devcontainer_directory: Path to the devcontainer directory
Returns: TemplateFinal class Example

set_envs

Set environment variables in the template. Arguments:
  • envs: Dictionary of environment variable names and values
Returns: TemplateBuilder class Example

skip_cache

Skip cache for all subsequent build instructions from this point. Call this before any instruction to force it and all following layers to be rebuilt, ignoring any cached layers. Returns: TemplateBuilder class Example

set_start_cmd

Set the command to start when the sandbox launches and the ready check command. Arguments:
  • start_cmd: Command to run when the sandbox starts
  • ready_cmd: Command or ReadyCmd to check if the sandbox is ready
Returns: TemplateFinal class Example

set_ready_cmd

Set the command to check if the sandbox is ready. Arguments:
  • ready_cmd: Command or ReadyCmd to check if the sandbox is ready
Returns: TemplateFinal class Example

TemplateFinal

Final template state after start/ready commands are set.

TemplateBase

Base class for building E2B sandbox templates.

__init__

Create a new template builder instance. Arguments:
  • file_context_path: Base path for resolving relative file paths in copy operations
  • file_ignore_patterns: List of glob patterns to ignore when copying files

skip_cache

Skip cache for all subsequent build instructions from this point. Returns: TemplateBase class Example

from_debian_image

Start template from a Debian base image. Arguments:
  • variant: Debian image variant
Returns: TemplateBuilder class Example

from_ubuntu_image

Start template from an Ubuntu base image. Arguments:
  • variant: Ubuntu image variant (default: ‘latest’)
Returns: TemplateBuilder class Example

from_python_image

Start template from a Python base image. Arguments:
  • version: Python version (default: ‘3’)
Returns: TemplateBuilder class Example

from_node_image

Start template from a Node.js base image. Arguments:
  • variant: Node.js image variant (default: ‘lts’)
Returns: TemplateBuilder class Example

from_bun_image

Start template from a Bun base image. Arguments:
  • variant: Bun image variant (default: ‘latest’)
Returns: TemplateBuilder class

from_base_image

Start template from the E2B base image (e2bdev/base:latest). Returns: TemplateBuilder class Example

from_image

Start template from a Docker image. Arguments:
  • image: Docker image name (e.g., ‘ubuntu:24.04’)
  • username: Username for private registry authentication
  • password: Password for private registry authentication
Returns: TemplateBuilder class Example

from_template

Start template from an existing E2B template. Arguments:
  • template: E2B template ID or alias
Returns: TemplateBuilder class Example

from_dockerfile

Parse a Dockerfile and convert it to Template SDK format. Arguments:
  • dockerfile_content_or_path: Either the Dockerfile content as a string, or a path to a Dockerfile file
Returns: TemplateBuilder class Example

from_aws_registry

Start template from an AWS ECR registry image. Arguments:
  • image: Docker image name from AWS ECR
  • access_key_id: AWS access key ID
  • secret_access_key: AWS secret access key
  • region: AWS region
Returns: TemplateBuilder class Example

from_gcp_registry

Start template from a GCP Artifact Registry or Container Registry image. Arguments:
  • image: Docker image name from GCP registry
  • service_account_json: Service account JSON string, dict, or path to JSON file
Returns: TemplateBuilder class Example

to_json

Convert a template to JSON representation. Arguments:
  • template: The template to convert (TemplateBuilder or TemplateFinal instance)
Returns: JSON string representation of the template Example

to_dockerfile

Convert a template to Dockerfile format. Note: Templates based on other E2B templates cannot be converted to Dockerfile. Arguments:
  • template: The template to convert (TemplateBuilder or TemplateFinal instance)
Raises:
  • ValueError: If the template is based on another E2B template or has no base image Example
Returns: Dockerfile string representation

InstructionType

Types of instructions that can be used in a template.

CopyItem

Configuration for a single file/directory copy operation.

Instruction

Represents a single instruction in the template build process.

GenericDockerRegistry

Configuration for a generic Docker registry with basic authentication.

AWSRegistry

Configuration for AWS Elastic Container Registry (ECR).

GCPRegistry

Configuration for Google Container Registry (GCR) or Artifact Registry.

TemplateType

Internal representation of a template for the E2B build API.

BuildInfo

Information about a built template. Special step name for the finalization phase of template building. This is the last step that runs after all user-defined instructions.

FINALIZE_STEP_NAME

Special step name for the base image phase of template building. This is the first step that sets up the base image.

BASE_STEP_NAME

Stack trace depth for capturing caller information. Depth levels:
  1. TemplateClass
  2. Caller method (e.g., copy(), from_image(), etc.)
This depth is used to determine the original caller’s location for stack traces.

STACK_TRACE_DEPTH

Default setting for whether to resolve symbolic links when copying files. When False, symlinks are copied as symlinks rather than following them.

ReadyCmd

Wrapper class for ready check commands.

wait_for_port

Wait for a port to be listening. Uses ss command to check if a port is open and listening. Arguments:
  • port: Port number to wait for
Returns: ReadyCmd that checks for the port Example

wait_for_url

Wait for a URL to return a specific HTTP status code. Uses curl to make HTTP requests and check the response status. Arguments: Returns: ReadyCmd that checks the URL Example

wait_for_process

Wait for a process with a specific name to be running. Uses pgrep to check if a process exists. Arguments:
  • process_name: Name of the process to wait for
Returns: ReadyCmd that checks for the process Example

wait_for_file

Wait for a file to exist. Uses shell test command to check file existence. Arguments:
  • filename: Path to the file to wait for
Returns: ReadyCmd that checks for the file Example

wait_for_timeout

Wait for a specified timeout before considering the sandbox ready. Uses sleep command to wait for a fixed duration. Arguments:
  • timeout: Time to wait in milliseconds (minimum: 1000ms / 1 second)
Returns: ReadyCmd that waits for the specified duration Example

DockerfFileFinalParserInterface

Protocol defining the final interface for Dockerfile parsing callbacks.

DockerfileParserInterface

Protocol defining the interface for Dockerfile parsing callbacks.

run_cmd

Handle RUN instruction.

copy

Handle COPY instruction.

set_workdir

Handle WORKDIR instruction.

set_user

Handle USER instruction.

set_envs

Handle ENV instruction.

set_start_cmd

Handle CMD/ENTRYPOINT instruction.

parse_dockerfile

Parse a Dockerfile and convert it to Template SDK format. Arguments:
  • dockerfile_content_or_path: Either the Dockerfile content as a string, or a path to a Dockerfile file
  • template_builder: Interface providing template builder methods
Raises:
  • ValueError: If the Dockerfile is invalid or unsupported
Returns: The base image from the Dockerfile

LogEntry

Represents a single log entry from the template build process.

LogEntryStart

Special log entry indicating the start of a build process.

LogEntryEnd

Special log entry indicating the end of a build process.

TIMER_UPDATE_INTERVAL_MS

Default minimum log level to display.

DEFAULT_LEVEL

Colored labels for each log level.

levels

Numeric ordering of log levels for comparison (lower = less severe).

set_interval

Returns a stop function that can be called to cancel the interval. Similar to JavaScript’s setInterval. Arguments:
  • func: Function to execute at each interval
  • interval: Interval duration in seconds
Returns: Stop function that can be called to cancel the interval

default_build_logger

Create a default build logger with animated timer display. Arguments:
  • min_level: Minimum log level to display (default: ‘info’)
Returns: Logger function that accepts LogEntry instances Example

read_dockerignore

Read and parse a .dockerignore file. Arguments:
  • context_path: Directory path containing the .dockerignore file
Returns: Array of ignore patterns (empty lines and comments are filtered out)

normalize_path

Normalize path separators to forward slashes for glob patterns (glob expects / even on Windows). Arguments:
  • path: The path to normalize
Returns: The normalized path

get_all_files_in_path

Get all files for a given path and ignore patterns. Arguments:
  • src: Path to the source directory
  • context_path: Base directory for resolving relative paths
  • ignore_patterns: Ignore patterns
  • include_directories: Whether to include directories
Returns: Array of files

calculate_files_hash

Calculate a hash of files being copied to detect changes for cache invalidation. The hash includes file content, metadata (mode, size), and relative paths. Note: uid, gid, and mtime are excluded to ensure stable hashes across environments. Arguments:
  • src: Source path pattern for files to copy
  • dest: Destination path where files will be copied
  • context_path: Base directory for resolving relative paths
  • ignore_patterns: Glob patterns to ignore
  • resolve_symlinks: Whether to resolve symbolic links when hashing
  • stack_trace: Optional stack trace for error reporting
Raises:
  • ValueError: If no files match the source pattern
Returns: Hex string hash of all files

tar_file_stream

Create a tar stream of files matching a pattern. Arguments:
  • file_name: Glob pattern for files to include
  • file_context_path: Base directory for resolving file paths
  • ignore_patterns: Ignore patterns
  • resolve_symlinks: Whether to resolve symbolic links
Returns: Tar stream

strip_ansi_escape_codes

Strip ANSI escape codes from a string. Source: https://github.com/chalk/ansi-regex/blob/main/index.js Arguments:
  • text: String with ANSI escape codes
Returns: String without ANSI escape codes

get_caller_frame

Get the caller’s stack frame at a specific depth. This is used to provide better error messages and debugging information by tracking where template methods were called from in user code. Arguments:
  • depth: The depth of the stack trace to retrieve
Returns: The caller frame, or None if not available

get_caller_directory

Get the directory of the caller at a specific stack depth. This is used to determine the file_context_path when creating a template, so file paths are resolved relative to the user’s template file location. Arguments:
  • depth: The depth of the stack trace
Returns: The caller’s directory path, or None if not available

pad_octal

Convert a numeric file mode to a zero-padded octal string. Arguments:
  • mode: File mode as a number (e.g., 493 for 0o755)
Returns: Zero-padded 4-digit octal string (e.g., “0755”) Example

get_build_step_index

Get the array index for a build step based on its name. Special steps:
  • BASE_STEP_NAME: Returns 0 (first step)
  • FINALIZE_STEP_NAME: Returns the last index
  • Numeric strings: Converted to number
Arguments:
  • step: Build step name or number as string
  • stack_traces_length: Total number of stack traces (used for FINALIZE_STEP_NAME)
Returns: Index for the build step

read_gcp_service_account_json

Read GCP service account JSON from a file or object. Arguments:
  • context_path: Base directory for resolving relative file paths
  • path_or_content: Either a path to a JSON file or a service account object
Returns: Service account JSON as a string