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

# Environment Variables

> Environment variable management resource for configuring sandbox environment in HopX using the Python SDK. Complete reference for the Environment class including methods for getting, setting, updating, and clearing environment variables. Includes code examples for configuration management and environment setup.

**Version:** 0.3.0\
**Last Verified:** 2025-01-27\
**Package:** `hopx-ai` on [PyPI](https://pypi.org/project/hopx-ai/)

## Overview

The `EnvironmentVariables` resource (accessed via `sandbox.env`) provides methods for managing environment variables in sandboxes. Use this resource to set, get, update, and delete environment variables that are available to all code execution and commands.

Environment variables set through this resource persist for the lifetime of the sandbox and are available to all executions.

## Access

```python theme={null}
from hopx_ai import Sandbox

sandbox = Sandbox.create(template="code-interpreter")
env = sandbox.env  # Lazy-loaded
```

## Methods

### `get_all`

Get all environment variables.

```python theme={null}
env.get_all(*, timeout=None) -> Dict[str, str]
```

**Returns:** `Dict[str, str]` - Dictionary of all environment variables

**Example:**

```python theme={null}
all_vars = sandbox.env.get_all()
for key, value in all_vars.items():
    print(f"{key}={value}")
```

**Expected Output:**

```
PATH=/usr/local/bin:/usr/bin:/bin
HOME=/root
LANG=en_US.UTF-8
```

**See Also:**

* [API: Get Environment Variables](/api/vm-agent/get-env)

***

### `get`

Get a specific environment variable value.

```python theme={null}
env.get(key, default=None) -> Optional[str]
```

**Parameters:**

* `key` (`str`): Environment variable name
* `default` (`str`, optional): Default value if not found

**Returns:** `Optional[str]` - Variable value or default

**Example:**

```python theme={null}
api_key = sandbox.env.get("API_KEY", "not-set")
print(f"API key: {api_key}")
```

**Expected Output:**

```
API key: not-set
```

**See Also:**

* [API: Get Environment Variables](/api/vm-agent/get-env)

***

### `set`

Set a single environment variable.

```python theme={null}
env.set(key, value, *, timeout=None) -> Dict[str, str]
```

**Parameters:**

* `key` (`str`): Environment variable name
* `value` (`str`): Variable value
* `timeout` (`int`, optional): Request timeout

**Returns:** `Dict[str, str]` - Updated dictionary of all environment variables

**Example:**

```python theme={null}
sandbox.env.set("API_KEY", "secret123")
all_vars = sandbox.env.get_all()
print(all_vars["API_KEY"])  # "secret123"
```

**Expected Output:**

```
secret123
```

**See Also:**

* [API: Set Environment Variables](/api/vm-agent/set-env)

***

### `set_all`

Set/replace all environment variables (destructive).

```python theme={null}
env.set_all(env_vars, *, timeout=None) -> Dict[str, str]
```

**Parameters:**

* `env_vars` (`Dict[str, str]`): Dictionary of environment variables
* `timeout` (`int`, optional): Request timeout

**Returns:** `Dict[str, str]` - Updated dictionary of all environment variables

<Warning>
  This replaces ALL existing environment variables. Use `update()` to merge instead.
</Warning>

**Example:**

```python theme={null}
sandbox.env.set_all({
    "API_KEY": "secret123",
    "DEBUG": "true",
    "ENV": "production"
})
```

**Expected Output:**

```
All environment variables replaced successfully
```

***

### `update`

Update specific environment variables (merge with existing).

```python theme={null}
env.update(env_vars, *, timeout=None) -> Dict[str, str]
```

**Parameters:**

* `env_vars` (`Dict[str, str]`): Dictionary of environment variables to update
* `timeout` (`int`, optional): Request timeout

**Returns:** `Dict[str, str]` - Updated dictionary of all environment variables

**Example:**

```python theme={null}
# Merge new variables with existing
sandbox.env.update({
    "NEW_VAR": "value",
    "API_KEY": "updated-secret"
})
```

**Expected Output:**

```
Environment variables updated successfully
```

**See Also:**

* [API: Update Environment Variables](/api/vm-agent/update-env)

***

### `delete`

Delete a specific environment variable.

```python theme={null}
env.delete(key, *, timeout=None) -> None
```

**Parameters:**

* `key` (`str`): Environment variable name to delete
* `timeout` (`int`, optional): Request timeout

**Example:**

```python theme={null}
sandbox.env.delete("OLD_VAR")
```

**Expected Output:**

```
Environment variable deleted successfully
```

***

## Examples

### Example 1: Basic Environment Variable Management

```python theme={null}
from hopx_ai import Sandbox

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

# Set environment variables
sandbox.env.set("API_KEY", "secret123")
sandbox.env.set("DEBUG", "true")

# Get a variable
api_key = sandbox.env.get("API_KEY")
print(f"API key: {api_key}")

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

sandbox.kill()
```

**Expected Output:**

```
API key: secret123
Total variables: 5
```

### Example 2: Setting Variables at Creation

```python theme={null}
from hopx_ai import Sandbox

# Set environment variables when creating sandbox
sandbox = Sandbox.create(
    template="code-interpreter",
    env_vars={
        "API_KEY": "secret123",
        "DEBUG": "true",
        "ENV": "development"
    }
)

# Verify they're set
result = sandbox.run_code("import os; print(os.getenv('API_KEY'))")
print(result.stdout)

sandbox.kill()
```

**Expected Output:**

```
secret123
```

### Example 3: Updating Variables

```python theme={null}
from hopx_ai import Sandbox

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

# Set initial variables
sandbox.env.set_all({
    "VAR1": "value1",
    "VAR2": "value2"
})

# Update specific variables (merge)
sandbox.env.update({
    "VAR2": "updated-value2",
    "VAR3": "value3"
})

# VAR1 still exists, VAR2 updated, VAR3 added
all_vars = sandbox.env.get_all()
print(all_vars)

sandbox.kill()
```

**Expected Output:**

```
{'VAR1': 'value1', 'VAR2': 'updated-value2', 'VAR3': 'value3', 'PATH': '/usr/local/bin:/usr/bin:/bin', 'HOME': '/root'}
```

### Example 4: Using Variables in Code Execution

```python theme={null}
from hopx_ai import Sandbox

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

# Set environment variable
sandbox.env.set("SECRET", "my-secret-key")

# Use it in code execution
result = sandbox.run_code(
    "import os; print(os.getenv('SECRET'))"
)
print(result.stdout)  # "my-secret-key\n"

sandbox.kill()
```

**Expected Output:**

```
my-secret-key
```

### Example 5: Using Variables in Commands

```python theme={null}
from hopx_ai import Sandbox

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

# Set environment variable
sandbox.env.set("MY_VAR", "Hello from env")

# Use it in command
result = sandbox.commands.run("echo $MY_VAR")
print(result.stdout)  # "Hello from env\n"

sandbox.kill()
```

**Expected Output:**

```
Hello from env
```

***

## Related Classes

* **[Sandbox](/sdk/python/sandbox)** - Main sandbox class
* **[Commands](/sdk/python/commands)** - Command execution resource
* **[Files](/sdk/python/files)** - File operations resource

## See Also

* [Core Concepts: Environment Variables](/core-concepts/environment-variables) - Learn about environment configuration
* [Sandbox Class](/sdk/python/sandbox) - Access env via `sandbox.env`

## Related

* **[Getting Environment Variables](/core-concepts/environment/getting)** - Learn about getting env vars
* **[Setting Environment Variables](/core-concepts/environment/setting)** - Learn about setting env vars
* **[Updating Environment Variables](/core-concepts/environment/updating)** - Batch update env vars
* **API**: [GET /env](/api/vm-agent/get-env) - VM Agent API endpoint

## Next Steps

* Learn about [Getting Environment Variables](/core-concepts/environment/getting) to read values
* Explore [Setting Environment Variables](/core-concepts/environment/setting) to configure environment
* Review [Updating Environment Variables](/core-concepts/environment/updating) for batch updates
* **[CLI Environment Variables](/cli/commands/env)** - Manage environment variables from the command line

## Related

* **[Getting Environment Variables](/core-concepts/environment/getting)** - Learn about retrieving variables
* **[Setting Environment Variables](/core-concepts/environment/setting)** - Learn about setting variables
* **[Updating Environment Variables](/core-concepts/environment/updating)** - Learn about updating variables
* **[API: Environment Variables](/api/vm-agent/get-env)** - VM Agent API endpoints
