All Products
Search
Document Center

Agent Sandbox:Build a Sandbox template from a GHCR custom image

Last Updated:Oct 20, 2026

Agent Sandbox Flash Edition builds Sandbox templates directly from images in a container registry. Package the language runtime, system dependencies, private SDK, or data science toolchain you need into an image. Building from that image is more controllable and reproducible than installing dependencies one by one on every run.

This topic uses a private image on GitHub Container Registry (GHCR) as an example. The example calls the OpenAPI operation CreateTemplate in the China (Hong Kong) region (cn-hongkong) to build a second-generation (micro) runtime template from ghcr.io/<owner>/<image>:<tag> . It then creates a Sandbox and verifies the result. GHCR is a private registry that requires authentication, so registry credentials must be included when the template is created. Because GHCR is an overseas registry, the build region must be able to access ghcr.io.

Use cases

  • A team packages a unified runtime for Python and Node.js, together with common dependencies, into an image, and multiple Agents share the same base template.

  • Analysis tasks need heavy dependencies such as pandas, numpy, and charting libraries preinstalled once at build time instead of at every run.

  • A private SDK or internal tool is published only to a private GHCR repository and cannot be pulled publicly.

  • Image versions need to be aligned with template versions so builds are traceable and can be rolled back.

Prerequisites

  • Agent Sandbox Flash Edition is activated. Create a Team and obtain the team ID.

  • The Alibaba Cloud account or Resource Access Management (RAM) user that calls the OpenAPI operations has the template API permissions (sandbox:CreateTemplate, sandbox:GetTemplate, and sandbox:DeleteTemplate). For more information about permission configuration, see Build and manage templates.

  • The E2B_API_KEY of the target region is obtained. It is used to create a Sandbox. For more information, see E2B SDK connection parameters.

  • An image is prepared on GHCR. The account and the target region are added to the allowlist of the second-generation runtime (contact technical support if the allowlist is not enabled). The second-generation runtime supports only images based on Ubuntu or Debian, and system components such as systemd, openssh-server, sudo, chrony, fuse3, and iptables must be kept in the image. For the full requirements, see Build and manage templates. The following example shows a minimal Dockerfile that meets the requirements:

    FROM debian:12
    RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
        systemd systemd-sysv openssh-server sudo chrony fuse3 iptables \
        python3 curl ca-certificates \
        && rm -rf /var/lib/apt/lists/*
    CMD ["/sbin/init"]
  • Registry credentials that can pull the image are prepared. For more information, see Registry credentials.

  • Install the Agent Sandbox Flash Edition OpenAPI SDK and the E2B SDK:

pip install alibabacloud_sandbox20260820 e2b==2.31.0

Registry credentials

Pulling an image from a private GHCR repository requires a username and a password. The credential here is a GitHub Personal Access Token (classic), not your account login password:

  • Username: Your GitHub username (the owner that the image belongs to).

  • Password: The value of the Personal Access Token (classic) you created (in the form ghp_xxxxxxxx).

Token permission requirements: The token only requires the read:packages scope. In addition, the account that owns the token must have read permission on the private package. If the image belongs to an organization that enforces SSO (single sign-on) authorization, you must also authorize that organization on the token page. Missing these permissions causes the image pull to fail during the build (authentication 401 or 403; see the GitHub documentation).

To create the token, go to GitHub → Settings → Developer settings → Personal access tokens → Tokens (classic) → Generate new token (classic), and select read:packages in Select scopes.

The credentials are passed in the CreateTemplate request body at runtime_config.sandbox_config.registry_config.auth_config:

Parameter

Meaning

Value

user_name

Registry username

GitHub username

password

Registry password

Personal Access Token (classic)

Credentials are sensitive. Inject them through environment variables or a secrets manager, and do not hardcode them in code or commit them to a repository.

Recommended workflow

Split "custom image → template → Sandbox" into four steps:

  1. Call CreateTemplate to create a template. Set sandbox_config.image to the GHCR image address, set generation to 2 (the second-generation micro runtime), and pass the registry credentials in registry_config.auth_config to obtain template_id.

  2. Poll GetTemplate until the build reaches a terminal state (ready or error).

  3. Create a Sandbox with the template_id, wait for the data plane to be ready, then run a command as a smoke test.

  4. Destroy the Sandbox after the verification passes to avoid holding resources for a long time. Call DeleteTemplate to delete the template when you confirm that it is no longer in use.

Building the template is a one-time action: the template_id built from an image can be reused by many subsequent Sandbox.create calls. In production, separate build and run into two stages instead of rebuilding on every run.

Example code

The following example builds a second-generation runtime template from the private GHCR image ghcr.io/<owner>/<image>:<tag>, creates a Sandbox, runs a command that prints the verification marker, and finally destroys the Sandbox. The Alibaba Cloud AccessKey pair, the registry credentials, and E2B_API_KEY are all read from environment variables.

Important

The unit of cpu is cores, and the units of memory_size and disk_size are MB. All three parameters are optional. If you leave them empty, the default specifications of 2 cores, 2,048 MB of memory, and 15,360 MB of disk are used. Insufficient specifications cause the template build or the Sandbox startup to fail. If the memory is insufficient, processes inside the image are terminated by the out of memory (OOM) killer. If the CPU is insufficient, the build and cold start slow down. If the disk is insufficient, file writes fail. For the second-generation runtime (when generation is 2), the configured disk size includes the space occupied by the image itself. The writable space therefore equals disk_size minus the image size. Set the value based on the uncompressed image size plus the peak memory and disk writes of the workload, and leave headroom.

import os
import time

from alibabacloud_sandbox20260820 import models
from alibabacloud_sandbox20260820.client import Client as SandboxClient
from alibabacloud_tea_openapi import models as open_api_models
from e2b import Sandbox

REGION = "cn-hongkong"
POP_ENDPOINT = f"sandbox.{REGION}.aliyuncs.com"
API_URL = f"https://api.{REGION}.sandbox.aliyuncs.com"
DOMAIN = f"{REGION}.sandbox.aliyuncs.com"
SOURCE_IMAGE = "ghcr.io/<owner>/<image>:<tag>"
SANDBOX_MARKER = "sandbox-ok"
READY_TIMEOUT_SECONDS = 90
READY_INTERVAL_SECONDS = 3


def required_env(name: str) -> str:
    value = os.environ.get(name, "").strip()
    if not value:
        raise RuntimeError(f"Missing environment variable: {name}")
    return value


def main() -> int:
    team_id = required_env("SANDBOX_TEAM_ID")
    pop_client = SandboxClient(
        open_api_models.Config(
            access_key_id=required_env("ALIBABA_CLOUD_ACCESS_KEY_ID"),
            access_key_secret=required_env("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),
            region_id=REGION,
            endpoint=POP_ENDPOINT,
        )
    )

    # 1. Create the template: second-generation micro runtime + private GHCR image + registry credentials. The first build starts right after the template is created.
    response = pop_client.create_template(
        models.CreateTemplateRequest(
            body=models.CreateTemplateInput(
                name=f"ghcr-demo-{int(time.time())}",
                team_id=team_id,
                runtime_config=models.CreateTemplateRuntimeConfig(
                    cpu=2,
                    memory_size=2048,
                    disk_size=15360,
                    sandbox_config=models.CreateTemplateSandboxConfig(
                        image=SOURCE_IMAGE,
                        generation=2,
                        registry_config=models.CreateTemplateRegistryConfig(
                            auth_config=models.CreateTemplateRegistryAuthConfig(
                                user_name=required_env("GHCR_USERNAME"),
                                password=required_env("GHCR_PASSWORD"),
                            ),
                        ),
                    ),
                ),
            )
        )
    )
    template_id = response.body.template_id
    print(f"template_id={template_id}")

    # 2. Poll GetTemplate until the build reaches a terminal state
    deadline = time.time() + 900
    while True:
        got = pop_client.get_template(template_id, models.GetTemplateRequest(team_id=team_id))
        state = got.body.status.state
        print(f"state={state}")
        if state == "ready":
            break
        if state == "error":
            reason = got.body.status.reason.message if got.body.status.reason else ""
            raise RuntimeError(f"Build failed: {reason}")
        if time.time() > deadline:
            raise RuntimeError("Build timed out")
        time.sleep(10)

    # 3. Create a Sandbox with the template_id
    sandbox = Sandbox.create(
        template=template_id,
        timeout=900,
        api_key=required_env("E2B_API_KEY"),
        api_url=API_URL,
        domain=DOMAIN,
    )
    print(f"sandbox_id={sandbox.sandbox_id}")

    try:
        # Wait for the data plane to be ready, then run a smoke test
        last_error = None
        deadline = time.monotonic() + READY_TIMEOUT_SECONDS
        while True:
            remaining = deadline - time.monotonic()
            if remaining <= 0:
                raise RuntimeError(f"Timed out waiting for the data plane: {last_error}") from last_error
            try:
                result = sandbox.commands.run(f"echo {SANDBOX_MARKER}", timeout=min(60, remaining))
                break
            except Exception as err:
                last_error = err
                time.sleep(min(READY_INTERVAL_SECONDS, max(deadline - time.monotonic(), 0)))
        if result.exit_code != 0 or SANDBOX_MARKER not in result.stdout:
            raise RuntimeError(f"Verification failed: exit={result.exit_code}, stdout={result.stdout}")
        print(f"stdout={result.stdout.strip()}")
    finally:
        # 4. Destroy the Sandbox
        sandbox.kill()

    # The template can be reused for a long time. Delete the template to release resources when it is no longer in use.
    # pop_client.delete_template(template_id, models.DeleteTemplateRequest(team_id=team_id))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

To run the example, export the credentials as environment variables:

export ALIBABA_CLOUD_ACCESS_KEY_ID="<your-access-key-id>"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="<your-access-key-secret>"
export SANDBOX_TEAM_ID="<your-team-id>"
export GHCR_USERNAME="<github-username>"
export GHCR_PASSWORD="ghp_xxxxxxxxxxxxxxxxxxxx"   # Personal Access Token (classic)
export E2B_API_KEY="<your-e2b-api-key>"
python3 build_from_ghcr.py

On success, the output prints template_id, the build state, sandbox_id, and the verification marker sandbox-ok in order. The script destroys the Sandbox at the end.

Production recommendations

  • Credential management: Inject the GitHub Personal Access Token (classic), the Alibaba Cloud AccessKey pair, and E2B_API_KEY through environment variables or a secrets manager. Never write them into code or commit them to Git. Follow the principle of least privilege for token scopes. Select only read:packages, and rotate tokens regularly.

  • Separate build and run: Building a template is a one-time action. Persist and reuse the resulting template_id, and do not rebuild before every Sandbox creation.

  • Version your images: Use explicit image tags (do not rely only on latest) so templates and images stay aligned, traceable, and rollback-friendly.

  • Resource specifications: Size cpu (in cores), memory_size (in MB), and disk_size based on the workload inside the image. The default specifications are used if you leave them empty.

  • Destroy promptly: Call sandbox.kill() when the task finishes (in a finally block) to avoid a Sandbox holding resources on error paths. Call DeleteTemplate to delete the template when you confirm that it is no longer in use.