Skip to content

Environment variables

This page covers how to set and use environment variables in a sandbox.

There are 3 ways to set environment variables in a sandbox:

  1. Global environment variables when creating the sandbox.
  2. When running code in the sandbox.
  3. When running commands in the sandbox.

1. Global environment variables

You can set global environment variables when creating a sandbox.

The envs parameter is a dictionary of environment variables to set in the sandbox.

from agentbox import Sandbox

# Create sandbox with and keep it running for 60 seconds.
# Note: The units are seconds.
sandbox = Sandbox(
    api_key="ab_xxxxxxxxxxxxxxxxxxxxxxxxx",
    template="wemmodr8mb2uk3kn7exw",
    timeout=60,
    envs={
        'MY_VAR': 'my_value',
    })

result = sandbox.commands.run("echo $MY_VAR")
print("Running sandbox get variables: ", result.stdout)

2. Setting environment variables when running code

You can set environment variables for specific code execution call in the sandbox. This is recommended for passing secrets.

Note:

  • These environment variables are securely scoped to the command and will not be global or accessible inside the sandbox or for subsequent commands.
  • If you had a global environment variable with the same name, it will be overridden only for the command.
from agentbox import Sandbox

# Create sandbox with and keep it running for 60 seconds.
# Note: The units are seconds.
sandbox = Sandbox(
    api_key="ab_xxxxxxxxxxxxxxxxxxxxxxxxx",
    template="wemmodr8mb2uk3kn7exw",
    timeout=60)

result = sandbox.run_code(
    'import os; print(os.environ.get("MY_VAR"))',
    envs={
        'MY_VAR': 'my_value'
    })

result = sandbox.commands.run("echo $MY_VAR")
print("Running sandbox get run_code variables: ", result.stdout)

3. Setting environment variables when running commands

You can set environment variables for specific command execution in the sandbox. This is recommended for passing secrets.

Note:

  • These environment variables are securely scoped to the command and will not be global or accessible inside the sandbox or for subsequent commands.
  • If you had a global environment variable with the same name, it will be overridden only for the command.
from agentbox import Sandbox

# Create sandbox with and keep it running for 60 seconds.
# Note: The units are seconds.
sandbox = Sandbox(
    api_key="ab_xxxxxxxxxxxxxxxxxxxxxxxxx",
    template="wemmodr8mb2uk3kn7exw",
    timeout=60)

result = sandbox.commands.run(
    'echo $MY_VAR',
    envs={
        'MY_VAR': '123'
    })

print("Running sandbox get variable result: ", result.stdout)