> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Setting

> Set and replace environment variables in sandboxes. Configure execution environments by setting environment variables for code execution, API keys, database connections, and other configuration values. Learn how to set single or multiple variables using Python and JavaScript SDKs or REST API. Includes examples for common use cases.

Set environment variables in your sandbox. You can set individual variables or replace all variables at once.

## Overview

Setting environment variables is essential for:

* Configuring application settings
* Providing API keys and secrets
* Setting up database connections
* Configuring runtime behavior

<Warning>
  `set_all()` replaces ALL existing environment variables. Use [Updating Environment Variables](/core-concepts/environment/updating) if you want to merge with existing variables instead.
</Warning>

## Set Single Variable

Set a single environment variable:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Set a single variable
    sandbox.env.set("API_KEY", "sk-prod-xyz")
    print("API_KEY set")

    # Verify it's set
    api_key = sandbox.env.get("API_KEY")
    print(f"API_KEY value: {api_key}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Set a single variable
    await sandbox.env.set('API_KEY', 'sk-prod-xyz');
    console.log('API_KEY set');

    // Verify it's set
    const apiKey = await sandbox.env.get('API_KEY');
    console.log(`API_KEY value: ${apiKey}`);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Set Multiple Variables

Set multiple environment variables at once:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Set multiple variables (replaces all existing)
    sandbox.env.set_all({
        "API_KEY": "sk-prod-xyz",
        "DATABASE_URL": "postgres://localhost/db",
        "NODE_ENV": "production",
        "DEBUG": "false"
    })

    # Verify all are set
    env = sandbox.env.get_all()
    print(f"Set {len(env)} variables")
    for key in ["API_KEY", "DATABASE_URL", "NODE_ENV", "DEBUG"]:
        print(f"  {key}: {env.get(key, 'not set')}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Set multiple variables (replaces all existing)
    await sandbox.env.setAll({
      API_KEY: 'sk-prod-xyz',
      DATABASE_URL: 'postgres://localhost/db',
      NODE_ENV: 'production',
      DEBUG: 'false'
    });

    // Verify all are set
    const env = await sandbox.env.getAll();
    console.log(`Set ${Object.keys(env).length} variables`);
    for (const key of ['API_KEY', 'DATABASE_URL', 'NODE_ENV', 'DEBUG']) {
      console.log(`  ${key}: ${env[key] || 'not set'}`);
    }

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Replace All Variables

Replace all environment variables (removes existing ones):

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Get current variables
    current_env = sandbox.env.get_all()
    print(f"Current variables: {len(current_env)}")

    # Replace all with new set
    sandbox.env.set_all({
        "API_KEY": "sk-new-key",
        "DATABASE_URL": "postgres://new-host/db"
    })

    # Verify replacement
    new_env = sandbox.env.get_all()
    print(f"New variables: {len(new_env)}")
    print(f"Variables: {list(new_env.keys())}")

    # Note: System variables like PATH may still exist
    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Get current variables
    const currentEnv = await sandbox.env.getAll();
    console.log(`Current variables: ${Object.keys(currentEnv).length}`);

    // Replace all with new set
    await sandbox.env.setAll({
      API_KEY: 'sk-new-key',
      DATABASE_URL: 'postgres://new-host/db'
    });

    // Verify replacement
    const newEnv = await sandbox.env.getAll();
    console.log(`New variables: ${Object.keys(newEnv).length}`);
    console.log(`Variables: ${Object.keys(newEnv)}`);

    // Note: System variables like PATH may still exist
    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Use in Code Execution

Set variables and use them in code:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Set environment variables
    sandbox.env.set_all({
        "API_KEY": "sk-123",
        "DATABASE_URL": "postgres://localhost/mydb",
        "DEBUG": "true"
    })

    # Use in code execution
    result = sandbox.run_code('''
    import os
    print(f"API key: {os.getenv('API_KEY')}")
    print(f"Database: {os.getenv('DATABASE_URL')}")
    print(f"Debug mode: {os.getenv('DEBUG')}")
    ''')

    print(result.stdout)

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Set environment variables
    await sandbox.env.setAll({
      API_KEY: 'sk-123',
      DATABASE_URL: 'postgres://localhost/mydb',
      DEBUG: 'true'
    });

    // Use in code execution
    const result = await sandbox.runCode(`
    import os
    print(f"API key: {os.getenv('API_KEY')}")
    print(f"Database: {os.getenv('DATABASE_URL')}")
    print(f"Debug mode: {os.getenv('DEBUG')}")
    `);

    console.log(result.stdout);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Use in Commands

Set variables and use them in shell commands:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Set environment variables
    sandbox.env.set_all({
        "API_KEY": "sk-123",
        "NODE_ENV": "production"
    })

    # Use in commands
    result = sandbox.commands.run('echo $API_KEY')
    print(f"Command output: {result.stdout}")

    result = sandbox.commands.run('echo $NODE_ENV')
    print(f"Command output: {result.stdout}")

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Set environment variables
    await sandbox.env.setAll({
      API_KEY: 'sk-123',
      NODE_ENV: 'production'
    });

    // Use in commands
    let result = await sandbox.commands.run('echo $API_KEY');
    console.log(`Command output: ${result.stdout}`);

    result = await sandbox.commands.run('echo $NODE_ENV');
    console.log(`Command output: ${result.stdout}`);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Complete Example

Here's a complete example showing environment variable setup:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from hopx_ai import Sandbox

    sandbox = Sandbox.create(template="code-interpreter")

    # Configure application environment
    print("🔧 Setting up environment...")

    sandbox.env.set_all({
        "API_KEY": "sk-prod-xyz123",
        "DATABASE_URL": "postgres://localhost/production",
        "REDIS_URL": "redis://localhost:6379",
        "NODE_ENV": "production",
        "DEBUG": "false",
        "LOG_LEVEL": "info"
    })

    # Verify setup
    env = sandbox.env.get_all()
    print(f"\n✅ Environment configured with {len(env)} variables")

    # Use in application code
    print("\n💻 Testing in code execution...")
    result = sandbox.run_code('''
    import os

    config = {
        "api_key": os.getenv("API_KEY", "not set"),
        "database": os.getenv("DATABASE_URL", "not set"),
        "redis": os.getenv("REDIS_URL", "not set"),
        "node_env": os.getenv("NODE_ENV", "development"),
        "debug": os.getenv("DEBUG", "false"),
        "log_level": os.getenv("LOG_LEVEL", "debug")
    }

    for key, value in config.items():
        if 'key' in key.lower():
            print(f"{key}: {value[:10]}...")
        else:
            print(f"{key}: {value}")
    ''')

    print(result.stdout)

    sandbox.kill()
    ```
  </Tab>

  <Tab title="JavaScript">
    ```javascript theme={null}
    import { Sandbox } from '@hopx-ai/sdk';

    const sandbox = await Sandbox.create({ template: 'code-interpreter' });

    // Configure application environment
    console.log('🔧 Setting up environment...');

    await sandbox.env.setAll({
      API_KEY: 'sk-prod-xyz123',
      DATABASE_URL: 'postgres://localhost/production',
      REDIS_URL: 'redis://localhost:6379',
      NODE_ENV: 'production',
      DEBUG: 'false',
      LOG_LEVEL: 'info'
    });

    // Verify setup
    const env = await sandbox.env.getAll();
    console.log(`\n✅ Environment configured with ${Object.keys(env).length} variables`);

    // Use in application code
    console.log('\n💻 Testing in code execution...');
    const result = await sandbox.runCode(`
    import os

    config = {
        "api_key": os.getenv("API_KEY", "not set"),
        "database": os.getenv("DATABASE_URL", "not set"),
        "redis": os.getenv("REDIS_URL", "not set"),
        "node_env": os.getenv("NODE_ENV", "development"),
        "debug": os.getenv("DEBUG", "false"),
        "log_level": os.getenv("LOG_LEVEL", "debug")
    }

    for key, value in config.items():
        if 'key' in key.lower():
            print(f"{key}: {value[:10]}...")
        else:
            print(f"{key}: {value}")
    `);

    console.log(result.stdout);

    await sandbox.kill();
    ```
  </Tab>
</Tabs>

## Best Practices

<Steps>
  <Step title="1. Use set() for Single Variables">
    Use `env.set(key, value)` for setting individual variables. This merges with existing variables.
  </Step>

  <Step title="2. Use set_all() Carefully">
    `set_all()` replaces ALL variables. Only use when you want to completely replace the environment.
  </Step>

  <Step title="3. Prefer update() for Multiple Variables">
    For setting multiple variables while preserving existing ones, use [Updating Environment Variables](/core-concepts/environment/updating) instead.
  </Step>

  <Step title="4. Set Before Execution">
    Set environment variables before running code or commands that need them.
  </Step>

  <Step title="5. Verify After Setting">
    Always verify variables are set correctly using `get()` or `get_all()` after setting.
  </Step>
</Steps>

## Related

* **[Getting Environment Variables](/core-concepts/environment/getting)** - Retrieve environment variables
* **[Updating Environment Variables](/core-concepts/environment/updating)** - Update variables without replacing
* **SDK**: [sandbox.env.set()](/sdk/python/environment-variables#set) - Python SDK method
* **API**: [PUT /env](/api/vm-agent/set-env) - VM Agent API endpoint
* [CLI Environment Variables](/cli/commands/env) - Environment variables from CLI

## Next Steps

* Learn about [Getting Environment Variables](/core-concepts/environment/getting) to retrieve variables
* Explore [Updating Environment Variables](/core-concepts/environment/updating) to merge with existing variables
* Review [Clearing Environment Variables](/core-concepts/environment/clearing) to remove variables
