---
title: "CLI reference"
sidebar:
  order: 3
  icon: terminal
  label: "CLI"
description: "Install and authenticate the varsafe CLI, resolve context, and master the run/export workflows — plus the generated command reference."
---

import CliReference from '../generated/cli-reference.mdx';
import help from '../examples/offline/help.sh?raw';
import runInject from '../examples/cli/run-inject.sh?raw';
import exportFormats from '../examples/cli/export-formats.sh?raw';
import unsetAndContext from '../examples/cli/unset-and-context.sh?raw';
import githubActions from '../examples/config/github-actions-example.yml?raw';
import gitlabCi from '../examples/config/gitlab-ci-example.yml?raw';

<PageMeta />

The `varsafe` CLI puts your secrets into the processes that need them, without a `.env` file on disk. You, your pipelines and your coding agents run the same command, `varsafe run -- <command>`: the values reach the program, and the person or agent typing the command sees only what it prints.

<div class="vs-wide-only">

<img src="/images/cli-welcome.png" alt="varsafe CLI" />

varsafe CLI

</div>

## Installation

```bash
curl -fsSL https://varsafe.dev/install.sh | bash
```

The CLI is a single self-contained binary, not an npm package. The installer detects your operating system, architecture and C library, prints the result as a `Detected platform:` line, and downloads the matching build: Linux x64 or arm64 (glibc or musl), or macOS x64 or arm64. On Windows, run it inside WSL.

It installs to `~/.varsafe/bin` (set `VARSAFE_INSTALL_DIR` to choose another directory) and offers to add that directory to your `PATH` in `~/.zshrc`, `~/.bashrc` or `~/.config/fish/config.fish`. Check the install and explore the commands, no account needed:

<CodeBlock lang="bash" title="help.sh" code={help} />

To upgrade later, the binary updates itself, checking the signed release manifest first:

```bash
varsafe update
```

## Commands at a glance

Fifteen commands, none nested:

| Command  | Use it to                                                 |
| -------- | --------------------------------------------------------- |
| `run`    | Run a command with secrets as environment variables       |
| `get`    | Print one secret's value, for piping into another tool    |
| `set`    | Create or change a secret                                 |
| `unset`  | Remove a secret                                           |
| `list`   | List the secrets in an environment (alias: `ls`)          |
| `export` | Write secrets to a file or stdout                         |
| `import` | Bring the values of a `.env` file into an environment     |
| `use`    | Set the default project and environment                   |
| `status` | Show the credential, the current context, and what is in it |
| `login`  | Sign in, through the browser or with an API token         |
| `logout` | Revoke this machine's credential and clear it locally     |
| `whoami` | Show the credential this machine is using and what it may do |
| `doctor` | Check that the CLI can store credentials securely here    |
| `theme`  | Choose the colour palette (auto, dark, light)             |
| `update` | Update the CLI to the latest version                      |

