Dynamic OSS mounts

Updated at:

Mount a specified Object Storage Service (OSS) Bucket or subdirectory into a local directory inside a Sandbox at creation time. After mounting, the Sandbox reads and writes the mounted directory like a local file system. This is suitable for reading input data, saving task artifacts, and persisting files across tasks.

Dynamic OSS mounts are configured through Sandbox metadata, so the template does not need to contain the mount configuration. When creating a Sandbox, pass:

  • fc.sandbox.storage.oss: OSS mount configuration, as a JSON string.

  • fc.sandbox.auth.role: The RAM Role ARN used to access OSS.

Prerequisites

Before use, prepare the following:

  • OSS Bucket name.

  • OSS Endpoint, for example https://oss-cn-hangzhou.aliyuncs.com.

  • RAM Role ARN. This role must allow the Function Compute service to assume it, and it must have OSS permissions to access the target Bucket or Bucket subdirectory.

  • Mount directory inside the Sandbox, for example /mnt/oss.

Only authorize the Bucket subdirectory required by the task. Do not expose an entire Bucket as writable to untrusted code.

Mount configuration

The value of fc.sandbox.storage.oss is a JSON string with the following structure:

{
  "mountPoints": [
    {
      "bucketName": "example-bucket",
      "mountDir": "/mnt/oss",
      "bucketPath": "/e2b-test",
      "endpoint": "https://oss-cn-hangzhou.aliyuncs.com",
      "readOnly": false
    }
  ]
}

Field descriptions:

Field

Required

Description

mountPoints

Yes

List of OSS mount points.

bucketName

Yes

OSS Bucket name.

mountDir

Yes

Mount directory inside the Sandbox. Must be an absolute path, for example /mnt/oss.

bucketPath

No

Subdirectory within the Bucket. Absolute paths are recommended. Set to / or leave empty for the Bucket root directory.

endpoint

Yes

OSS Endpoint. Should match the Bucket's region.

readOnly

No

Whether the mount is read-only. Set to true for read-only access to the mount directory.

Create a Sandbox with OSS mounts

The following example creates a Sandbox with dynamic OSS mounts and lists the files under the mount directory:

import json
import os
import sys

from dotenv import load_dotenv
from e2b import Sandbox

load_dotenv()

api_key = os.environ.get("E2B_API_KEY")
api_url = os.environ.get("E2B_API_URL")
domain = os.environ.get("E2B_DOMAIN")
oss_bucket = os.environ.get("E2E_OSS_BUCKET")
oss_endpoint = os.environ.get("E2E_OSS_ENDPOINT")
role_arn = os.environ.get("E2E_ROLE_ARN")

if not api_key:
    print("Error: E2B_API_KEY environment variable not set")
    sys.exit(1)
if not oss_bucket:
    print("Error: E2E_OSS_BUCKET environment variable not set")
    sys.exit(1)
if not oss_endpoint:
    print("Error: E2E_OSS_ENDPOINT environment variable not set")
    sys.exit(1)
if not role_arn:
    print("Error: E2E_ROLE_ARN environment variable not set")
    sys.exit(1)

conn_opts = {}
if api_url:
    conn_opts["api_url"] = api_url
if domain:
    conn_opts["domain"] = domain

mount_dir = "/mnt/oss"
oss_config = {
    "mountPoints": [
        {
            "bucketName": oss_bucket,
            "mountDir": mount_dir,
            "bucketPath": "/e2b-test",
            "endpoint": oss_endpoint,
            "readOnly": False,
        }
    ]
}

sandbox = Sandbox.create(
    api_key=api_key,
    timeout=300,
    **conn_opts,
    metadata={
        "fc.sandbox.storage.oss": json.dumps(oss_config),
        "fc.sandbox.auth.role": role_arn,
    },
)

try:
    print(f"Sandbox created: {sandbox.sandbox_id}")

    files = sandbox.files.list(mount_dir)
    print(f"OSS files: {[file.name for file in files]}")
finally:
    sandbox.kill()
import { Sandbox } from "e2b";

const apiKey = process.env.E2B_API_KEY;
const apiUrl = process.env.E2B_API_URL;
const domain = process.env.E2B_DOMAIN;
const ossBucket = process.env.E2E_OSS_BUCKET;
const ossEndpoint = process.env.E2E_OSS_ENDPOINT;
const roleArn = process.env.E2E_ROLE_ARN;

