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

# Getting

> Retrieve environment variables from sandboxes. Learn how to get single or all environment variables from HopX sandboxes using Python and JavaScript SDKs or REST API. Includes examples for reading variables, handling missing variables, and processing environment data. Essential for configuring code execution environments.

Retrieve environment variables from your sandbox. You can get all variables at once or fetch specific variables by name.

## Overview

Getting environment variables is useful for:

* Inspecting current environment configuration
* Verifying variables are set correctly
* Accessing system and custom variables
* Debugging environment-related issues

<Note>
  Environment variables include both system variables (like `PATH`, `HOME`) and custom variables you've set. Sensitive values may be masked in responses.
</Note>

## Get All Environment Variables

Retrieve all environment variables:

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

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

    # Get all environment variables
    env = sandbox.env.get_all()
    print(f"Total variables: {len(env)}")

    # Access specific variables
    print(f"PATH: {env.get('PATH', 'not set')}")
    print(f"HOME: {env.get('HOME', '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' });

    // Get all environment variables
    const env = await sandbox.env.getAll();
    console.log(`Total variables: ${Object.keys(env).length}`);

    // Access specific variables
    console.log(`PATH: ${env.PATH || 'not set'}`);
    console.log(`HOME: ${env.HOME || 'not set'}`);

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

## Get Specific Variable

Get a single environment variable:

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

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

    # Get a specific variable
    api_key = sandbox.env.get("API_KEY")
    if api_key:
        print(f"API key: {api_key[:10]}...")
    else:
        print("API_KEY not set")

    # Get with default value
    db_url = sandbox.env.get("DATABASE_URL", "postgres://localhost/db")
    print(f"Database URL: {db_url}")

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

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

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

    // Get a specific variable
    const apiKey = await sandbox.env.get('API_KEY');
    if (apiKey) {
      console.log(`API key: ${apiKey.substring(0, 10)}...`);
    } else {
      console.log('API_KEY not set');
    }

    // Get with default value
    const dbUrl = await sandbox.env.get('DATABASE_URL', 'postgres://localhost/db');
    console.log(`Database URL: ${dbUrl}`);

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

## List All Variables

Iterate through all environment variables:

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

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

    # Get all variables
    env = sandbox.env.get_all()

    # List all variables
    print("Environment Variables:")
    for key, value in sorted(env.items()):
        # Mask sensitive values
        if any(sensitive in key.upper() for sensitive in ['KEY', 'SECRET', 'PASSWORD', 'TOKEN']):
            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' });

    // Get all variables
    const env = await sandbox.env.getAll();

    // List all variables
    console.log('Environment Variables:');
    for (const [key, value] of Object.entries(env).sort()) {
      // Mask sensitive values
      const isSensitive = ['KEY', 'SECRET', 'PASSWORD', 'TOKEN'].some(
        s => key.toUpperCase().includes(s)
      );
      if (isSensitive) {
        console.log(`  ${key}=***MASKED***`);
      } else {
        console.log(`  ${key}=${value}`);
      }
    }

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

## Filter Variables

Filter environment variables by prefix or pattern:

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

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

    # Get all variables
    env = sandbox.env.get_all()

    # Filter by prefix
    api_vars = {k: v for k, v in env.items() if k.startswith('API_')}
    print(f"API variables: {list(api_vars.keys())}")

    # Filter by pattern
    debug_vars = {k: v for k, v in env.items() if 'DEBUG' in k.upper()}
    print(f"Debug variables: {list(debug_vars.keys())}")

    # Filter custom variables (exclude system vars)
    system_vars = {'PATH', 'HOME', 'USER', 'SHELL', 'PWD'}
    custom_vars = {k: v for k, v in env.items() if k not in system_vars}
    print(f"Custom variables: {list(custom_vars.keys())}")

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

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

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

    // Get all variables
    const env = await sandbox.env.getAll();

    // Filter by prefix
    const apiVars = Object.fromEntries(
      Object.entries(env).filter(([k]) => k.startsWith('API_'))
    );
    console.log(`API variables: ${Object.keys(apiVars)}`);

    // Filter by pattern
    const debugVars = Object.fromEntries(
      Object.entries(env).filter(([k]) => k.toUpperCase().includes('DEBUG'))
    );
    console.log(`Debug variables: ${Object.keys(debugVars)}`);

    // Filter custom variables (exclude system vars)
    const systemVars = new Set(['PATH', 'HOME', 'USER', 'SHELL', 'PWD']);
    const customVars = Object.fromEntries(
      Object.entries(env).filter(([k]) => !systemVars.has(k))
    );
    console.log(`Custom variables: ${Object.keys(customVars)}`);

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

## Check Variable Existence

Check if a variable exists:

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

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

    # Check if variable exists
    api_key = sandbox.env.get("API_KEY")
    if api_key:
        print("API_KEY is set")
    else:
        print("API_KEY is not set")

    # Check multiple variables
    required_vars = ["API_KEY", "DATABASE_URL", "NODE_ENV"]
    env = sandbox.env.get_all()

    missing = [var for var in required_vars if var not in env]
    if missing:
        print(f"Missing variables: {missing}")
    else:
        print("All required variables are set")

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

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

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

    // Check if variable exists
    const apiKey = await sandbox.env.get('API_KEY');
    if (apiKey) {
      console.log('API_KEY is set');
    } else {
      console.log('API_KEY is not set');
    }

    // Check multiple variables
    const requiredVars = ['API_KEY', 'DATABASE_URL', 'NODE_ENV'];
    const env = await sandbox.env.getAll();

    const missing = requiredVars.filter(v => !(v in env));
    if (missing.length > 0) {
      console.log(`Missing variables: ${missing}`);
    } else {
      console.log('All required variables are set');
    }

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

## Verify Variables in Code

Verify environment variables are accessible in code execution:

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

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

    # Set some variables
    sandbox.env.set("API_KEY", "sk-123")
    sandbox.env.set("DEBUG", "true")

    # Verify they're accessible in code
    result = sandbox.run_code('''
    import os
    print(f"API_KEY: {os.getenv('API_KEY')}")
    print(f"DEBUG: {os.getenv('DEBUG')}")
    ''')

    print(result.stdout)

    # Get variables via env API
    env = sandbox.env.get_all()
    print(f"\nVia API - API_KEY: {env.get('API_KEY')}")
    print(f"Via API - DEBUG: {env.get('DEBUG')}")

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

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

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

    // Set some variables
    await sandbox.env.set('API_KEY', 'sk-123');
    await sandbox.env.set('DEBUG', 'true');

    // Verify they're accessible in code
    const result = await sandbox.runCode(`
    import os
    print(f"API_KEY: {os.getenv('API_KEY')}")
    print(f"DEBUG: {os.getenv('DEBUG')}")
    `);

    console.log(result.stdout);

    // Get variables via env API
    const env = await sandbox.env.getAll();
    console.log(`\nVia API - API_KEY: ${env.API_KEY}`);
    console.log(`Via API - DEBUG: ${env.DEBUG}`);

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

## Complete Example

Here's a complete example showing environment variable retrieval:

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

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

    # Set up environment
    sandbox.env.set_all({
        "API_KEY": "sk-prod-xyz",
        "DATABASE_URL": "postgres://localhost/db",
        "NODE_ENV": "production",
        "DEBUG": "false"
    })

    # Get all variables
    print("📋 All Environment Variables:")
    env = sandbox.env.get_all()
    for key, value in sorted(env.items()):
        if any(sensitive in key.upper() for sensitive in ['KEY', 'SECRET', 'PASSWORD']):
            print(f"  {key}=***MASKED***")
        else:
            print(f"  {key}={value}")

    # Get specific variables
    print("\n🔍 Specific Variables:")
    api_key = sandbox.env.get("API_KEY")
    print(f"  API_KEY: {'Set' if api_key else 'Not set'}")

    db_url = sandbox.env.get("DATABASE_URL")
    print(f"  DATABASE_URL: {db_url}")

    node_env = sandbox.env.get("NODE_ENV", "development")
    print(f"  NODE_ENV: {node_env}")

    # Verify in code execution
    print("\n✅ Verification in Code:")
    result = sandbox.run_code('''
    import os
    print(f"API_KEY: {os.getenv('API_KEY', 'not set')[:10]}...")
    print(f"DATABASE_URL: {os.getenv('DATABASE_URL', 'not set')}")
    print(f"NODE_ENV: {os.getenv('NODE_ENV', 'not set')}")
    ''')
    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 up environment
    await sandbox.env.setAll({
      API_KEY: 'sk-prod-xyz',
      DATABASE_URL: 'postgres://localhost/db',
      NODE_ENV: 'production',
      DEBUG: 'false'
    });

    // Get all variables
    console.log('📋 All Environment Variables:');
    const env = await sandbox.env.getAll();
    for (const [key, value] of Object.entries(env).sort()) {
      const isSensitive = ['KEY', 'SECRET', 'PASSWORD'].some(
        s => key.toUpperCase().includes(s)
      );
      if (isSensitive) {
        console.log(`  ${key}=***MASKED***`);
      } else {
        console.log(`  ${key}=${value}`);
      }
    }

    // Get specific variables
    console.log('\n🔍 Specific Variables:');
    const apiKey = await sandbox.env.get('API_KEY');
    console.log(`  API_KEY: ${apiKey ? 'Set' : 'Not set'}`);

    const dbUrl = await sandbox.env.get('DATABASE_URL');
    console.log(`  DATABASE_URL: ${dbUrl}`);

    const nodeEnv = await sandbox.env.get('NODE_ENV', 'development');
    console.log(`  NODE_ENV: ${nodeEnv}`);

    // Verify in code execution
    console.log('\n✅ Verification in Code:');
    const result = await sandbox.runCode(`
    import os
    print(f"API_KEY: {os.getenv('API_KEY', 'not set')[:10]}...")
    print(f"DATABASE_URL: {os.getenv('DATABASE_URL', 'not set')}")
    print(f"NODE_ENV: {os.getenv('NODE_ENV', 'not set')}")
    `);
    console.log(result.stdout);

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

## Best Practices

<Steps>
  <Step title="1. Use get() for Single Variables">
    Use `env.get(key)` for retrieving individual variables with optional defaults.
  </Step>

  <Step title="2. Use get_all() for Multiple Variables">
    Use `env.get_all()` when you need to access multiple variables or iterate through all.
  </Step>

  <Step title="3. Handle Missing Variables">
    Always check if variables exist or provide defaults when retrieving.
  </Step>

  <Step title="4. Mask Sensitive Values">
    When displaying environment variables, mask sensitive values (keys, secrets, passwords, tokens).
  </Step>

  <Step title="5. Verify in Code">
    Test that environment variables are accessible in code execution to ensure they're set correctly.
  </Step>
</Steps>

## Related

* **[Setting Environment Variables](/core-concepts/environment/setting)** - Set environment variables
* **[Updating Environment Variables](/core-concepts/environment/updating)** - Update variables
* **SDK**: [sandbox.env.get()](/sdk/python/environment-variables#get) - Python SDK method
* **API**: [GET /env](/api/vm-agent/get-env) - VM Agent API endpoint
* [CLI Environment Variables](/cli/commands/env) - Environment variables from CLI

## Next Steps

* Learn about [Setting Environment Variables](/core-concepts/environment/setting) to configure your sandbox
* Explore [Updating Environment Variables](/core-concepts/environment/updating) to modify existing variables
* Review [Clearing Environment Variables](/core-concepts/environment/clearing) to remove variables
