Pass configuration and secrets into SmolVM sandboxes
You can pass configuration values, API keys, and other settings into a sandbox using environment variables. SmolVM supports two approaches: setting variables when you create the sandbox, or adding them at runtime while the sandbox is running.Variables are written to /etc/profile.d/smolvm_env.sh inside the guest and automatically available in new login shells.
def unset_env_vars(self, keys: list[str]) -> dict[str, str]: """Remove environment variables from a running VM. Args: keys: Variable names to remove. Returns: Mapping of removed keys to their previous values. """
from smolvm import SmolVMdef main() -> int: with SmolVM() as vm: print(f"VM started: {vm.vm_id}") print("\n1) Set environment variables") vm.set_env_vars({"APP_MODE": "dev", "DEBUG": "1"}) print(vm.list_env_vars()) print("\n2) Use env vars in a command") # vm.run() opens a fresh SSH session, so new values are available print(vm.run("echo APP_MODE=$APP_MODE DEBUG=$DEBUG").output) print("\n3) Remove one variable") removed = vm.unset_env_vars(["DEBUG"]) print(f"Removed: {removed}") print(vm.list_env_vars()) print("\nDone.") return 0if __name__ == "__main__": raise SystemExit(main())
from smolvm.env import validate_env_key# Valid keysvalidate_env_key("MY_VAR") # OKvalidate_env_key("_PRIVATE") # OKvalidate_env_key("VAR_123") # OK# Invalid keysvalidate_env_key("") # ValueError: cannot be emptyvalidate_env_key("123VAR") # ValueError: must start with letter or _validate_env_key("MY-VAR") # ValueError: only [A-Za-z0-9_] allowed
Keys must match the pattern: [A-Za-z_][A-Za-z0-9_]*
SmolVM uses shlex.quote() to safely handle special characters:
vm.set_env_vars({ "MESSAGE": "Hello, World!", "PATH_VAR": "/usr/local/bin:/usr/bin", "COMPLEX": "value with 'quotes' and spaces",})# All values are safely quoted in the generated shell script
with SmolVM() as vm: # Start in dev mode vm.set_env_vars({"APP_MODE": "dev"}) vm.run("start-app") # Switch to production mode vm.set_env_vars({"APP_MODE": "production"}) vm.run("restart-app")