This page covers how to set and use environment variables in a sandbox, and default environment variables inside the sandbox.

Setting environment variables

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

1. Global environment variables

You can set global environment variables when creating a sandbox.
import { Sandbox } from 'novita-sandbox/code-interpreter'

const sandbox = await Sandbox.create({
  envs: {
    MY_VAR: 'my_value',
  },
})

const result = await sandbox.commands.run("echo $MY_VAR")

console.log(result)

// Output example:
// { exitCode: 0, error: undefined, stdout: 'my_value\n', stderr: '' }

await sandbox.kill()

2. Setting environment variables when running code

You can set environment variables for specific code execution call in the sandbox.
If you had a global environment variable with the same name, it will be overridden.
import { Sandbox } from 'novita-sandbox/code-interpreter'

const sandbox = await Sandbox.create()

const result = await sandbox.runCode('import os; print(os.environ.get("MY_VAR"))', {
  envs: {
    MY_VAR: 'my_value',
  },
})
console.log(result.logs)

await sandbox.kill()

3. Setting environment variables when running commands

You can set environment variables for specific command execution in the sandbox.
If you had a global environment variable with the same name, it will be overridden.
import { Sandbox } from 'novita-sandbox/code-interpreter'

const sandbox = await Sandbox.create()

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

console.log(result)

// Output example:
// { exitCode: 0, error: undefined, stdout: '123\n', stderr: '' }

await sandbox.kill()