> ## 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.

# Updating

> Update and merge environment variables without replacing existing ones in HopX sandboxes. Incrementally update environment configuration, add new variables, or modify existing ones without clearing the entire environment. Essential for dynamic configuration management. Includes Python and JavaScript SDK examples and REST API endpoints.

Update environment variables by merging new values with existing ones. This preserves existing variables while adding or updating specific ones.

## Overview

Updating environment variables is ideal for:

* Adding new variables without removing existing ones
* Updating specific variables while preserving others
* Incrementally building environment configuration
* Modifying configuration without full replacement

<Note>
  `update()` merges new variables with existing ones. Existing variables not specified in the update are preserved. This is safer than `set_all()` which replaces everything.
</Note>

## Update Single Variable

Update a single environment variable:

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

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

    # Set initial variables
    sandbox.env.set_all({
        "API_KEY": "sk-123",
        "DEBUG": "true"
    })

    # Update a single variable
    sandbox.env.update({"DEBUG": "false"})

    # Verify update
    env = sandbox.env.get_all()
    print(f"API_KEY: {env.get('API_KEY')}")  # Still "sk-123"
    print(f"DEBUG: {env.get('DEBUG')}")      # Now "false"

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

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

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

    // Set initial variables
    await sandbox.env.setAll({
      API_KEY: 'sk-123',
      DEBUG: 'true'
    });

    // Update a single variable
    await sandbox.env.update({ DEBUG: 'false' });

    // Verify update
    const env = await sandbox.env.getAll();
    console.log(`API_KEY: ${env.API_KEY}`);  // Still "sk-123"
    console.log(`DEBUG: ${env.DEBUG}`);      // Now "false"

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

## Update Multiple Variables

Update multiple variables at once:

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

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

    # Set initial configuration
    sandbox.env.set_all({
        "API_KEY": "sk-123",
        "DATABASE_URL": "postgres://localhost/db"
    })

    # Update multiple variables
    sandbox.env.update({
        "NODE_ENV": "production",
        "DEBUG": "false",
        "LOG_LEVEL": "info"
    })

    # Verify all variables
    env = sandbox.env.get_all()
    print("All environment variables:")
    for key in ["API_KEY", "DATABASE_URL", "NODE_ENV", "DEBUG", "LOG_LEVEL"]:
        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 initial configuration
    await sandbox.env.setAll({
      API_KEY: 'sk-123',
      DATABASE_URL: 'postgres://localhost/db'
    });

    // Update multiple variables
    await sandbox.env.update({
      NODE_ENV: 'production',
      DEBUG: 'false',
      LOG_LEVEL: 'info'
    });

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

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

## Incremental Configuration

Build environment configuration incrementally:

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

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

    # Step 1: Set base configuration
    sandbox.env.set_all({
        "NODE_ENV": "production"
    })

    # Step 2: Add API configuration
    sandbox.env.update({
        "API_KEY": "sk-prod-xyz",
        "API_URL": "https://api.example.com"
    })

    # Step 3: Add database configuration
    sandbox.env.update({
        "DATABASE_URL": "postgres://localhost/prod",
        "DB_POOL_SIZE": "10"
    })

    # Step 4: Add logging configuration
    sandbox.env.update({
        "LOG_LEVEL": "info",
        "LOG_FORMAT": "json"
    })

    # Verify final configuration
    env = sandbox.env.get_all()
    print(f"Final configuration: {len(env)} variables")
    for key in sorted(env.keys()):
        if key not in ['PATH', 'HOME', 'USER', 'SHELL']:  # Skip system vars
            print(f"  {key}: {env[key]}")

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

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

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

    // Step 1: Set base configuration
    await sandbox.env.setAll({
      NODE_ENV: 'production'
    });

    // Step 2: Add API configuration
    await sandbox.env.update({
      API_KEY: 'sk-prod-xyz',
      API_URL: 'https://api.example.com'
    });

    // Step 3: Add database configuration
    await sandbox.env.update({
      DATABASE_URL: 'postgres://localhost/prod',
      DB_POOL_SIZE: '10'
    });

    // Step 4: Add logging configuration
    await sandbox.env.update({
      LOG_LEVEL: 'info',
      LOG_FORMAT: 'json'
    });

    // Verify final configuration
    const env = await sandbox.env.getAll();
    console.log(`Final configuration: ${Object.keys(env).length} variables`);
    for (const key of Object.keys(env).sort()) {
      if (!['PATH', 'HOME', 'USER', 'SHELL'].includes(key)) {  // Skip system vars
        console.log(`  ${key}: ${env[key]}`);
      }
    }

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

## Override Existing Variables

Update existing variables with new values:

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

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

    # Set initial values
    sandbox.env.set_all({
        "API_KEY": "sk-dev-123",
        "DEBUG": "true",
        "LOG_LEVEL": "debug"
    })

    # Override with production values
    sandbox.env.update({
        "API_KEY": "sk-prod-xyz",
        "DEBUG": "false",
        "LOG_LEVEL": "info"
    })

    # Verify overrides
    env = sandbox.env.get_all()
    print(f"API_KEY: {env.get('API_KEY')}")      # "sk-prod-xyz"
    print(f"DEBUG: {env.get('DEBUG')}")            # "false"
    print(f"LOG_LEVEL: {env.get('LOG_LEVEL')}")   # "info"

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

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

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

    // Set initial values
    await sandbox.env.setAll({
      API_KEY: 'sk-dev-123',
      DEBUG: 'true',
      LOG_LEVEL: 'debug'
    });

    // Override with production values
    await sandbox.env.update({
      API_KEY: 'sk-prod-xyz',
      DEBUG: 'false',
      LOG_LEVEL: 'info'
    });

    // Verify overrides
    const env = await sandbox.env.getAll();
    console.log(`API_KEY: ${env.API_KEY}`);      // "sk-prod-xyz"
    console.log(`DEBUG: ${env.DEBUG}`);          // "false"
    console.log(`LOG_LEVEL: ${env.LOG_LEVEL}`); // "info"

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

