Skip to content

About

E2B on AWS

Resources

Code of conduct

Contributing

Security policy

Stars

90 stars

Watchers

2 watching

Forks

Latest commit

Β 

History

153 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

E2B on AWS

Deploy E2B AI Sandboxes in Your Own AWS Account

License Platform CloudFormation

English | δΈ­ζ–‡


πŸ“‹ Table of Contents


✨ Introduction

E2B on AWS provides a secure, scalable, and customizable environment for running AI agent sandboxes in your own AWS account. This project addresses the growing need for organizations to maintain control over their AI infrastructure while leveraging the power of E2B's sandbox technology for AI agent development, testing, and deployment.

If you encounter any issues, please submit a PR directly. Special thanks to all contributors involved in the project transformation.

Upstream version

The code layer (packages/, spec/, scripts/, tests/, firecracker/) is a byte-for-byte copy of e2b-dev/infra at 225f963, with three exceptions: three packages this deployment does not build and so does not vendor (dashboard-api, local-dev, nomad-nodepool-apm β€” none of them appear in go.work); upstream's .env* samples, which .gitignore excludes; and four files taken as they are from the later upstream commit d01654d8 for arm64 β€” packages/api/Makefile and packages/api/docker-bake.hcl (the api and db-migrator images follow BUILD_ARCH), and packages/orchestrator/pkg/sandbox/fc/kernel_args.go with its test (no x86-only kernel parameters on arm64 guests). The rest of that commit is not carried. A sync replaces that layer wholesale rather than merging into it. The deployment layer (CloudFormation, infra-iac/, nomad/) is specific to this repository.


πŸ“¦ Prerequisites

Requirement Description
AWS Account With appropriate permissions
Domain Name A domain you own (Cloudflare recommended)
Grafana Account (Optional) For monitoring and logging
Posthog Account (Optional) For analytics
πŸ”’ Production Security Checklist

Before deploying to production, verify these critical security and reliability settings are enabled:

  • DB_INSTANCE_BACKUP_ENABLED
  • RDS_AUTOMATIC_MINOR_VERSION_UPGRADE_ENABLED
  • RDS_ENHANCED_MONITORING_ENABLED
  • RDS_INSTANCE_LOGGING_ENABLED
  • RDS_MULTI_AZ_SUPPORT
  • S3_BUCKET_LOGGING_ENABLED
  • IMDSv2 enforced - Instance Metadata Service v2 is required on all EC2 instances (HttpTokens: required)

πŸš€ Deployment (New VPC)

To deploy into an existing VPC instead, see Deployment (Existing VPC).

Step 1 β€” Deploy CloudFormation Stack

  1. Clone this repository
  2. Open AWS CloudFormation console and create a new stack
  3. Upload the e2b-setup-env.yml file
  4. Configure the following parameters:
Parameter Description
Stack Name Must be lowercase (e.g., e2b-infra)
VPC Configuration New VPC environment configuration
Environment dev or prod (prod has stricter resource protection)
Architecture x64 or AWS Graviton
ClientSubnetType Private (default) or Public: which subnets the sandbox host nodes run in, see Client node placement
Domain A domain you own (e.g., example.com)
EC2 Key Pair Existing key pair for SSH access
AllowRemoteSSHIPs IP range for SSH access (defaults to private networks)
Database Settings RDS password: 8-30 characters with letters and numbers
  1. Complete all required fields and launch the stack

Note: See AWS Graviton Technical Guide for Graviton best practices.

Client node placement

ClientSubnetType decides where the client nodes - the hosts that run the sandboxes - live:

