Build and manage custom templates with code

Updated at:

Use the Python SDK or Alibaba Cloud CLI to configure a custom image, run build steps, and pre-deploy resident services for Agent Sandbox custom templates. Each sandbox then reuses a ready template snapshot instead of reinstalling dependencies and reinitializing the environment, which shortens startup time and standardizes the runtime environment.

Quick start

This example uses the official base image, installs Python dependencies, and writes a file during the build. After the template is built, create a sandbox to check the dependency version and the file content.

Before you begin

  1. Activate Agent Sandbox, create a Team in the destination region, and obtain the Team ID and the API key that is used to create sandboxes.

  2. Prepare the access credentials of an Alibaba Cloud account or a Resource Access Management (RAM) user. Template management uses Alibaba Cloud access credentials, whereas sandbox creation uses E2B_API_KEY.

  3. Grant the template management permissions to the calling identity. The following policy covers the create, query, update, and delete operations in this topic:

    {
      "Version": "1",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": [
            "sandbox:CreateTemplate",
            "sandbox:GetTemplate",
            "sandbox:ListTemplates",
            "sandbox:UpdateTemplate",
            "sandbox:DeleteTemplate"
          ],
          "Resource": "*"
        }
      ]
    }

To grant permissions by Team, specify the template resource in the format acs:sandbox:<region>:<account-id>:teams/<team-id>/templates/*.

Install the SDK:

python3 -m venv .venv
source .venv/bin/activate
pip install alibabacloud_sandbox20260820==1.2.3 e2b==2.31.0

Set the environment variables. The Team, the API key, and the image address all use the same region:

export ALIBABA_CLOUD_ACCESS_KEY_ID="<YOUR-ACCESS-KEY-ID>"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="<YOUR-ACCESS-KEY-SECRET>"
# Set the following when you use a Security Token Service (STS) temporary credential:
# export ALIBABA_CLOUD_SECURITY_TOKEN="<YOUR-SECURITY-TOKEN>"
export SANDBOX_REGION="cn-hangzhou"
export SANDBOX_TEAM_ID="<YOUR-TEAM-ID>"
export E2B_API_KEY="<YOUR-E2B-API-KEY>"

Python SDK

Save the following code as build_template.py and run python3 build_template.py. To install dependencies, the build environment must be able to access the Python package repository.

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 = os.environ["SANDBOX_REGION"]
TEAM_ID = os.environ["SANDBOX_TEAM_ID"]

client = SandboxClient(
    open_api_models.Config(
        access_key_id=os.environ["ALIBABA_CLOUD_ACCESS_KEY_ID"],
        access_key_secret=os.environ["ALIBABA_CLOUD_ACCESS_KEY_SECRET"],
        security_token=os.environ.get("ALIBABA_CLOUD_SECURITY_TOKEN"),
        region_id=REGION,
        endpoint=f"sandbox.{REGION}.aliyuncs.com",
    )
)

# 1. Create the template. The build steps run in the specified order.
request = models.CreateTemplateRequest(
    body=models.CreateTemplateInput(
        name=f"steps-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=f"fc-e2b-registry.{REGION}.cr.aliyuncs.com/runtime-v2/base:v0.1.5",
                generation=2,
                steps=[
                    models.CreateTemplateStep(type="USER", args=["user"]),
                    models.CreateTemplateStep(type="WORKDIR", args=["/home/user"]),
                    models.CreateTemplateStep(type="ENV", args=["APP_MESSAGE", "hello-template"]),
                    models.CreateTemplateStep(
                        type="RUN",
                        args=[
                            "python3 -m venv /home/user/app-venv && "
                            "/home/user/app-venv/bin/pip install packaging==25.0"
                        ],
                    ),
                    models.CreateTemplateStep(
                        type="RUN",
                        args=["printf '%s\\n' \"$APP_MESSAGE\" > /home/user/message.txt"],
                    ),
                ],
            ),
        ),
    )
)
response = client.create_template(request)
template_id = response.body.template_id
print(f"template_id={template_id}")

# 2. A successful create call only submits the build task. Wait for the ready state before you use the template.
deadline = time.monotonic() + 1200
while True:
    result = client.get_template(template_id, models.GetTemplateRequest(team_id=TEAM_ID))
    state = result.body.status.state
    print(f"state={state}")
    if state == "ready":
        break
    if state in ("error", "updateFailed"):
        reason = result.body.status.reason
        raise RuntimeError(f"Template build or update failed ({state}): {reason.message if reason else 'Keep the template ID and the Request ID for troubleshooting'}")
    if time.monotonic() >= deadline:
        raise TimeoutError(f"Timed out waiting for the build. Query again by using GetTemplate: {template_id}")
    time.sleep(10)

# 3. Create a sandbox and verify the dependencies that are installed and the files that are written during the build.
sandbox = Sandbox.create(
    template=template_id,
    api_key=os.environ["E2B_API_KEY"],
    api_url=f"https://api.{REGION}.sandbox.aliyuncs.com",
    domain=f"{REGION}.sandbox.aliyuncs.com",
    timeout=300,
)
try:
    check = sandbox.commands.run(
        "/home/user/app-venv/bin/python -c 'import packaging; print(packaging.__version__)' "
        "&& cat /home/user/message.txt"
    )
    print(check.stdout)
finally:
    sandbox.kill()

# The template is reusable. When you no longer use it, delete it with the DeleteTemplate example at the end of this topic.

The verification output must contain 25.0 and hello-template. Reuse the printed template_id to create multiple sandboxes without rebuilding the template each time.

Alibaba Cloud CLI

Alternatively, call the same Sandbox OpenAPI operations by using Alibaba Cloud CLI. Install Alibaba Cloud CLI and jq, and reuse the Alibaba Cloud credentials, SANDBOX_REGION and SANDBOX_TEAM_ID environment variables.

Generate the request file and create the template:

jq -n \
  --arg team "$SANDBOX_TEAM_ID" \
  --arg name "steps-cli-$(date +%s)" \
  --arg image "fc-e2b-registry.${SANDBOX_REGION}.cr.aliyuncs.com/runtime-v2/base:v0.1.5" \
  '{
    teamID: $team,
    name: $name,
    runtimeConfig: {
      cpu: 2,
      memorySize: 2048,
      diskSize: 15360,
      sandboxConfig: {
        generation: 2,
        image: $image,
        steps: [{type: "RUN", args: ["echo cli-ready > /tmp/cli-ready", "root"]}]
      }
    }
  }' > create-template.json

TEMPLATE_ID=$(aliyun sandbox CreateTemplate \
  --version 2026-08-20 \
  --region "$SANDBOX_REGION" \
  --endpoint "sandbox.${SANDBOX_REGION}.aliyuncs.com" \
  --body "$(cat create-template.json)" | jq -er '.templateID')

echo "$TEMPLATE_ID"

After the CreateTemplate operation returns, run the following query repeatedly until status.state is ready. If the state is error or updateFailed, troubleshoot the issue based on status.reason. Do not create a sandbox while the template is still being built.

aliyun sandbox GetTemplate \
  --version 2026-08-20 \
  --region "$SANDBOX_REGION" \
  --endpoint "sandbox.${SANDBOX_REGION}.aliyuncs.com" \
  --templateID "$TEMPLATE_ID" \
  --teamID "$SANDBOX_TEAM_ID"

After the template is ready, use the returned template ID to create a sandbox and run cat /tmp/cli-ready for verification. The expected output is cli-ready. Delete the template when you no longer use it:

aliyun sandbox DeleteTemplate \
  --version 2026-08-20 \
  --region "$SANDBOX_REGION" \
  --endpoint "sandbox.${SANDBOX_REGION}.aliyuncs.com" \
  --templateID "$TEMPLATE_ID" \
  --teamID "$SANDBOX_TEAM_ID"

Use a custom image

Image requirements

A custom image must use the linux/amd64 architecture. The following base operating system versions are supported:

Operating system

Supported versions

Ubuntu

22.04, 24.04, 26.04, 26.10

Debian

12 (bookworm), 13 (trixie)

The image must retain system components such as systemd, openssh-server, and sudo.

  • Retain writable standard /etc/passwd and /etc/group files.

  • To use the command execution and terminal features, retain /bin/bash.

  • Provide Python, Node.js, certificate authority (CA) certificates, and other dependencies based on the workload.

  • Use a new tag each time you change the image content, and make the template reference that tag.

  • disk_size includes the space that the image occupies. Reserve enough space for the decompressed image and for business writes.

ACR EE image (pulling over a VPC)

Use a Container Registry Enterprise Edition (ACR EE) instance that belongs to the same Alibaba Cloud account and region as the sandbox, and associate a virtual private cloud (VPC) with the instance. In the image address, prefer the access domain name that contains -vpc. The VPC association of the instance must be in effect.

Replace sandbox_config in the quick start with the following configuration to explicitly specify the pull network. The rest of the creation and polling process remains unchanged. The credentials are read from environment variables. For ACR EE, registry_config.auth_config can also be omitted so that the platform automatically generates a temporary pull credential.

sandbox_config = models.CreateTemplateSandboxConfig(
    image="<instance>-registry-vpc.cn-hangzhou.cr.aliyuncs.com/<namespace>/<image>:<tag>",
    generation=2,
    registry_config=models.CreateTemplateRegistryConfig(
        auth_config=models.CreateTemplateRegistryAuthConfig(
            user_name=os.environ["REGISTRY_USERNAME"],
            password=os.environ["REGISTRY_PASSWORD"],
        ),
        network_config=models.CreateTemplateRegistryNetworkConfig(
            vpc_id="<vpc-id>",
            v_switch_id="<vsw-id>",
            security_group_id="<sg-id>",
        ),
    ),
)

Network constraints

  • At least one VPC association is added on the Access Control page of the ACR EE instance, and the association is in the Active state. The sandbox pulls images over the access IP address assigned in the associated VPC. A newly created association remains in the Activating state for a period of time, and an expired association causes the pull to fail. Check the association status and the access IP address on the Access Control page of the instance.

  • The VPC of the pull network must be a VPC associated with the ACR EE instance. At least one vSwitch in the VPC must be located in a zone supported by Function Compute.

  • The ACR EE image repository, VPC, vSwitch, and sandbox must be located in the same region.

  • The classless inter-domain routing (CIDR) block of the VPC must use a private address range specified in RFC 1918, which is 10.0.0.0/8, 172.16.0.0/12, or 192.168.0.0/16. A public address range cannot be used as a private address range.

  • At least one custom security group must be configured for the VPC, and its outbound direction must allow TCP port 443. By default, the outbound direction of a basic security group allows all access, so no outbound rule is required. By default, the outbound direction of an enterprise security group denies all access, so an outbound rule that allows TCP port 443 must be added.

  • Make sure that the ACR EE instance has an inbound elastic network interface (ENI) in the VPC. If the ENI is deleted, you can re-associate the VPC to recreate the ENI.

Internet-accessible image repository

Pull images from standard Open Container Initiative (OCI) image repositories that are accessible over the Internet and require authentication. Supported sources include GitHub Container Registry (GHCR), Docker Hub, and Harbor instances that expose HTTPS access over the Internet. The repository must use a valid HTTPS certificate, and the region of the sandbox must be able to access the authentication, manifest, and blob download endpoints of the repository.

  • Set registry_config.auth_config to a username and a password or a token that has the image read permission. The platform does not automatically generate credentials for third-party repositories. Repositories that are accessible over the Internet without authentication are not currently supported.

  • When you access an overseas repository such as GHCR from a region in the Chinese mainland, the connection may time out or be interrupted, or the pull may be slow. If you require high build stability, synchronize the image to an ACR EE instance in the destination region. Alternatively, build the template in a region that can stably access the source repository.

For example, replace sandbox_config in the CreateTemplate request with the following configuration:

sandbox_config = models.CreateTemplateSandboxConfig(
    image="ghcr.io/<owner>/<image>:<tag>",
    generation=2,
    registry_config=models.CreateTemplateRegistryConfig(
        auth_config=models.CreateTemplateRegistryAuthConfig(
            user_name=os.environ["GHCR_USERNAME"],
            password=os.environ["GHCR_TOKEN"],
        ),
    ),
)

For a private GHCR image, use a personal access token as the password. The token must have the read:packages permission and be able to read the destination image. For the complete procedure, see Build a Sandbox template from a GHCR custom image.

ACR EE can also serve as a third-party public image source across accounts and regions. Enable Internet access for the instance, allow access on the Access Control page, and provide the pull credentials of the source repository explicitly in registry_config.auth_config. This method does not configure registry_config.network_config.

Self-managed image repository in a VPC

Second-generation templates support pulling images from self-managed image repositories in a VPC, such as Harbor, Nexus, and Docker Registry. The repository must be compatible with the OCI standard.

This feature is being rolled out region by region. Regions where it is not enabled by default require whitelist access. Before you use this feature, contact technical support to confirm the availability in the destination region.

The repository provides services over HTTPS port 443. In registry_config.network_config, specify vpc_id, v_switch_id, and security_group_id together. Make sure that the network can resolve the repository domain name and access the authentication, manifest, and blob download endpoints of the repository.

The following configuration replaces sandbox_config. Specify auth_config if the repository requires authentication, and omit this field if the repository allows access without authentication inside the VPC. Certificates are verified by default. If the repository uses a self-signed certificate or a certificate issued by a private CA and fails the default verification, you can set cert_config.insecure=True to skip certificate verification. Use this setting only if you trust the destination repository and network.

sandbox_config = models.CreateTemplateSandboxConfig(
    image="registry.example.internal/<namespace>/<image>:<tag>",
    generation=2,
    registry_config=models.CreateTemplateRegistryConfig(
        auth_config=models.CreateTemplateRegistryAuthConfig(
            user_name=os.environ["REGISTRY_USERNAME"],
            password=os.environ["REGISTRY_PASSWORD"],
        ),
        network_config=models.CreateTemplateRegistryNetworkConfig(
            vpc_id="<vpc-id>",
            v_switch_id="<vsw-id>",
            security_group_id="<sg-id>",
        ),
        # Add the following only if you need to skip certificate verification of the target repository:
        # cert_config=models.CreateTemplateRegistryCertConfig(insecure=True),
    ),
)

This configuration is used only to pull images. It does not allow steps to access resources in the VPC during the build.

ACR Personal Edition

ACR Personal Edition is intended for individual development and testing, but does not provide Service Level Agreement (SLA) guarantees or SLA compensation, and does not guarantee image pull or push speeds. Do not rely on it for stable builds in production environments. Use ACR EE in production environments. For more information, see Differences between Personal and Enterprise Edition instances.

If a Personal Edition repository requires authentication, pass the repository credentials explicitly in registry_config.auth_config. The rule that the platform automatically generates a temporary credential when the ACR EE credentials are omitted does not apply.

Configure build steps (steps)

Put steps in runtime_config.sandbox_config. The platform runs the steps in the order of the array. Common uses include installing dependencies, downloading files, creating directories, and writing configurations. Files generated during the build are saved to the template.

Supported steps

Type

Format of args

Purpose

USER

["user"]

Sets the user that runs the subsequent steps

WORKDIR

["/home/user/app"]

Sets the working directory of the subsequent steps

ENV

["KEY", "value"]. Pass multiple key-value pairs in sequence

Sets the environment variables for the subsequent build steps

RUN

["command"]

Runs a shell command

RUN

["command", "root"]

Runs only this command as the specified user

For example, install system dependencies as the root user, and then switch back to a regular user:

steps = [
    models.CreateTemplateStep(
        type="RUN",
        args=["apt-get update && apt-get install -y git ca-certificates", "root"],
    ),
    models.CreateTemplateStep(type="USER", args=["user"]),
    models.CreateTemplateStep(type="WORKDIR", args=["/home/user/app"]),
    models.CreateTemplateStep(type="ENV", args=["APP_ENV", "production", "LANG", "C.UTF-8"]),
    models.CreateTemplateStep(type="RUN", args=["printf '%s\\n' \"$APP_ENV\" > app.env"]),
]

Take note of the following items:

  • To change the user, working directory, or environment variables of the subsequent steps, use the corresponding step. If the change applies only to the current command, write it in the same RUN step.

  • RUN is used for installation or initialization commands that can finish. To start a resident service, use the start command.

  • The COPY step is not supported. Package local files into the custom image in advance. Download remote files in a RUN step over a stable HTTPS link. The link must be reachable from the build environment and remain valid for later rebuilds.

  • Pin versions when you install dependencies, and pin the version or verify the digest when you download resources. Do not write secrets into steps or template files.

Start and ready commands

The start command and the ready command pre-deploy a running service in the template, so that the service is available immediately after a sandbox is created.

The start command starts the service during the template build. The ready command checks whether the service is available. An exit code of 0 indicates that the service is ready.

After the service is ready, the platform saves a template snapshot that contains the running service. When you create a sandbox from this template, the service is already running, does not need to be started again, and the start command is not run again.

Limits

  • The start command runs once during the build. The ready command also runs repeatedly only during the build, until it returns the exit code 0. Neither command runs again during the sandbox runtime.

  • Configure a ready command that can check whether the service is available. The wait for readiness lasts up to 5 minutes. If the wait times out, the build fails.

Execution user and environment

The following descriptions apply to Linux (linux-amd64, default) templates.

  • Execution identity: The default user is user, not the root user. The USER instruction of the image does not take effect.

  • Working directory: The default value is /home/user. Use absolute paths in commands and do not rely on the current directory.

  • If root permissions are required, prefix the command with sudo. The platform is configured with passwordless sudo, and the image must retain the sudo command.

  • systemd: The runtime uses systemd as process identifier (PID) 1. systemctl must be called as the root user, so use sudo systemctl.

  • Environment variables: The OCI ENV instructions of the image and the environment variables injected by the platform are visible to the start command, the ready command, and commands.run. They are not passed to systemd or to the services that systemd starts. To pass variables to a systemd service, write them in the Environment= directive of the unit file.

  • Image entry command: The ENTRYPOINT and CMD instructions of the image are not executed. Write the resident service directly in the start command, which is the recommended practice. The systemd services that are already enabled in the image run automatically. Do not start them again in the start command. Otherwise, two processes occupy the same port.

  • Build-time side effects: The changes that the build makes to the file system and to the systemd state are included in the template snapshot.

For more information about UID allocation and file owners, see User and Working Directory.

Example

The following example creates a template by using OpenAPI, runs a resident HTTP service in the start command, and probes port 8000 in the ready command. After the build is ready, use the E2B SDK to create a sandbox and access the port:

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 = os.environ["SANDBOX_REGION"]
TEAM_ID = os.environ["SANDBOX_TEAM_ID"]

config = open_api_models.Config(
    access_key_id=os.environ["ALIBABA_CLOUD_ACCESS_KEY_ID"],
    access_key_secret=os.environ["ALIBABA_CLOUD_ACCESS_KEY_SECRET"],
    security_token=os.environ.get("ALIBABA_CLOUD_SECURITY_TOKEN"),
    region_id=REGION,
    endpoint=f"sandbox.{REGION}.aliyuncs.com",
)
pop_client = SandboxClient(config)

# 1. Create the template and submit the build, which captures the HTTP service in the template.
resp = pop_client.create_template(
    models.CreateTemplateRequest(
        body=models.CreateTemplateInput(
            name=f"my-service-{int(time.time())}",
            team_id=TEAM_ID,
            runtime_config=models.CreateTemplateRuntimeConfig(
                cpu=2,
                memory_size=4096,
                disk_size=15360,
                sandbox_config=models.CreateTemplateSandboxConfig(
                    image=f"fc-e2b-registry.{REGION}.cr.aliyuncs.com/runtime-v2/base:v0.1.5",
                    generation=2,
                    # The start command runs as a background process during the build.
                    start_command="python3 -m http.server 8000 --directory /home/user",
                    # The ready command runs repeatedly. An exit code of 0 once means the service is ready.
                    ready_command="curl -sf http://localhost:8000/ > /dev/null",
                ),
            ),
        )
    )
)
template_id = resp.body.template_id

# 2. Poll the build status until the template is ready.
deadline = time.time() + 900
while True:
    got = pop_client.get_template(
        template_id, models.GetTemplateRequest(team_id=TEAM_ID))
    state = got.body.status.state
    if state == "ready":
        break
    if state in ("error", "updateFailed"):
        reason = got.body.status.reason
        raise SystemExit(f"Build failed: {reason.message if reason else state}")
    if time.time() > deadline:
        raise SystemExit("Build timed out")
    time.sleep(10)

# 3. The template snapshot already contains the running service, so the new sandbox can access it directly.
sandbox = Sandbox.create(
    template=template_id,
    api_key=os.environ["E2B_API_KEY"],
    timeout=600,
    api_url=f"https://api.{REGION}.sandbox.aliyuncs.com",
    domain=f"{REGION}.sandbox.aliyuncs.com",
)
try:
    check = sandbox.commands.run("curl -fsS http://localhost:8000/ > /dev/null")
    assert check.exit_code == 0, check.stderr
    print(f"https://{sandbox.get_host(8000)}")
finally:
    sandbox.kill()

# 4. Delete the templates that you no longer use to release resources.
pop_client.delete_template(
    template_id, models.DeleteTemplateRequest(team_id=TEAM_ID))

Run background commands in a sandbox

For a resident process that does not need to be captured in the template, start it with a background command after the sandbox is created.

Python

server = sandbox.commands.run(
    "python3 -m http.server 8000",
    background=True,
)

host = sandbox.get_host(8000)
print(f"https://{host}")

TypeScript

const server = await sandbox.commands.run("python3 -m http.server 8000", {
  background: true,
});

const host = sandbox.getHost(8000);
console.log(`https://${host}`);

Configure as needed

Scope of the network configurations

  • registry_config.network_config: the network configuration used to access the source image repository during the build. It is used only to pull images.

  • runtime_config.vpc_config: the VPC network configuration that is used by the sandbox instances created from the template.

Requirement

Configuration location

Items to check

Pull images from ACR EE over a VPC

sandbox_config.registry_config.network_config

The VPC association of the instance is in effect, the access domain name, the outbound rule for port 443 of the security group, and the pull credentials

Pull images from a self-managed repository in a VPC

sandbox_config.registry_config.network_config

The availability of the feature, DNS, routes, the security group, the repository credentials, and the certificate

Access internal services during the sandbox runtime

runtime_config.vpc_config

The connectivity and permissions of the business service

Access the Internet over the platform egress during the sandbox runtime

runtime_config.internet_access

Whether the platform Internet egress is enabled

Steps cannot access internal resources over a VPC during the build. Only the Internet is accessible. registry_config.network_config is used only to pull images. runtime_config.vpc_config is used by the sandbox runtime to access the VPC, and it cannot let steps access internal resources. Package the dependencies or files that the build requires into the image in advance, or download them over a stable public HTTPS link. The link must remain valid for later rebuilds, and the file version or the digest must be pinned.

During the sandbox runtime, internet_access=False disables the platform Internet egress. If the VPC itself provides an Internet egress such as an Internet NAT gateway, the Internet may still be accessible.

The following example configures VPC and Internet access for the sandbox runtime:

runtime_config = models.CreateTemplateRuntimeConfig(
    cpu=2,
    memory_size=2048,
    disk_size=15360,
    sandbox_config=sandbox_config,
    vpc_config=models.CreateTemplateVPCConfig(
        vpc_id="<vpc-id>",
        v_switch_ids=["<vsw-id>"],
        security_group_id="<sg-id>",
    ),
    internet_access=True,
)

Obtain a fixed Internet egress IP address

To obtain a fixed egress IP address, use the Internet NAT gateway and the elastic IP address (EIP) of the VPC. For more information, see Configure a fixed public IP for a sandbox instance.

Install storage clients

The official images include the storage clients for Object Storage Service (OSS), AgenticBucket, JuiceFS, and AgenticFS. You do not need to install them again.

To mount OSS, AgenticBucket, JuiceFS, or AgenticFS when the image does not include the corresponding client, add the following to the request before you call create_template:

build_config = models.CreateTemplateBuildConfig(install_storage_clients=True)
request.body.build_config = build_config

This option installs only the clients and their dependencies. It does not create storage resources, perform mounts, or grant access permissions. When you create a sandbox, you must still configure the mount parameters, and prepare the network and the credentials for the storage type. For more information, see Mount an OSS Volume, Mount an AgenticBucket Volume, Mount a JuiceFS Volume, and Mount an AgenticFS Volume.

Runtime log configuration

To centrally view sandbox runtime logs, prepare a Simple Log Service (SLS) project and Logstore in the same region, and create an index for the destination Logstore (see Create indexes). Then, before you call create_template, configure the following:

log_config = models.CreateTemplateLogConfig(
    project="<sls-project>",
    logstore="<sls-logstore>",
)
request.body.runtime_config.log_config = log_config

Update and delete templates

The following code continues from the client, TEAM_ID, and template_id variables in the quick start.

After you change the build steps, submit the update by using UpdateTemplate. A successful response only indicates that the update is accepted. Continue to call GetTemplate and wait until the state changes to ready before you create a sandbox. The state updateFailed or error indicates that the update failed.

steps is kept unchanged when it is omitted, is cleared when you pass an empty array, and is fully replaced when you pass a non-empty array. The following example replaces all the steps in the quick start with a single RUN step. To append steps instead, pass the original steps together with the new ones.

import time

client.update_template(
    template_id,
    models.UpdateTemplateRequest(
        team_id=TEAM_ID,
        body=models.PublicUpdateTemplateInput(
            runtime_config=models.PublicUpdateTemplateRuntimeConfig(
                sandbox_config=models.PublicUpdateTemplateSandboxConfig(
                    steps=[
                        models.PublicUpdateTemplateStep(type="RUN", args=["touch /home/user/updated.txt"]),
                    ],
                ),
            ),
        ),
    ),
)

# Wait until this update is complete.
deadline = time.monotonic() + 900
while True:
    result = client.get_template(
        template_id, models.GetTemplateRequest(team_id=TEAM_ID)
    )
    state = result.body.status.state
    print(f"state={state}")
    if state == "ready":
        print(f"Template updated: {template_id}")
        break
    if state in ("updateFailed", "error"):
        reason = result.body.status.reason
        raise RuntimeError(
            f"Template update failed ({state}): {reason.message if reason else 'Keep the template ID and the Request ID for troubleshooting'}"
        )
    if time.monotonic() >= deadline:
        raise TimeoutError(f"Timed out waiting for the update. Query again by using GetTemplate: {template_id}")
    time.sleep(10)

Delete the template when you no longer use it:

client.delete_template(template_id, models.DeleteTemplateRequest(team_id=TEAM_ID))

Troubleshoot build failures

Query the build status and the failure cause by using GetTemplate first, and then troubleshoot by failure stage.

Failure stage

Items to check first

Image pull

The image address, tag, credentials, and connectivity. For an ACR EE pull over a VPC, also check that the VPC association is in effect and that the outbound direction allows port 443. For a self-managed repository in a VPC, also check the availability of the feature, DNS, routes, and the certificate

Step execution

The failed step, the package names and versions, the execution user, the writable directories, the download URL, and DNS

Waiting for the service to be ready

Whether the service has started, and whether the probe address and port are correct. For more information, see Start and ready commands

Sandbox creation or storage mount

Whether the template is ready, the API key and the region, the storage clients, the mount parameters, and the access permissions

Keep the template_id, the Request ID that the API returns, the failure cause, and the time of the failure. When you submit the issue for troubleshooting, also provide the image address and the steps that you use. After the build is submitted, save the template_id so that you can query or clean up failed templates.