## Complete Example

Here's a complete example showing incremental environment setup:

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

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

    # Start with base configuration
    print("🔧 Setting up environment incrementally...\n")

    # Step 1: Base environment
    sandbox.env.set_all({"NODE_ENV": "production"})
    print("✅ Step 1: Base environment set")

    # Step 2: API configuration
    sandbox.env.update({
        "API_KEY": "sk-prod-xyz",
        "API_URL": "https://api.example.com",
        "API_TIMEOUT": "30"
    })
    print("✅ Step 2: API configuration added")

    # Step 3: Database configuration
    sandbox.env.update({
        "DATABASE_URL": "postgres://localhost/prod",
        "DB_POOL_SIZE": "10",
        "DB_TIMEOUT": "5"
    })
    print("✅ Step 3: Database configuration added")

    # Step 4: Feature flags
    sandbox.env.update({
        "FEATURE_NEW_UI": "true",
        "FEATURE_ANALYTICS": "true",
        "FEATURE_BETA": "false"
    })
    print("✅ Step 4: Feature flags added")

    # Step 5: Update existing variable
    sandbox.env.update({"NODE_ENV": "staging"})
    print("✅ Step 5: NODE_ENV updated to staging")

    # Final verification
    env = sandbox.env.get_all()
    custom_vars = {k: v for k, v in env.items() 
                   if k not in ['PATH', 'HOME', 'USER', 'SHELL', 'PWD']}

    print(f"\n📋 Final environment ({len(custom_vars)} custom variables):")
    for key, value in sorted(custom_vars.items()):
        if any(sensitive in key.upper() for sensitive in ['KEY', 'SECRET', 'PASSWORD']):
            print(f"  {key}=***MASKED***")
        else:
            print(f"  {key}={value}")

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

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

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

    // Start with base configuration
    console.log('🔧 Setting up environment incrementally...\n');

    // Step 1: Base environment
    await sandbox.env.setAll({ NODE_ENV: 'production' });
    console.log('✅ Step 1: Base environment set');

    // Step 2: API configuration
    await sandbox.env.update({
      API_KEY: 'sk-prod-xyz',
      API_URL: 'https://api.example.com',
      API_TIMEOUT: '30'
    });
    console.log('✅ Step 2: API configuration added');

    // Step 3: Database configuration
    await sandbox.env.update({
      DATABASE_URL: 'postgres://localhost/prod',
      DB_POOL_SIZE: '10',
      DB_TIMEOUT: '5'
    });
    console.log('✅ Step 3: Database configuration added');

    // Step 4: Feature flags
    await sandbox.env.update({
      FEATURE_NEW_UI: 'true',
      FEATURE_ANALYTICS: 'true',
      FEATURE_BETA: 'false'
    });
    console.log('✅ Step 4: Feature flags added');

    // Step 5: Update existing variable
    await sandbox.env.update({ NODE_ENV: 'staging' });
    console.log('✅ Step 5: NODE_ENV updated to staging');

    // Final verification
    const env = await sandbox.env.getAll();
    const systemVars = new Set(['PATH', 'HOME', 'USER', 'SHELL', 'PWD']);
    const customVars = Object.fromEntries(
      Object.entries(env).filter(([k]) => !systemVars.has(k))
    );

    console.log(`\n📋 Final environment (${Object.keys(customVars).length} custom variables):`);
    for (const [key, value] of Object.entries(customVars).sort()) {
      const isSensitive = ['KEY', 'SECRET', 'PASSWORD'].some(
        s => key.toUpperCase().includes(s)
      );
      if (isSensitive) {
        console.log(`  ${key}=***MASKED***`);
      } else {
        console.log(`  ${key}=${value}`);
      }
    }

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

## Best Practices

<Steps>
  <Step title="1. Use update() Instead of set_all()">
    Prefer `update()` over `set_all()` to preserve existing variables unless you want to replace everything.
  </Step>

  <Step title="2. Build Incrementally">
    Build environment configuration incrementally by updating variables in logical groups.
  </Step>

  <Step title="3. Override When Needed">
    Use `update()` to override existing variables with new values without affecting others.
  </Step>

  <Step title="4. Group Related Variables">
    Update related variables together (e.g., all API config, all database config) for better organization.
  </Step>

  <Step title="5. Verify After Updates">
    Always verify variables are updated correctly using `get_all()` after updates.
  </Step>
</Steps>

## Related

* **[Getting Environment Variables](/core-concepts/environment/getting)** - Retrieve environment variables
* **[Setting Environment Variables](/core-concepts/environment/setting)** - Set or replace variables
* **SDK**: [sandbox.env.update()](/sdk/python/environment-variables#update) - Python SDK method
* **API**: [PATCH /env](/api/vm-agent/update-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 [Setting Environment Variables](/core-concepts/environment/setting) to replace all variables
* Review [Clearing Environment Variables](/core-concepts/environment/clearing) to remove variables