Private (default) Public
Subnets Private subnets Public subnets, one public IP per node
Sandbox egress Through the NAT gateway Out through the internet gateway, from the node's own public IP
Inbound from the internet None None: the client security group admits traffic from inside the VPC only
Trade-off NAT data-processing charges and NAT port limits apply No NAT charge or NAT port limit (the node's own connection tracking still applies); sandbox traffic leaves from each node's address rather than a fixed NAT address

To change it on a running stack (sandboxes on the client nodes are lost):

# 1. Record the new value on the stack, keeping the deployed template.
#    Skip this step if the stack was created from a template without
#    ClientSubnetType, or if CloudFormation wants to replace the bastion because
#    the Ubuntu AMI moved on since the stack was created (the stack policy stops
#    that update). terraform only reads what step 2 writes.
aws cloudformation update-stack --stack-name <stack> --use-previous-template \
  --capabilities CAPABILITY_IAM --parameters \
  $(aws cloudformation describe-stacks --stack-name <stack> \
      --query 'Stacks[0].Parameters[?ParameterKey!=`ClientSubnetType`].ParameterKey' --output text \
    | tr '\t' '\n' | sed 's/.*/ParameterKey=&,UsePreviousValue=true/') \
  ParameterKey=ClientSubnetType,ParameterValue=Public

# 2. On the bastion. The chain reads the value from /opt/config.properties, which
#    the init step wrote when the stack was created. Do not rerun --only init for
#    this: it rewrites the file from the stack outputs and drops what later steps
#    appended to it.
if grep -q '^CFNCLIENTSUBNETTYPE=' /opt/config.properties; then
  sudo sed -i 's/^CFNCLIENTSUBNETTYPE=.*/CFNCLIENTSUBNETTYPE=Public/' /opt/config.properties
else
  echo 'CFNCLIENTSUBNETTYPE=Public' | sudo tee -a /opt/config.properties
fi
sudo bash deploy-all.sh --only terraform

# 3. Replace the client nodes; terraform applies the change without refreshing them.
aws autoscaling terminate-instance-in-auto-scaling-group \
  --instance-id <client-instance-id> --no-should-decrement-desired-capacity

If your public and private subnets cover different Availability Zones (possible with the existing-VPC template), the Auto Scaling group rebalances across the new zones by itself and may replace client nodes before step 3.

Stacks created before ClientSubnetType existed have no CFNCLIENTSUBNETTYPE in /opt/config.properties, so the next deploy-all.sh --only terraform with this code stops in prepare.sh, naming the missing key. Add it with the value those stacks always had: echo 'CFNCLIENTSUBNETTYPE=Private' | sudo tee -a /opt/config.properties.

Step 2 β€” Validate Domain Certificate

  1. Navigate to Amazon Certificate Manager (ACM)
  2. Find your domain certificate and note the required CNAME record
  3. Add the CNAME record to your DNS settings (Cloudflare DNS)
  4. Wait for domain validation (typically 5 minutes)

Step 3 β€” Connect to Bastion Machine

# Option A: SSH with your key pair
ssh -i your-key.pem ubuntu@<instance-ip>

# Option B: AWS Session Manager from the EC2 console

Step 4 β€” Run the Deployment (or Watch It Run)

The whole bootstrap writes to a single log, /tmp/e2b.log β€” the toolchain install, every deployment step, and the output of each step:

sudo su root
tail -f /tmp/e2b.log

If you left AutoDeploy=true (the default), the chain is already running and there is nothing to start. Follow it in the log above.

If you set AutoDeploy=false, the stack installed the toolchain and cloned this repository but ran nothing. One command does the rest:

cd /opt/infra/sample-e2b-on-aws
sudo bash deploy-all.sh

It runs the same steps, in the same order, that AutoDeploy=true would: init β†’ packer β†’ terraform β†’ init-db β†’ build β†’ prepare β†’ deploy β†’ create-template. Each step that succeeds writes /opt/.e2b-step-<name>.done, so if one fails you can fix the cause and re-run the script β€” it resumes at the step that broke instead of repeating the work before it.

sudo bash deploy-all.sh --list             # steps, and which are already done
sudo bash deploy-all.sh --skip-template    # stop after deploy, no test template
sudo bash deploy-all.sh --only terraform   # re-run one step, ignoring its marker
sudo bash deploy-all.sh --force            # clear all markers and start over
sudo bash deploy-all.sh --help

Note: the full chain took about 45 minutes on an x86_64 dev stack. build (compiling and pushing the service images, ~19 min) and packer (the AMI, ~14 min) dominate; everything else is minutes.

Step 5 β€” Configure DNS Records (Cloudflare)

  1. Wildcard DNS: Add a * CNAME record pointing to the Application Load Balancer (ALB) DNS name
  2. Nomad Dashboard: Navigate to https://nomad.<your-domain>
  3. Retrieve Token: Run cat /opt/config.properties to get the Nomad management token
πŸ“Š Logging & Monitoring (Optional)

The logging and monitoring stack consists of three components. The deploy step of deploy-all.sh deploys Loki and the logs collector on every stack, and the OTel collector once you have configured a backend for it (see below):

Component Type Purpose Port
OTel Collector system (all nodes) Collects metrics, traces, and application logs via OTLP 4317 (gRPC), 4318 (HTTP)
Logs Collector (Vector) system (all nodes) Collects sandbox user logs, routes to Loki 30006
Loki service (api node) Log storage and query engine, backed by S3 3100

Architecture:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”     β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Go Services (api/orch/proxy)β”‚     β”‚ Sandbox envd         β”‚
β”‚  OTel SDK β†’ gRPC :4317      β”‚     β”‚  HTTP β†’ :30006       β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           β”‚                                    β”‚
           β–Ό                                    β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚   OTel Collector      β”‚            β”‚   Vector (logs-coll) β”‚
β”‚   Metrics/Traces/Logs β”‚            β”‚   Sandbox user logs  β”‚
β”‚   β†’ Customer endpoint β”‚            β”‚   β†’ Loki             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                                               β–Ό
                                    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
                                    β”‚   Loki               β”‚
                                    β”‚   Storage: S3 bucket β”‚
                                    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Deploy the logging module

Sandbox user logs are the one part of this stack that needs no external backend: Vector ships them to a Loki that runs in the cluster and stores in S3. The deploy step does this on its own; to redeploy the two jobs by hand, Loki first because Vector's sink resolves loki.service.consul:

source nomad/nomad.sh          # exports NOMAD_ADDR / NOMAD_TOKEN
bash nomad/deploy.sh loki
bash nomad/deploy.sh logs-collector

logs-collector is a system job, so it lands one allocation per node β€” the api, build and sandbox nodes all ship logs. Storage is the Loki bucket CloudFormation created, {stack-name}-loki-{account-id}; retention is Loki's default, not S3 lifecycle, so set a lifecycle rule on that bucket if the volume matters to you.

Deploy this even if you have no OTel backend. Without logs-collector the services keep POSTing to localhost:30006, nothing is listening, and the log line is dropped β€” which is how a template build failure once surfaced only as Build failed: An internal error occurred with the real cause (stat /fc-versions/...: no such file or directory) discarded.

Query the logs

Loki has no UI of its own. It listens on the private address of the node its allocation landed on, so find that node and query the HTTP API from the bastion:

source nomad/nomad.sh
ALLOC=$(nomad job status loki | sed -n '/^Allocations/,$p' | awk 'NR==3{print $1}')
NODE=$(nomad alloc status -json "$ALLOC" | jq -r .NodeID)
LOKI=$(nomad node status -json "$NODE" | jq -r .HTTPAddr | cut -d: -f1)

# What labels exist yet
curl -s "http://$LOKI:3100/loki/api/v1/labels" | jq -c .data
# ["buildID","category","envID","sandboxID","service","source","teamID"]

# Everything one sandbox emitted in the last 10 minutes
curl -s --get "http://$LOKI:3100/loki/api/v1/query_range" \
  --data-urlencode 'query={sandboxID="<sandbox-id>"}' \
  --data-urlencode "start=$(( $(date +%s) - 600 ))000000000" \
  --data-urlencode 'limit=50' | jq -r '.data.result[]?.values[]?[1]'

Each line is a JSON object carrying the command, pid, exit status, teamID and envID, so {service="envd"} gives every sandbox's activity and {sandboxID="..."} narrows it to one. An empty label list means no logs have arrived yet β€” either logs-collector is not deployed or no sandbox has run.

Consul DNS is not resolvable from the bastion, which is why the address is looked up through Nomad rather than by using loki.service.consul directly. Inside the cluster that name works, and it is what Vector and the API use.

Deploy with Customer OTel Endpoint

Point the cluster at your own OTLP/HTTP backend β€” Grafana Cloud, Datadog, Honeycomb, New Relic, or a collector you run. Do it once the regular installation has finished: add the backend to /opt/config.properties on the bastion, then let deploy-all.sh render and deploy the collector.

cd /opt/infra/sample-e2b-on-aws

# 1. The backend. otel_customer_endpoint is the OTLP/HTTP base URL - the exporter
#    appends /v1/metrics, /v1/traces and /v1/logs itself, so leave those out.
cat << EOF | sudo tee -a /opt/config.properties
otel_customer_endpoint=https://otlp-gateway-prod-us-east-0.grafana.net/otlp
otel_customer_header_name=Authorization
otel_customer_header_value=Basic <base64(instanceID:token)>
EOF

# 2. Render the jobs with it, then deploy
sudo bash deploy-all.sh --only prepare
sudo bash deploy-all.sh --only deploy
Backend otel_customer_header_name otel_customer_header_value
Grafana Cloud Authorization Basic <base64(instanceID:token)>
Datadog DD-API-KEY your API key
Honeycomb x-honeycomb-team your ingest key
New Relic api-key your licence key
Self-hosted, no auth (leave both out)

The deploy step checks the settings before it deploys the collector (Loki and the logs collector go first either way) and fails with a message instead of shipping a collector that cannot start or that sends somewhere else:

  • With a header the endpoint must be https:// β€” the credential is not sent in clear. Set otel_customer_header_name and otel_customer_header_value together, or neither.
  • The endpoint and the header value may not contain quotes, backslashes, $, backticks, braces, control characters or double spaces: they are substituted verbatim into the collector's YAML, which also expands ${...} itself. API keys and Basic/Bearer tokens never need them. Header names are letters, digits, - and _.
  • If an otel_customer_* key changed after the last prepare, deploy refuses to run with the stale rendered job and tells you to rerun prepare first.
  • The collector is a system job that nomad job run does not wait for, so the step waits until it is running on every node without restarts. That proves the collector is up, not that the backend accepts what it sends: a wrong credential shows up as Exporting failed in nomad alloc logs -stderr <alloc-id>.

To change the backend, append the new keys (the last occurrence of a key wins) and run the same two commands. To drop the header, append both header keys empty. To turn the collector off, append otel_customer_endpoint= and run them again: the deploy step stops the running collector, so it does not keep sending to the old backend with the old credential. Without an otel_customer_endpoint the deploy step simply leaves the collector out, which is what a fresh installation does.

The keys live in /opt/config.properties, like the other credentials there, and are lost if the init step is rerun: init regenerates the file from the stack outputs. Add them again afterwards.

No backend yet? Sandbox user logs do not need one: logs-collector writes them to the in-cluster Loki, and the deploy step runs it on every stack. Only the OTel pipeline (metrics, traces, service logs) requires an endpoint to send to.

Data Flow Details

Data Type Source Pipeline Storage
Metrics (application) Go services OTel SDK β†’ OTel Collector β†’ Customer endpoint External
Metrics (infrastructure) Nomad /v1/metrics β†’ OTel Collector (Prometheus scrape) β†’ Customer endpoint External
Traces Go services OTel SDK β†’ OTel Collector β†’ Customer endpoint External
Application Logs Go services zap logger β†’ OTel Collector (OTLP log bridge) β†’ Customer endpoint External
Sandbox User Logs envd β†’ orchestrator β†’ Vector (:30006) β†’ Loki (:3100) S3 (Loki bucket)

Note: Every metric, trace and log the OTel collector exports carries the EC2 host and zone it came from (host.id is the instance ID, plus host.name, host.type, cloud.availability_zone, ...), read from the instance metadata service. The node identity each service reports for itself is kept as nomad.node.id: the Nomad node ID for api, client-proxy and orchestrator, the Nomad node name (which is the instance ID) for template-manager. Nomad's own metrics and the collector's self-metrics have no nomad.node.id.

Note: Sandbox user logs always go through Vector β†’ Loki β†’ S3, independent of the OTel pipeline. The Loki S3 bucket is created by CloudFormation ({stack-name}-loki-{account-id}); Terraform only grants the nodes access to it.

Step 6 β€” Test E2B

Create a template:

# On the bastion, from the repository root (/opt/infra/sample-e2b-on-aws):
# the script reads /opt/config.properties, which only exists there.

# Create from e2bdev/code-interpreter (default on x86_64). That image is published
# for linux/amd64 only, so arm64 (Graviton) stacks default to e2bdev/base instead,
# with no start command (no Jupyter).
bash tools/legacy/create_template.sh

# Create from a Dockerfile
bash tools/legacy/create_template.sh --docker-file <Docker_File_Path>

# Example: Desktop
bash tools/legacy/create_template.sh --docker-file test_use_case/Dockerfile/e2b.Dockerfile.Desktop

# Example: BrowserUse
bash tools/legacy/create_template.sh --docker-file test_use_case/Dockerfile/e2b.Dockerfile.BrowserUse

# Example: S3FS
bash tools/legacy/create_template.sh --docker-file test_use_case/Dockerfile/e2b.Dockerfile.s3fs

# Example: Code Interpreter (customized)
bash tools/legacy/create_template.sh --docker-file test_use_case/Dockerfile/e2b.Dockerfile.code_interpreter

# Create from an ECR image in your own account
bash tools/legacy/create_template.sh --ecr-image <ECR_IMAGE_URI>

Create a sandbox:

# e2b_API:     jq -r .teamApiKey infra-iac/db/config.json   (on the bastion, from the repo root)
# template_ID: e2b template list
curl -X POST \
  https://api.<e2bdomain>/sandboxes \
  -H "X-API-Key: <e2b_API>" \
  -H 'Content-Type: application/json' \
  -d '{
    "templateID": "<template_ID>",
    "timeout": 3600,
    "autoPause": true,
    "metadata": { "purpose": "test" }
  }'

