使用代码构建和管理自定义模板

更新时间:
复制 MD 格式

在运行智能体代码或自动化任务时,为避免每次创建沙箱都重复安装依赖与初始化环境,可通过 Python SDK 或阿里云 CLI 调用接口配置自有镜像、执行构建步骤并预置常驻服务,从而直接复用已就绪的模板快照,缩短沙箱启动耗时并统一运行环境。

快速开始

本例使用官方基础镜像,在构建期安装 Python 依赖并写入文件。模板构建完成后,创建沙箱检查依赖版本和文件内容。

准备工作

  1. 开通智能体沙箱,在目标地域创建 Team,获取 Team ID 和用于创建沙箱的 API Key。

  2. 准备阿里云账号或 RAM 用户的访问凭证。模板管理使用阿里云访问凭证,创建沙箱使用 E2B_API_KEY。

  3. 为调用身份授予模板管理权限。以下策略涵盖本文的创建、查询、更新和删除操作:

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

按 Team 授权时,模板资源格式为 acs:sandbox:<region>:<account-id>:teams/<team-id>/templates/*。

安装 SDK:

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

设置环境变量。Team、API Key 和镜像地址均使用同一地域:

export ALIBABA_CLOUD_ACCESS_KEY_ID="<YOUR-ACCESS-KEY-ID>"
export ALIBABA_CLOUD_ACCESS_KEY_SECRET="<YOUR-ACCESS-KEY-SECRET>"
# 使用 STS 临时凭证时设置:
# 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

将以下代码保存为 build_template.py,执行 python3 build_template.py。安装依赖需要构建环境能访问 Python 包仓库。

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. 创建模板,按顺序执行构建步骤。
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. 创建成功表示构建任务已提交,需等待 ready 后再使用模板。
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"模板构建或更新失败({state}): {reason.message if reason else '请保留模板 ID 和 Request ID 排查'}")
    if time.monotonic() >= deadline:
        raise TimeoutError(f"等待构建超时,请用 GetTemplate 继续查询: {template_id}")
    time.sleep(10)

# 3. 创建沙箱,验证构建期安装的依赖和写入的文件。
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()

# 模板可以复用。不再使用时,调用文末的 DeleteTemplate 示例删除。

验证输出应包含 25.0 和 hello-template。后续可以复用打印出的 template_id 创建多个沙箱,无需每次重新构建。

阿里云 CLI

也可以使用阿里云 CLI 调用同一套 Sandbox OpenAPI。安装 阿里云 CLI 和 jq ,沿用前述阿里云凭证、SANDBOX_REGION 和 SANDBOX_TEAM_ID 环境变量。

生成请求文件并创建模板:

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"

创建接口返回后,重复执行以下查询,直到 status.state 为 ready。如果为 error 或 updateFailed,根据 status.reason 排查;不要在模板仍处于构建状态时创建沙箱。

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

模板就绪后,使用返回的模板 ID 创建沙箱,执行 cat /tmp/cli-ready 验证,预期输出为 cli-ready。不再使用模板时删除:

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

使用自有镜像

镜像要求

自有镜像需使用 linux/amd64 架构,支持以下基础系统版本:

系统

支持版本

Ubuntu

22.04、24.04、26.04、26.10

Debian

12(bookworm)、13(trixie)

镜像需保留 systemd、openssh-server、sudo 等系统组件。

  • 保留可写的标准 /etc/passwd、/etc/group 文件。

  • 使用命令执行和终端功能时,保留 /bin/bash。

  • 按工作负载提供 Python、Node.js、CA 证书和其他依赖。

  • 每次修改镜像内容后使用新的 tag,并让模板引用对应 tag。

  • disk_size 包含镜像占用,需要为解压后的镜像和业务写入预留空间。

ACR 企业版镜像(VPC 拉取)

使用与沙箱同账号、同地域的 ACR 企业版实例,并为实例绑定 VPC。镜像地址优先使用带 -vpc 的访问域名;实例的 VPC 绑定需已生效。

用以下配置替换快速开始中的 sandbox_config,显式指定拉取网络,其余创建和轮询流程不变。凭据从环境变量读取;对于 ACR 企业版,也可省略 registry_config.auth_config,由平台自动生成临时拉取凭据。

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>",
        ),
    ),
)

网络约束

  • ACR 企业版实例的访问控制中已添加至少一个专有网络 VPC 绑定,且绑定处于“已生效”状态。沙箱经该绑定在 VPC 内分配的访问 IP 拉取镜像;绑定刚创建存在“生效中”窗口,绑定失效会导致拉取失败,可在实例的访问控制页面确认绑定状态与访问 IP。

  • 拉取网络的 VPC 需为 ACR 企业版实例已绑定的 VPC,且该 VPC 下至少有一个 vSwitch 位于函数计算支持的可用区。

  • ACR 企业版镜像仓库、VPC、vSwitch 与沙箱需位于同一地域。

  • VPC 网段需使用 RFC 1918 规定的私有地址段,即 10.0.0.0/8、172.16.0.0/12 或 192.168.0.0/16,不支持公网私用。

  • VPC 下需至少配置一个自建安全组,其出方向需放行 443/TCP。普通安全组出方向默认允许所有访问(无出方向规则即满足);企业级安全组出方向默认禁止所有访问,需显式添加放行 443/TCP 的出方向规则。

  • 需确保 ACR 企业版实例在 VPC 内存在入口 ENI。如果 ENI 已被删除,可以通过重新绑定 VPC 的方式重新创建。

公网可访问镜像仓库

支持从公网可达且需要鉴权的标准 OCI 镜像仓库拉取镜像,如 GHCR、Docker Hub,以及开放公网 HTTPS 访问的 Harbor。仓库需要使用有效的 HTTPS 证书,且沙箱所在地域能够访问仓库的认证、镜像清单和镜像层下载地址。

  • 通过 registry_config.auth_config 提供具有镜像读取权限的用户名和密码或 Token;平台不会为第三方仓库自动生成凭据。目前暂不支持公网无鉴权仓库。

  • 从中国内地地域访问 GHCR 等海外仓库可能出现连接超时、连接中断或拉取缓慢。对构建稳定性要求较高时,建议将镜像同步到目标地域的 ACR 企业版;也可选择能够稳定访问源仓库的地域构建模板。

例如,将以下配置替换到创建模板请求的 sandbox_config 中:

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"],
        ),
    ),
)

GHCR 私有镜像的密码填写具有 read:packages 权限且能读取目标镜像的 Personal Access Token。完整步骤参见使用 GHCR 自定义镜像构建 Sandbox 模板。

ACR 企业版也可作为第三方公网镜像来源,支持跨账号、跨地域使用。需开启实例公网访问并放行访问控制,通过 registry_config.auth_config 显式提供源仓库的拉取凭据;此方式不配置 registry_config.network_config。

VPC 内自建镜像仓库

二代模板支持从 VPC 内的自建镜像仓库(如 Harbor、Nexus、Docker Registry)拉取镜像,仓库需兼容 OCI 标准。

该能力正在逐地域开放,尚未默认开放的地域需申请白名单。使用前请联系技术支持确认目标地域的开通情况。

仓库通过 HTTPS 443 提供服务。在 registry_config.network_config 中同时指定 vpc_id、v_switch_id 和 security_group_id,确保该网络能够解析仓库域名,并访问仓库的认证、镜像清单和镜像层下载地址。

以下配置替换创建请求的 sandbox_config。仓库需要鉴权时传入 auth_config;允许 VPC 内免鉴权访问时可省略此字段。默认校验证书,使用自签或私有 CA 证书且无法通过默认校验时,可配置 cert_config.insecure=True 跳过证书校验,仅在信任目标仓库和网络时使用。

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>",
        ),
        # 仅在需要跳过目标仓库证书校验时增加:
        # cert_config=models.CreateTemplateRegistryCertConfig(insecure=True),
    ),
)

此配置仅用于拉取镜像,不能用于 steps 构建期访问 VPC 内的资源。

ACR 个人版

ACR 个人版面向个人开发和测试,不提供 SLA 保障或 SLA 赔偿,也不保证镜像拉取和推送速度。不要将其作为生产环境稳定构建的保障,生产环境建议使用 ACR 企业版,参见个人版和企业版实例差异化说明。

个人版仓库需要鉴权时,通过 registry_config.auth_config 显式传入仓库凭据;不要套用 ACR 企业版省略凭据时自动生成临时凭据的规则。

配置构建步骤(steps)

将 steps 放在 runtime_config.sandbox_config 中,平台按数组顺序执行。常见用途包括安装依赖、下载文件、创建目录和写入配置;构建产生的文件会保存到模板中。

支持的步骤

类型

args 写法

用途

USER

["user"]

设置后续步骤的执行用户

WORKDIR

["/home/user/app"]

设置后续步骤的工作目录

ENV

["KEY", "value"],可连续传多组键值对

设置后续构建步骤的环境变量

RUN

["命令"]

执行 Shell 命令

RUN

["命令", "root"]

仅以指定用户执行本条命令

例如,以 root 安装系统依赖,再切回普通用户:

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"]),
]

使用时注意:

  • 需要改变后续步骤的用户、目录或环境变量时,使用对应步骤;只在当前命令内切换时,写在同一条 RUN 中。

  • RUN 用于执行能结束的安装或初始化命令。启动常驻服务请使用启动命令。

  • 不支持 COPY。本地文件可预先打进自定义镜像;远端文件可在 RUN 中通过稳定的 HTTPS 链接下载,链接需对构建环境可达,并在后续重复构建时持续有效。

  • 安装依赖时固定版本,下载资源时固定版本或校验摘要。不要把密钥写进 steps 或模板文件。

启动与就绪命令

启动命令和就绪命令用于在模板中预置已启动的服务,使沙箱创建后即可使用。

启动命令用于在构建模板时启动服务;就绪命令用于检查服务是否可用,返回退出码 0 表示就绪。

服务就绪后,平台保存包含运行中服务的模板快照。基于该模板创建沙箱时,服务已在运行,无需重新启动,也不会再次执行启动命令。

使用限制

  • 启动命令在构建期执行一次;就绪命令也仅在构建期反复执行,直到返回退出码 0。沙箱运行期不会再次执行启动命令或就绪命令。

  • 请配置能够检查服务是否可用的就绪命令。等待就绪最长 5 分钟,超时则构建失败。

执行用户与环境

以下说明适用于 Linux(linux-amd64,默认)模板。

  • 执行身份:默认用户 user,不是 root,也不跟随镜像的 USER。

  • 工作目录:默认 /home/user。命令中请使用绝对路径,不要依赖当前目录。

  • 需要 root 权限时,在命令前加 sudo。平台已配置免密 sudo,镜像需保留 sudo 命令。

  • systemd:运行时以 systemd 作为 PID 1,systemctl 需要以 root 调用,请使用 sudo systemctl。

  • 环境变量:镜像的 OCI ENV 和平台注入的环境变量对启动命令、就绪命令和 commands.run 可见,但不会进入 systemd 及其启动的服务。需要传给 systemd 服务时,请写在单元文件的 Environment= 中。

  • 镜像入口命令:镜像的 ENTRYPOINT 和 CMD 不会执行,常驻服务直接写在启动命令里即可,这是推荐做法。镜像中已经 enabled 的 systemd 服务会自动运行,不要在启动命令中重复启动,否则两个进程会占用同一个端口。

  • 构建期副作用:构建期对文件系统和 systemd 状态的修改都会进入模板快照。

UID 分配和文件属主的细节,参见用户与工作目录。

使用示例

以下示例通过 OpenAPI 创建模板,在启动命令中常驻一个 HTTP 服务,就绪命令探测 8000 端口;构建就绪后用 E2B SDK 创建沙箱并访问该端口。

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. 创建模板并提交构建,把 HTTP 服务固化到模板。
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,
                    # 启动命令在构建期以后台进程执行。
                    start_command="python3 -m http.server 8000 --directory /home/user",
                    # 就绪命令反复执行,退出码只要有一次为 0,即判定就绪。
                    ready_command="curl -sf http://localhost:8000/ > /dev/null",
                ),
            ),
        )
    )
)
template_id = resp.body.template_id

# 2. 轮询构建状态,直到就绪。
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"构建失败: {reason.message if reason else state}")
    if time.time() > deadline:
        raise SystemExit("构建超时")
    time.sleep(10)

# 3. 模板快照已包含运行中的服务,创建沙箱后即可直接访问。
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. 不再使用的模板请及时删除,释放资源。
pop_client.delete_template(
    template_id, models.DeleteTemplateRequest(team_id=TEAM_ID))

在沙箱中运行后台命令

不需要固化到模板的常驻进程,可以在创建沙箱后通过后台命令启动。

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}`);

按需配置

网络配置的作用范围

  • registry_config.network_config:构建期访问镜像来源仓库的网络配置,仅用于拉取镜像。

  • runtime_config.vpc_config:从模板创建的沙箱运行实例所使用的 VPC 网络配置。

需求

配置位置

检查内容

通过 VPC 从 ACR 企业版拉取镜像

sandbox_config.registry_config.network_config

检查实例的 VPC 绑定已生效、访问域名、安全组 443 出方向和拉取凭据

从 VPC 内自建仓库拉取镜像

sandbox_config.registry_config.network_config

检查能力已开通、DNS、路由、安全组、仓库凭据和证书

沙箱运行时访问内网服务

runtime_config.vpc_config

业务服务的连通性和权限

沙箱运行时通过平台出口访问公网

runtime_config.internet_access

是否开启平台公网出口

steps 构建期不支持通过 VPC 访问内网,只能访问公网。registry_config.network_config 仅用于拉取镜像;runtime_config.vpc_config 用于沙箱运行期访问 VPC,不能让 steps 访问内网。构建时需要的依赖或文件,可预先打进镜像,或通过稳定的公网 HTTPS 链接下载。下载链接应在后续重复构建时持续有效,并固定文件版本或校验摘要。

沙箱运行期,internet_access=False 关闭平台公网出口;如果 VPC 自身配置了公网 NAT 网关等出口,仍可能访问公网。

以下示例配置沙箱运行期的 VPC 和公网访问:

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,
)

获取固定公网出口 IP

需要固定出口 IP 时,使用 VPC 的 NAT 网关和 EIP,参见沙箱实例出公网访问(固定 IP)。

安装存储客户端

官方镜像已内置 OSS、AgenticBucket、JuiceFS 和 AgenticFS 的存储客户端,无需重复安装。

需要挂载 OSS、AgenticBucket、JuiceFS 或 AgenticFS,且镜像中没有相应客户端时,在调用 create_template 前,为请求增加:

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

该选项只安装客户端及依赖,不会创建存储资源、执行挂载或授予访问权限。创建沙箱时仍需配置挂载参数,并按存储类型准备网络和凭证。参见挂载 OSS Volume、挂载 AgenticBucket Volume、挂载 JuiceFS Volume、挂载 AgenticFS Volume。

升级存储客户端

平台更新预装的存储客户端后,如需使用新版本,请确保模板已开启 buildConfig.installStorageClients,并重新构建模板。待模板状态变为 ready 后,使用本次构建的模板创建新沙箱。已有沙箱继续使用创建时的客户端版本。

运行日志配置

需要集中查看沙箱运行日志时,先准备同地域的 SLS Project 和 Logstore,并为目标 Logstore 创建索引,再在调用 create_template 前配置:

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

更新与删除模板

以下代码接续快速开始中的 client、TEAM_ID、template_id。

修改构建步骤后,通过 UpdateTemplate 提交更新。请求返回仅表示更新已受理;需继续调用 GetTemplate,等待状态变为 ready 后再创建沙箱。状态为 updateFailed 或 error 时表示更新失败。

steps 省略时保持原配置,传空数组时清空,传非空数组时整体替换原步骤。以下示例会用一条 RUN 替换快速开始中的所有步骤;如果只想追加步骤,需要将原步骤一并传入。

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"]),
                    ],
                ),
            ),
        ),
    ),
)

# 等待本次更新完成。
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_id}")
        break
    if state in ("updateFailed", "error"):
        reason = result.body.status.reason
        raise RuntimeError(
            f"模板更新失败({state}): {reason.message if reason else '请保留模板 ID 和 Request ID 排查'}"
        )
    if time.monotonic() >= deadline:
        raise TimeoutError(f"等待更新超时,请用 GetTemplate 继续查询: {template_id}")
    time.sleep(10)

不再使用模板时删除:

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

排查构建失败

先通过 GetTemplate 获取构建状态和失败原因,再按失败阶段排查。

失败阶段

优先检查

拉取镜像

镜像地址、tag、凭据和连通性;ACR 企业版的 VPC 拉取另检查绑定已生效及 443 出方向;VPC 自建仓库另检查开通情况、DNS、路由与证书

执行 steps

失败的步骤、包名与版本、执行用户、可写目录、下载地址和 DNS

等待服务就绪

服务是否启动、探测地址和端口是否正确;参见本文启动与就绪命令

创建沙箱或挂载存储

模板是否 ready、API Key 与地域、存储客户端、挂载参数和访问权限

保留 template_id、API 返回的 Request ID、失败原因和发生时间;提交排查时同时说明镜像地址与所用 steps。构建提交后建议立即保存 template_id,便于查询或清理失败的模板。