Every command and flag is in the [generated reference](#command-reference) at the bottom of this page.

---

## Authentication

There are two ways to authenticate: an interactive browser login for humans, and an API token for machines.

### Browser login (default)

```bash
varsafe login
```

The CLI shows a confirmation code such as `7KQ2M-X9D4F` and opens your browser. Type that code into the approval page, choose what this login may do (**Read only**, **Standard** or **Full access**), and approve; the CLI finishes on its own. Your password never passes through the terminal. The code expires after 10 minutes, and the login lasts up to 180 days, or until the machine goes 90 days without using it.

Browser login keeps the credential encrypted under `~/.varsafe`, with the key in your operating system's keychain. On a machine with no keychain, a login run at a terminal falls back to a **machine token** instead: limited to the teams, projects and environments you choose, it lasts at most 30 days and is stored unencrypted in `~/.varsafe` (a directory only you can read). A CI job has nobody to approve a login and no keychain, so use a token there. Details: [Authentication](/reference/authentication#cli-authentication).

### API token (CI and automation)

Owners and admins create [API tokens](/reference/api-tokens) in the dashboard, under **Access → API tokens**. Three ways to supply one:

<Tab title="Environment variable">
```bash
# The CLI picks the token up automatically — no login step at all
export VARSAFE_API_TOKEN="vs_at_vsafe_example"
varsafe run -- ./deploy.sh
```
</Tab>

<Tab title="stdin">
```bash
# "-" reads the token from stdin — keeps it out of argv
secret-manager read varsafe-token | varsafe login -t -
```
</Tab>

<Tab title="Masked prompt">
```bash
# Interactive masked input — never lands in shell history
varsafe login -T
```
</Tab>

:::warning
There is no flag for passing a token inline. `varsafe login --token "$TOKEN"` is **rejected**, because the value would be visible in shell history and in `ps` output. Supply the token through the environment, on stdin, or via the masked prompt.
:::

For pipelines, prefer the environment variable and skip `login` entirely — see [CI/CD usage](#cicd-usage).

### Session commands

```bash
varsafe whoami   # which credential this machine uses, and what it may reach
varsafe logout   # revoke this machine's credential and clear it
```

`whoami` shows your account and, for each team, the scopes, projects and environments the login may reach; for an API token, its name, team, projects and environments.

For a browser login, `logout` revokes the credential on the server before clearing it, so a copy of the credentials file is useless afterwards. For an API token stored with `varsafe login -T`, it only clears the local copy: revoke the token in the dashboard if the machine is no longer trusted.

---

## Environment variables

| Variable                  | Purpose                                                                                                                             |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| `VARSAFE_API_TOKEN`       | API token for non-interactive auth — the primary CI variable. Used when this machine has no stored login: a `varsafe login` credential on the same machine takes precedence. `varsafe whoami` shows which one is in use |
| `VARSAFE_TOKEN`           | Alias, read when `VARSAFE_API_TOKEN` is not set. A bare `varsafe login` stores it as the machine's login                            |
| `VARSAFE_API_URL`         | Overrides the API base URL (default `https://api.varsafe.dev`) — for self-hosted or test stacks                                     |
| `VARSAFE_DEBUG`           | Set to any value to append a troubleshooting log to `~/.varsafe/debug.log`, readable only by you. A log over 5 MB is emptied at the next start. Writes to the file, not to your terminal |
| `VARSAFE_NO_UPDATE_CHECK` | Any non-empty value disables the interactive "update available" prompt, including `0` and `false`, as with `NO_COLOR`; an empty value does not. Set it in CI so the prompt cannot hang an unattended run |
| `VARSAFE_THEME`           | `auto`, `dark`, or `light` — overrides the saved palette for one invocation without rewriting settings. An unrecognized value is ignored |
| `NO_COLOR`, `FORCE_COLOR` | The usual conventions: `NO_COLOR` (any value) turns colour off; `FORCE_COLOR` turns it on for a pipe, unless it is `0`              |
| `VARSAFE_INSTALL_DIR`     | Read by the installer only: where to put the binary, as an absolute path (default `~/.varsafe/bin`)                                 |
| `VARSAFE_VERSION`         | Read by the installer only: install this release instead of the latest, for example `7.6.0` — useful for pinning CI                 |

There are no variables for the project or environment: use flags, a `.varsafe` file, or `varsafe use` (see [Context](#context)).

---

## Context

Commands that touch secrets need a project and environment. Resolution order:

1. **Flags** — `-p`/`--project` and `-e`/`--env` (or `-i`/`--project-id` in automation) always win
2. **Local `.varsafe` file** — found by searching from the current directory up to the git root
3. **Global saved context** — set via `varsafe use` outside a git repository
4. **Auto-selection** when there is only one choice; otherwise a prompt at a terminal, and an error in a script or CI job

:::note[One flag is enough inside a repository]
Inside a repository with a `.varsafe` file, a flag you leave out comes from that file (CLI 7.8.1 and later): `varsafe run -e staging -- …` runs against the repository's project, and `-p` naming the repository's project uses its environment. `-p` naming a different project borrows nothing: name its environment too, unless it has only one, or choose it at the prompt. CLI 7.8.0 and older took the missing half from the global context, which can name another project; `varsafe update` fixes that.
:::

```bash
# Set context — inside a git repo this writes a .varsafe file at the repo root,
# elsewhere it saves globally
varsafe use -p my-api -e development

# Pick interactively at a terminal; elsewhere, print the current context
varsafe use

# Clear the global context (a repo's .varsafe file stays: delete it to drop it)
varsafe use --clear
```

A `.varsafe` file holds only the project, environment and team IDs, with their names as a comment, never a secret value.

This script removes a secret and exercises the context lifecycle:

<details>
<summary>Tested script: unset-and-context.sh</summary>

<CodeBlock lang="bash" title="unset-and-context.sh" code={unsetAndContext} />

</details>

---

## Inject secrets into a process

`varsafe run` is the core workflow: it fetches secrets over TLS and injects them as environment variables into the child process. Nothing is written to disk; when the process exits, the secrets are gone.

```bash
varsafe run -- npm run dev
```

The command after `--` is executed argv-exact — no shell re-parsing, so quoting is preserved and arguments arrive in the child process exactly as you wrote them. Status messages (`Injecting 5 secrets from my-api/development`) go to stderr, so stdout stays clean for piping. `run` exits with the command's own exit code, so CI steps and wrappers behave as if the command ran directly.

That also means shell syntax is *not* interpreted: `;`, `|`, `&&`, `$()` and backticks reach your program as literal characters rather than being executed. This is deliberate — it stops a value such as a CI branch name from running as a command inside the process holding your secrets. When you do want a shell, ask for one explicitly with `--shell`, which takes a single command string:

```bash
varsafe run --shell 'bun run build && ./deploy.sh'
```

Prefer the argv form when you can. Reach for `--shell` only for pipes, `&&`, and redirection — and note that `--shell 'setup && exec app'` keeps your real process in the foreground, which matters for signal handling.

Shape what gets injected:

```bash
# Only secrets matching glob patterns (comma-separated, and the flag can be repeated)
varsafe run --include 'VITE_*,CRISP_*' -- bun run build
varsafe run --include 'VITE_*' --include 'CRISP_*' -- bun run build

# Rename injected keys: each secret is exposed with MONITORING_ prepended
# (e.g. DATABASE_URL becomes MONITORING_DATABASE_URL). Keys that already start
# with the prefix are left unchanged.
varsafe run --prefix monitoring -- ./run-monitoring.sh
```

`--include` selects *which* secrets are injected; `--prefix` renames them. They compose. Repeating `--include` unions the patterns, so the two forms above inject the same keys.

To merge a plaintext `.env` (local overrides that are not secrets), source it in the shell, inside the child, so its values win over the injected secrets:

```bash
varsafe run --shell 'set -a; . ./.env.local; set +a; exec npm start'
```

The full version, including the child process assertion:

<details>
<summary>Tested script: run-inject.sh</summary>

<CodeBlock lang="bash" title="run-inject.sh" code={runInject} />

</details>

### What `run` protects against

- **Your varsafe credential stays out of the command.** `run` removes `VARSAFE_API_TOKEN` and `VARSAFE_TOKEN` from the environment it hands to the command, so a build script or an agent's tool cannot read the token that fetched the secrets. Pass `--pass-credential` when the command itself calls `varsafe`. A command running as your user can still call `varsafe` with your stored login.
- **A secret cannot take over the command.** `run` refuses to inject a secret named after a variable that controls how programs load or launch code — `PATH`, `LD_PRELOAD`, `LD_LIBRARY_PATH`, `DYLD_INSERT_LIBRARIES`, `NODE_OPTIONS`, `PYTHONPATH`, `BASH_ENV`, `GIT_SSH_COMMAND`, `EDITOR` and the like — so someone who can edit one secret cannot run code on every machine that uses it. Set those in your shell instead.
- **Nothing is written to disk**, and shell syntax in arguments is not executed unless you ask for `--shell`.

### Encrypted `.env` files

`--env-file` merges an [encrypted `.env` file](/guides/encrypted-env) into the injected secrets. It accepts encrypted files only, can be repeated, and file values win over the API's.

```bash
varsafe run --env-file .env --env-file .env.extra -- npm start
```

The CLI sends the file's encrypted values to varsafe, which opens them for anyone allowed to read the environment and records the read. It needs the same access as `varsafe run` itself, so it works with a `varsafe login` or an API token. A file holds the values as they were when it was exported: run without a file for the current ones.

### Read a single value

For piping one secret into another tool, `varsafe get` prints just the value:

```bash
# Pipe a value into a tool that reads it from stdin: here, load a deploy key
# into ssh-agent without writing it to disk
varsafe get DEPLOY_SSH_KEY | ssh-add -

# Exact bytes, no trailing newline — for tools that are byte-sensitive.
# On Linux, /dev/shm keeps the file in RAM (macOS has none: use mktemp -d).
# mktemp creates the file readable by you only, under a name nobody else can
# predict or plant first; a plain redirect to a fixed name would do neither.
# Remove the file when the tool is done.
key_file=$(mktemp /dev/shm/signing.XXXXXX)
varsafe get SIGNING_KEY -n > "$key_file"

# Structured output: {key, value, version, updatedAt}
varsafe get DATABASE_URL --json
```

:::warning[Don't pass a value as an argument]
`some-tool "$(varsafe get DATABASE_URL)"` puts the value in the tool's argument list, which other users on the machine can read in `ps` output. Use `varsafe run -- some-tool` and let the tool read the variable from its environment, or pipe the value to its stdin.
:::

---

## Import a .env file

`varsafe import` (CLI 7.8.0 and later; `varsafe update` upgrades) brings the values of an existing `.env` into the current environment. It reads the file the way a `.env` loader does (quotes, `export`, multi-line values, comments), shows the plan by key name, and asks before writing at a terminal:

```bash
varsafe import .env --dry-run   # the plan, nothing written
varsafe import .env
```

Keys the environment already has are kept unless you pass `--replace-existing`; composed secrets are always kept. A key set twice, or a line that is not `KEY=value`, stops the import before anything is written, and no value is ever printed. In a protected environment it asks you to type the slug, or takes `--yes` in a script. [Move an existing .env into varsafe](/guides/migrate-from-dotenv) walks through the whole migration.

---

## Export secrets to a file

When a tool insists on a file, `varsafe export` writes one. The `.env` format is **encrypted by default**: the file starts with a `#@varsafe/v2/ek_<id>` header naming the environment key, and each value is sealed separately and bound to its variable name (`varsafe:v2:...`). The file shows which variables exist, not their values.

Sealing uses the environment's public key, which any credential that can read the environment's values may use, API tokens included; the first export from an environment creates its key. `varsafe run --env-file` opens the file again under the same access (see [encrypted .env](/guides/encrypted-env)). When another tool needs to read the values itself, write a plaintext file to RAM with `--plain --tmpfs` and delete it when done, or skip the file and use `varsafe run`.

```bash
# Encrypted .env (default)
varsafe export -o .env

# Plaintext requires an explicit opt-in
varsafe export --plain -o .env

# Other formats: compose (alias: env), docker (alias: kubectl), json, yaml (alias: yml) —
# auto-detected from the output file extension, or forced with -f
varsafe export --plain -o secrets.json
varsafe export --plain -f yaml

# Write to RAM-backed tmpfs (/dev/shm) so the file never touches disk
varsafe export --plain --tmpfs -o app.env
```

:::info[Encryption applies to the env format only]
`json`, `yaml`, `docker`, and `kubectl` outputs are always plaintext. Only the default `env` format encrypts values.
:::

The export flow, covering the encrypted default, `--plain`, and format variants:

<details>
<summary>Tested script: export-formats.sh</summary>

<CodeBlock lang="bash" title="export-formats.sh" code={exportFormats} />

</details>

---

## CI/CD usage

For pipelines, set `VARSAFE_API_TOKEN` from your CI secret store: no `varsafe login` step is needed. The installer cannot change the `PATH` of the job that runs it, so add `~/.varsafe/bin` to `PATH` yourself, as these examples do:

**GitHub Actions**

<CodeBlock lang="yaml" title=".github/workflows/deploy.yml" code={githubActions} />

**GitLab CI**

<CodeBlock lang="yaml" title=".gitlab-ci.yml" code={gitlabCi} />

Both files are validated in our test suite. [CI/CD pipelines](/guides/ci) explains each step: scoping the token, naming the project by ID, and what to do when a tool needs a file.

:::tip
Prefer `varsafe run` over file exports in CI — secrets stay in process memory. If a file is unavoidable, `varsafe export --plain --tmpfs` writes to RAM-backed `/dev/shm` on Linux; delete it in the same job step.
:::

---

## Exit codes

| Code | Meaning |
| ---- | ------- |
| 0    | Success |
| 1    | Authentication failed, a usage error (unknown command or flag, missing argument), or a failure with no more specific code |
| 2    | Network error |
| 3    | Validation error (a bad value or file) |
| 4    | Not found (project, environment or secret) |
| 5    | Permission denied |
| 99   | Internal error |

`varsafe run` is the exception: once the command starts, `run` exits with the **command's** exit code (128 plus the signal number if a signal ended it). If the command cannot start, `run` uses the shell's codes: 127 when it is not found, 126 when it cannot be executed.

---

## Uninstall

1. **Sign out**, so the credential is revoked on the server and not only deleted locally:

   ```bash
   varsafe logout
   ```

2. **Remove the binary and local data:**

   ```bash
   rm -rf ~/.varsafe
   ```

3. **Remove the `PATH` line** the installer added: `export PATH="$HOME/.varsafe/bin:$PATH"` in `~/.zshrc` or `~/.bashrc`, or `fish_add_path` in `~/.config/fish/config.fish`.

Also left behind, if you want a clean machine: the CLI's entry in the operating system keychain (service `varsafe`), `~/.cache/varsafe/run` if it was created, and any `.varsafe` context files in your repositories.

:::tip
This removes only the CLI. Your account, secrets and teams stay in varsafe, in the dashboard or after a reinstall.
:::

---

## Troubleshooting

Error messages, their causes, and the fix for each are in the
[troubleshooting guide](/guides/troubleshooting) — expired tokens, a stuck browser login,
`Not signed in`, an empty `varsafe list`, `Project is required` in CI, secure-storage
failures, and rate limits.

One case belongs here, because it happens before the CLI can report anything: **`varsafe:
command not found` right after installing.** The installer adds `~/.varsafe/bin` to your
shell config, which an already-open shell has not read yet. Restart the terminal, or add it
for the current session:

```bash
export PATH="$HOME/.varsafe/bin:$PATH"
```

If it is still missing, run the installer again and read its `Detected platform:` line —
it names the artifact chosen for your OS, architecture and C library.

---

## Command reference

Generated from the CLI's own `--help` output — always matches the shipped binary.

{/* The page's component map, so the generated reference gets the same code and table handling. */}
<CliReference components={props.components} />