πŸ”„ Deployment (Existing VPC)

If you already have a VPC with subnets configured, use the e2b-setup-env-existing-vpc.yml template instead.

Step 1 β€” Deploy CloudFormation Stack

  1. Open AWS CloudFormation console and create a new stack
  2. Upload the e2b-setup-env-existing-vpc.yml file
  3. Configure the following parameters:
Parameter Description
Stack Name Must be lowercase (e.g., e2b-infra)
ExistingVpcId Your existing VPC ID
ExistingPrivateSubnet1Id / 2Id Private subnet IDs (two AZs)
ExistingPublicSubnet1Id / 2Id Public subnet IDs (two AZs)
PublicAccess public or private access mode
ClientSubnetType Private (default) or Public; Public uses the two public subnets above, which must route 0.0.0.0/0 to an internet gateway
Architecture, Domain, Key Pair, DB Same as standard deployment
  1. The template automatically discovers your VPC CIDR block via a Lambda function

Step 2 β€” Post-Deployment

Domain validation, bastion access, DNS setup, monitoring, and testing follow the same process as the standard deployment starting from Step 2.

Note: The existing VPC template uses Aurora Serverless PostgreSQL and Redis Serverless.


πŸ–₯️ Using E2B CLI

# Installation Guide: https://e2b.dev/docs/cli
# Pin the version this deployment was verified with (see the table below).
# brew cannot pin a version, so it is not used here.
npm i -g @e2b/cli@2.16.1          # or run each command as: npx -y @e2b/cli@2.16.1 <command>