if (!apiKey) {
    console.error("Error: E2B_API_KEY environment variable not set");
    process.exit(1);
}
if (!ossBucket) {
    console.error("Error: E2E_OSS_BUCKET environment variable not set");
    process.exit(1);
}
if (!ossEndpoint) {
    console.error("Error: E2E_OSS_ENDPOINT environment variable not set");
    process.exit(1);
}
if (!roleArn) {
    console.error("Error: E2E_ROLE_ARN environment variable not set");
    process.exit(1);
}

const connOpts: { apiUrl?: string; domain?: string } = {};
if (apiUrl) connOpts.apiUrl = apiUrl;
if (domain) connOpts.domain = domain;

const mountDir = "/mnt/oss";
const ossConfig = {
  mountPoints: [
    {
      bucketName: ossBucket,
      mountDir,
      bucketPath: "/e2b-test",
      endpoint: ossEndpoint,
      readOnly: false,
    },
  ],
};

const sandbox = await Sandbox.create("code-interpreter-v1", {
  apiKey,
  timeoutMs: 300_000,
  ...connOpts,
  metadata: {
    "fc.sandbox.storage.oss": JSON.stringify(ossConfig),
    "fc.sandbox.auth.role": roleArn,
  },
});

try {
  console.log(`Sandbox created: ${sandbox.sandboxId}`);

  const filesAfter = await sandbox.files.list(mountDir);
  console.log(`OSS files: ${filesAfter.map((file) => file.name)}`);
} finally {
  await sandbox.kill();
}

Set environment variables before running:

export E2B_API_KEY=your-api-key
export E2B_API_URL=your-api-url
export E2B_DOMAIN=your-domain

export E2E_OSS_BUCKET=your-bucket
export E2E_OSS_ENDPOINT=https://oss-cn-hangzhou.aliyuncs.com
export E2E_ROLE_ARN=acs:ram::1234567890123456:role/your-role

# Run the Python example
python 04_sandbox_oss.py

Read and write the mount directory

After the mount is complete, access mountDir through the Filesystem API or commands inside the Sandbox.

mount_dir = "/mnt/oss"

# List the mount directory through the Filesystem API.
files = sandbox.files.list(mount_dir)
print([file.name for file in files])

# Write a file inside the Sandbox. This will fail when readOnly=true.
result = sandbox.commands.run(
    f"python3 - <<'PY'\n"
    f"from pathlib import Path\n"
    f"path = Path({mount_dir!r}) / 'outputs' / 'result.txt'\n"
    f"path.parent.mkdir(parents=True, exist_ok=True)\n"
    f"path.write_text('sandbox task finished\\n', encoding='utf-8')\n"
    f"print(path)\n"
    f"PY"
)
print(result.stdout.strip())

Permission recommendations

  • Use readOnly: true to mount input data directories so that tasks cannot accidentally modify or delete source data.

  • Use a separate prefix when writing results, for example tenants/<tenant-id>/tasks/<task-id>/outputs/.

  • Scope the RAM Policy to only the object prefixes required by the task. Grant oss:ListObjects and oss:GetObject for read-only tasks; add oss:PutObject, oss:DeleteObject, oss:AbortMultipartUpload, and oss:ListParts as needed for read-write tasks.

  • Do not write a long-term AccessKey pair (AccessKey ID and AccessKey secret) into code, templates, or metadata. Access OSS through the RAM Role specified by fc.sandbox.auth.role.

Notes

  • For security reasons, OSS mounts do not currently support Key Management Service (KMS) server-side encryption (SSE-KMS).

  • fc.sandbox.storage.oss must be a valid JSON string. Do not pass a Python dict or JavaScript object directly.

  • OSS mounts require fc.sandbox.auth.role to be configured as well; otherwise the Sandbox cannot obtain permissions to access OSS.

  • The endpoint should match the Bucket's region; cross-region access may cause higher latency or access failures.

  • bucketPath should use an absolute path, for example /e2b-test. To mount the Bucket root directory, set it to / or leave it empty.

  • mountDir should avoid conflicts with existing system directories in the template. Recommended paths: /mnt/oss or /home/user/oss.

  • Configure OSS lifecycle cleanup rules for temporary artifacts.