云沙箱支持在创建实例时动态挂载 OSS Bucket,作为沙箱内的工作目录或结果输出目录。本文给出代码示例。
代码示例
Python
import json
from datetime import datetime
from e2b import Sandbox
mount_dir = "/mnt/oss"
oss_config = {
"mountPoints": [
{
"bucketName": "your_bucket_name",
"mountDir": mount_dir,
"bucketPath": "/",
"endpoint": "http://oss-cn-beijing-internal.aliyuncs.com",
"readOnly": False,
}
]
}
role_arn = "acs:ram::<account-id>:role/<role-name>"
sandbox = None
try:
sandbox = Sandbox.create(
api_key=E2B_API_KEY,
timeout=300,
metadata={
"fc.sandbox.storage.oss": json.dumps(oss_config),
"fc.sandbox.auth.role": role_arn,
},
**E2B_CONN_OPTS,
)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
path = f"{mount_dir}/e2b-test-{timestamp}.txt"
sandbox.files.write(path, f"Hello from OSS sandbox at {timestamp}\n")
print(sandbox.files.read(path))
finally:
if sandbox is not None:
sandbox.kill()
TypeScript
import 'dotenv/config';
import { Sandbox } from 'e2b';
const mountDir = '/mnt/oss';
const ossConfig = {
mountPoints: [
{
bucketName: 'your-bucket-name',
mountDir,
bucketPath: '/',
endpoint: 'http://oss-cn-beijing-internal.aliyuncs.com',
readOnly: false,
},
],
};
const roleArn = 'acs:ram::<account-id>:role/<role-name>';
async function main() {
const sbx = await Sandbox.create({
apiKey: process.env.E2B_API_KEY,
timeoutMs: 300_000,
metadata: {
'fc.sandbox.storage.oss': JSON.stringify(ossConfig),
'fc.sandbox.auth.role': roleArn,
},
});
try {
const timestamp = new Date().toISOString().replace(/[-:T]/g, '').slice(0, 15);
const path = `${mountDir}/e2b-test-${timestamp}.txt`;
await sbx.files.write(path, `Hello from OSS sandbox at ${timestamp}\n`);
console.log(await sbx.files.read(path));
} finally {
await sbx.kill();
}
}
main();
注意事项
-
role_arn为授信给函数计算服务的 RAM 角色 ARN,需要具备对应 Bucket 的读写权限。 -
内网 endpoint 需要与沙箱地域匹配。
-
如果只读访问,把
readOnly设置为True/true。
该文章对您有帮助吗?