# Export environment variables
# (query teamApiKey from /opt/config.properties)
#
# E2B_ACCESS_TOKEN is not set here: upstream dropped the access_tokens table, so
# this deployment no longer issues an sk_e2b_ token. CLI commands that take a
# team API key work; the ones that authenticate as a user need an auth provider,
# which this deployment does not run.
export E2B_API_KEY=xxx
export E2B_DOMAIN="<e2bdomain>"

# Common commands
e2b template list                 # List templates - the template ID the SDK needs
e2b sandbox list                  # List all sandboxes
e2b sandbox connect <sandbox-id>  # Connect to a sandbox
e2b sandbox kill <sandbox-id>     # Kill a sandbox
e2b sandbox kill --all            # Kill all sandboxes

Client versions this deployment was verified with

Client Version Install
E2B CLI 2.16.1 npm i -g @e2b/cli@2.16.1
Python SDK e2b 2.46.0 pip install e2b==2.46.0 e2b-code-interpreter==2.9.2
Python SDK e2b-code-interpreter 2.9.2 same command - pin both, or the dependency floats to the newest e2b
envd (in-sandbox agent, server side) 0.7.0 built by the deploy chain, not installed by you

Verified against the code layer at upstream 225f963. envd is reported by the API on every create (envdVersion) and by e2b sandbox list, so it is the quickest way to confirm which build a sandbox actually came from.

Only E2B_API_KEY and E2B_DOMAIN are needed β€” e2b sandbox list and e2b template list were both checked with no E2B_ACCESS_TOKEN set, which is what this deployment can offer now that upstream dropped user access tokens. If ~/.e2b/config.json holds an older E2B Cloud login, every command first prints "Your CLI authentication config is deprecated. You have been signed out." That is harmless here: the CLI leaves the file alone and uses the two variables.

Two scripts in tools/ exercise the API against a running deployment:

python3 tools/api-smoke-test.py                  # auth, templates, sandbox lifecycle
python3 tools/api-load-test.py --sandboxes 40    # concurrency: burst, fan-out, churn
# add --replicas <ip:port>,<ip:port> to also assert the API replicas share state

Both read the credentials the deploy chain wrote, so there is nothing to export first, and both clean up every sandbox they create.


🐍 Using the Python SDK

Run this from any machine that resolves *.<e2bdomain>. It pins the SDK versions from the table above and goes through a sandbox's lifecycle: create, run a command, reach the internet, write a file, list, pause and resume, then run code through e2b-code-interpreter. uv keeps it out of your environments; with pip, install e2b==2.46.0 e2b-code-interpreter==2.9.2 and run the same script.

export E2B_API_KEY=xxx               # teamApiKey from /opt/config.properties
export E2B_DOMAIN="<e2bdomain>"      # without it the SDK talks to E2B Cloud (api.e2b.app)
export E2B_TEMPLATE=<template_ID>    # from `e2b template list`

uv run --no-project --with e2b==2.46.0 --with e2b-code-interpreter==2.9.2 python - <<'EOF'
import os
from e2b import Sandbox
from e2b_code_interpreter import Sandbox as CodeSandbox

template = os.environ["E2B_TEMPLATE"]

sbx = Sandbox.create(template=template, timeout=300)
print("sandbox:", sbx.sandbox_id)
print(sbx.commands.run("echo hello && uname -r").stdout)
print("egress:", sbx.commands.run("curl -s -o /dev/null -w '%{http_code}' https://pypi.org/simple/").stdout)
sbx.files.write("/tmp/hello.txt", "hi")
print("listed:", sbx.sandbox_id in [s.sandbox_id for s in Sandbox.list().next_items()])
sbx.pause()
sbx = Sandbox.connect(sbx.sandbox_id)       # resumes the paused sandbox
print("after resume:", sbx.files.read("/tmp/hello.txt"))
sbx.kill()

code = CodeSandbox.create(template=template, timeout=300)
print("run_code:", code.run_code("21 * 2").text)
code.kill()
EOF

A working deployment prints egress: 200, listed: True, after resume: hi and run_code: 42.

Two things differ from E2B Cloud. Both apply to the e2b-cookbook examples as well: hello-world-python, for one, has only E2B_API_KEY in its .env.template and calls Sandbox.create() with no template.

  • Set E2B_DOMAIN. Without it every call goes to api.e2b.app, where this deployment's key is not valid.
  • Pass template=. Without it e2b_code_interpreter asks for its default template code-interpreter-v1, which this deployment does not have, and the create fails with a 404. The template the deploy chain builds (alias test-<timestamp>) comes from e2bdev/code-interpreter, so it serves both e2b.Sandbox and e2b_code_interpreter.Sandbox. On an arm64 stack it comes from e2bdev/base, which has no Jupyter, so only e2b.Sandbox works there.

πŸ—‘οΈ Snapshot Retention

Pausing a sandbox writes a snapshot into the templates bucket, next to the template builds it was layered on, and nothing upstream ever deletes it β€” not even DELETE /sandboxes/{id}, which only hides the database row. The snapshot-retention Nomad job (nomad/origin/snapshot-retention.hcl, built from tools/snapshot-retention) runs daily at 03:00 UTC and applies one policy:

  • A paused sandbox whose last pause is older than 90 days is soft-deleted: it disappears from e2b sandbox list and cannot be resumed, exactly as if it had been deleted through the API.
  • 7 days later its objects are deleted from the bucket and its build rows from the database β€” but only after the job has confirmed, from the headers of every live template and snapshot, that nothing still reads those blocks. A fork's checkpoint, a snapshot template, or a template built from one keeps its ancestors alive. Template objects are never touched.
  • Snapshots deleted through the API follow the same 90-day / 7-day rule.

Why a job rather than an S3 lifecycle rule: snapshots are diffs. A newer snapshot's header points at blocks of older snapshots and of the template, and a running sandbox reads them lazily. Expiring objects by age would corrupt them.

The job ships as a dry run: it logs every MARK and PURGE it would make and changes nothing. Review a run, then enable it:

# Trigger a run now and read its log
nomad job periodic force snapshot-retention
nomad job status snapshot-retention        # child job -> allocation id
nomad alloc logs <alloc-id>

# Enable deletion
echo "RETENTION_APPLY=true" >> /opt/config.properties
bash nomad/prepare.sh
bash nomad/deploy.sh snapshot-retention

Only one run executes at a time: a manual run started while the nightly one is active exits at once with another snapshot-retention run holds the lock.

Within the 7-day window a marked sandbox can be brought back by clearing the soft delete on its snapshot env (the env in the MARK log line). The extra conditions keep a mistyped id from resurrecting a template someone deleted on purpose:

UPDATE envs SET deleted_at = NULL
WHERE id = '<env-id>' AND source = 'snapshot' AND deleted_at IS NOT NULL;

The same statement covers the one edge case the job does not handle itself: a sandbox that was running at the moment it was marked stays hidden after its next pause. Its objects are safe β€” that pause keeps them for another 90 days β€” it just needs the soft delete cleared to show up again. These envs are the ones that gained a build after they were soft-deleted, so they can be listed without the log:

SELECT e.id, s.sandbox_id, e.deleted_at
FROM envs e JOIN snapshots s ON s.env_id = e.id
WHERE e.source = 'snapshot' AND e.deleted_at IS NOT NULL
  AND EXISTS (SELECT 1 FROM env_build_assignments a JOIN env_builds b ON b.id = a.build_id
              WHERE a.env_id = e.id AND GREATEST(b.created_at, a.created_at) > e.deleted_at);

RETENTION_DAYS and PURGE_DELAY_DAYS live in the job spec. The delay must exceed the longest sandbox lifetime (tiers.max_length_hours); the job refuses to run otherwise.

The tool is compiled against the vendored code layer and pinned to the newest database migration it was verified with (verifiedMigration in tools/snapshot-retention/schema.go). After an upstream sync that adds migrations, go test for the tool fails until the constant is bumped, and a deployed binary that meets a newer schema runs as a dry run and exits non-zero. Treat a failing build or test of tools/snapshot-retention as a failed sync.


πŸ”§ Troubleshooting

No nodes were eligible for evaluation

Check node status and constraints in the Nomad dashboard.

Driver Failure: Failed to pull from ECR

Error: pull access denied ... Your authorization token has expired

Solution: Execute aws ecr get-login-password --region us-east-1 to get a new ECR token and update the HCL file.

For other unresolved issues, contact support.


🧹 Resource Cleanup

When you need to delete the E2B environment, follow these steps:

1. Terraform Resource Cleanup

cd ~/infra-iac/terraform/
terraform destroy

Note: S3 Buckets must be manually emptied first. ALBs may require manual deletion through the AWS console.

2. CloudFormation Stack Cleanup

  • Disable RDS deletion protection through the RDS console first
  • Then delete the CloudFormation stack

3. Manual Verification

After automated cleanup, verify in the AWS console that all resources are removed:

Service Check
EC2 Instances, Security Groups, Load Balancers
S3 Buckets
RDS Database instances
ECR Container repositories

πŸ” Security

See CONTRIBUTING for more information.

πŸ“„ License

This project is licensed under the Apache-2.0 License.

About

E2B on AWS

Resources

Code of conduct

Contributing

Security policy

Stars

90 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages