12. Handling Secrets with SOPS

Keep passwords, keys, and tokens out of the world-readable Nix store

Back in The NixOS Mental Model we leaned hard on one fact: every path under /nix/store is immutable and readable by anyone on the machine. That property is exactly what makes NixOS reproducible and cacheable — but it also sets a trap. The moment you need a database password, an API token, or a TLS private key in your configuration, that same store suddenly looks less like a feature and more like a public bulletin board. This article is about the standard NixOS answer: encrypt your secrets at rest, commit the ciphertext to git without a second thought, and decrypt only into a runtime-only path at activation. We'll use SOPS and the sops-nix module to do it.

The problem: the Nix store is world-readable

Here's the naive thing you might try first, and why it quietly betrays you. Say a service needs a password. You write it straight into configuration.nix:

Don't do this

services.myapp = {
  enable = true;
  # interpolated into a config file the app reads at startup
  password = "hunter2";
};

The problem isn't that this fails — it's that it works. To make the service start, NixOS has to write that password into a config file, and that config file is built by a derivation, which means it lands at some path like /nix/store/…-myapp.conf with mode 0444. Every path in the store is world-readable by design; the store is even mounted read-only precisely because it's meant to be shared. So now hunter2 is sitting in cleartext where any unprivileged user on the box can cat it, and it'll stay there until that store path is garbage-collected.

The rule to internalize

Anything you interpolate into a derivation ends up in the store, in cleartext, world-readable. A NixOS config is a big tree of derivations, so a secret written into the config is a secret written into the store. And because the store is content-addressed and immutable, you can't even "delete" it easily — it persists across generations until garbage collection.

It gets worse when you remember where the configuration itself lives. A flake-based NixOS config is a git repo — flake.nix, flake.lock, your host modules — and you almost certainly push it somewhere, maybe even a public forge. A hardcoded secret is now in your commit history forever, world-readable on disk and leaked to your remote. Stripping it out later means rewriting history, and you should assume it's already compromised.

So the requirement is precise:

  1. At rest — in the repo, on disk, in the store — a secret must be encrypted. It's fine for the ciphertext to be world-readable; that's the whole point of encryption.
  2. At runtime — when a service actually needs the plaintext — it must be decrypted into a location that is not in the store, is not in git, and is readable only by the users that need it.

That runtime location, on a sops-nix system, is /run/secrets — a tmpfs that lives only in RAM, is recreated on every boot, and never touches /nix/store. Getting a secret from "encrypted blob in git" to "a file at /run/secrets/foo owned by the right user" is exactly the job of the tooling we're about to set up.

What SOPS is

SOPS — short for Secrets OPerationS, originally built at Mozilla and now a CNCF project — is a command-line editor for encrypted files. Its defining trick is that it does not encrypt the file as an opaque blob. Instead it walks the structure of a YAML, JSON, INI, or dotenv file and encrypts only the values, leaving the keys in cleartext.

Plaintext secrets.yaml

database:
  host: db.internal
  password: hunter2
api_token: sk-live-abc123

Encrypted, on disk

database:
  host: ENC[AES256_GCM,data:9f2…,tag:…]
  password: ENC[AES256_GCM,data:aa71…,tag:…]
api_token: ENC[AES256_GCM,data:c40…,tag:…]

Why leave the keys readable? Because it keeps the file diff-friendly. You can see in a code review that someone added an api_token, or renamed password, without ever seeing a plaintext value and without the whole file turning into one giant unreadable blob every time a single byte changes. Each value is encrypted independently with AES-256-GCM.

Under the hood SOPS uses envelope encryption. It generates a random data key, encrypts every value with that data key, and then encrypts the data key itself once per recipient. That short encrypted-data-key section, plus a MAC over the whole file, lives in a sops: metadata block appended to the file. The upshot: the bulk data is encrypted once, but any recipient's private key can unwrap the data key and read everything.

Backends. SOPS can wrap the data key with cloud KMS (AWS, GCP, Azure), with PGP/GPG, or with age. For a personal-to-small-team NixOS setup, age is the recommended default: it's a single small binary, an age key is one short line of text (age1… public, AGE-SECRET-KEY-… private), and there's no keyring, web of trust, or expiry dates to manage. GPG works and you'll see it in older configs, but it drags in the entire GnuPG agent/keyring apparatus for very little benefit here.

A recipient is just "a public key that should be able to decrypt this file." With age, a recipient can be:

  • An age key you generated for yourself (or a teammate) — this is how humans edit the file.
  • A host SSH key, converted to an age recipient with ssh-to-age. Every NixOS box already has an Ed25519 host key at /etc/ssh/ssh_host_ed25519_key; sops-nix can use it directly to decrypt at activation, so you don't have to provision a separate key just for secrets. This is how machines decrypt.

Why sops-nix, and not the alternatives

agenix is the leaner cousin — it uses age directly (no per-value encryption; each secret is its own file) and is delightfully simple, but you lose the single-file, diff-friendly YAML and the multi-backend flexibility. git-crypt transparently encrypts whole files in a repo, but it's all-or-nothing per file and has no NixOS integration for decrypting at activation. Vault is a full secrets server — the right tool at real scale, massive overkill for a handful of hosts. sops-nix hits the sweet spot: one encrypted file per host (or shared), age keys for people and SSH host keys for machines, and a NixOS module that decrypts straight into /run/secrets at activation. It's the de-facto community default, and what we'll use here.

Here's the whole pipeline before we build it piece by piece — the encrypted file safe in git on the left, the world-readable store you must avoid at the bottom, and the runtime-only decrypted secret on the right:

From encrypted-at-rest to runtime-only plaintext secrets.yaml — in git db_password: ENC[AES256_GCM,…] api_token: ENC[AES256_GCM,…] recipients (can decrypt): age1yourkey… (you, to edit) age1hostkey… (the host, to run) safe to commit — values are ciphertext /nix/store — NEVER put plaintext here world-readable (mode 0444), immutable, shared, and often pushed to git via the flake anything interpolated into a derivation leaks bypass activation host age key unwraps /run/secrets — tmpfs, in RAM only /run/secrets/db_password hunter2 (decrypted plaintext) owner: postgres group: postgres mode: 0400 never in /nix/store, never in git, recreated fresh on every boot a service reads the PATH /run/secrets/db_password — never the value — so plaintext stays out of the store

Adding sops-nix to a flake

sops-nix ships a NixOS module. Wiring it in is the usual two-step flake dance: declare the input, then add the module to your host. Start with the input, and make it follow your nixpkgs so you don't end up evaluating two copies:

flake.nix — the input

{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.05";
    sops-nix.url = "github:Mic92/sops-nix";
    sops-nix.inputs.nixpkgs.follows = "nixpkgs";
  };
  outputs = { nixpkgs, sops-nix, ... }: {
    nixosConfigurations.bluewhale = nixpkgs.lib.nixosSystem {
      system = "x86_64-linux";
      modules = [
        ./configuration.nix
        sops-nix.nixosModules.sops
      ];
    };
  };
}

Adding sops-nix.nixosModules.sops to the module list is what brings the sops.* options into scope. From here on, everything is configured through those options in your ordinary host modules — there's no separate tool to run at rebuild time; decryption happens as part of nixos-rebuild switch. It's also worth having the sops CLI itself available where you edit secrets; drop it into a dev shell (see Dev Shells) or your user packages so sops and age are on your PATH.

Encrypting your first secret

SOPS needs to know who can decrypt a given file. That policy lives in a .sops.yaml file at the root of your repo, in a set of creation rules. When you create or edit a file, SOPS finds the first rule whose path_regex matches and encrypts to that rule's recipients.

First, generate an age key for yourself — this is the human key you'll use to edit secrets:

mkdir -p ~/.config/sops/age
age-keygen -o ~/.config/sops/age/keys.txt

age-keygen prints the public key (a line starting age1…) to stderr and writes the matching private key into keys.txt. Guard that file — it never goes in the repo. The public key is what goes into .sops.yaml. You'll also want the host's recipient so the machine can decrypt at activation; derive it from the host's SSH public key:

nix-shell -p ssh-to-age --run 'ssh-to-age < /etc/ssh/ssh_host_ed25519_key.pub'

That prints another age1… line — the host, expressed as an age recipient. Now write both into .sops.yaml. Using YAML anchors keeps it readable when you have several recipients:

.sops.yaml — creation rules

keys:
  - &admin_jo age1yourpersonalkey0000000000000000000000000000000000000000
  - &host_bluewhale age1thehostkey00000000000000000000000000000000000000000
creation_rules:
  - path_regex: secrets/[^/]+\.yaml$
    key_groups:
      - age:
          - *admin_jo
          - *host_bluewhale

Read that as: "any secrets/*.yaml file should be decryptable by both admin_jo and host_bluewhale." The person needs to be a recipient so they can edit the file; the host needs to be a recipient so it can decrypt at boot. Now create the file:

sops secrets/secrets.yaml

sops opens your $EDITOR on a decrypted view. You type plain YAML; when you save and quit, SOPS encrypts every value in place using the recipients from the matching rule. There is no separate "encrypt" step — the file only ever exists as ciphertext on disk. What lands there looks like this:

What's actually on disk

db_password: ENC[AES256_GCM,data:Zt9k…,iv:8f…,tag:pQ…,type:str]
api_token: ENC[AES256_GCM,data:Lm2…,iv:c1…,tag:oX…,type:str]
sops:
  age:
    - recipient: age1yourpersonalkey0000000000000000000000000000000000000000
      enc: |
        -----BEGIN AGE ENCRYPTED FILE-----
        …encrypted copy of the data key for you…
        -----END AGE ENCRYPTED FILE-----
    - recipient: age1thehostkey00000000000000000000000000000000000000000
      enc: |
        -----BEGIN AGE ENCRYPTED FILE-----
        …encrypted copy of the data key for the host…
        -----END AGE ENCRYPTED FILE-----
  lastmodified: "2026-07-06T12:00:00Z"
  mac: ENC[AES256_GCM,data:…]

Notice the shape. The keys (db_password, api_token) are cleartext, so diffs stay meaningful. The values are ENC[…]. And the sops: block carries one enc entry per recipient — each is the same data key encrypted under a different age public key. That's the envelope: two recipients, one data key, two wrapped copies of it. Commit this file with confidence; the ciphertext is what you want in git.

Decrypting at activation

Now the NixOS side. First tell sops-nix which file to read and which key the host should use to decrypt. On a NixOS box the simplest choice is the existing SSH host key — no extra provisioning:

Host wiring

sops.defaultSopsFile = ./secrets/secrets.yaml;
sops.age.sshKeyPaths = [ "/etc/ssh/ssh_host_ed25519_key" ];

sshKeyPaths points at the host's private SSH key; sops-nix converts it to an age identity in memory and uses it to unwrap the data key. (If you'd rather use a dedicated age key, set sops.age.keyFile = "/var/lib/sops-nix/key.txt"; instead, optionally with sops.age.generateKey = true; to have it created on first boot.) Then declare each secret you want materialized:

Declaring a secret

sops.secrets.db_password = {
  owner = "postgres";
  group = "postgres";
  mode = "0400";
};

The attribute name (db_password) is, by default, the key to pull out of the YAML file. At activation, sops-nix decrypts that one value and writes it to /run/secrets/db_password with the owner, group, and mode you specified. Under the hood /run/secrets is a symlink into a versioned tmpfs directory (/run/secrets.d/<n>/), owned root:keys — it lives in RAM, is rebuilt on every activation and every boot, and is never part of /nix/store.

The crucial move is how a service consumes it. You reference the secret's path, not its value:

Referencing the path, not the value

services.postgresql.enable = true;
# WRONG — would bake plaintext into the store:
#   passwordFile = builtins.readFile config.sops.secrets.db_password.path;
# RIGHT — pass the path; the service reads it at runtime:
services.myapp.settings.passwordFile = config.sops.secrets.db_password.path;

config.sops.secrets.db_password.path evaluates to the string "/run/secrets/db_password" — a filename, not the contents. That string is all that ends up in the store; the plaintext behind it only ever exists in the runtime tmpfs, read directly by the service when it starts. This is why so many NixOS options come in passwordFile / tokenFile / keyFile variants rather than plain password: the file-based form exists precisely so you can hand it a /run/secrets path instead of a literal.

The one-sentence version

Store the ciphertext in git, decrypt to a tmpfs at activation, and have services read the path under /run/secrets — never interpolate the plaintext into any derivation.

See it decrypt (and see who's locked out)

Below, flip a secrets file between its two lives — the encrypted-at-rest view you'd commit to git, and the decrypted /run/secrets view a running service sees. Toggle recipients on and off to watch who can and can't unwrap the data key.

Rekeying and rotation

Recipients and secret values both change over time — a teammate joins, a laptop is re-imaged, a token leaks. There are three distinct operations, and it's worth keeping them straight.

Adding or removing a recipient. Edit the recipient list in .sops.yaml (add the new age1…, or delete a departed one), then re-encrypt the data key to the new set:

sops updatekeys secrets/secrets.yaml

updatekeys does not touch the encrypted values — it only rewraps the data key for the current recipients in .sops.yaml. That's cheap and produces a clean, values-unchanged diff. Run it whenever you change who can decrypt.

Rotating a host key. If a machine is rebuilt, its SSH host key (and thus its age recipient) changes. Generate the new host recipient with ssh-to-age, swap it into .sops.yaml, and run sops updatekeys. Until you do, the rebuilt host is no longer a recipient and will fail to decrypt at activation — see the gotchas below.

Rotating the secret value. If a password or token itself is compromised, the recipient list is irrelevant — you need a new value and you should assume anyone who had the old ciphertext could read it. Change the credential at the source (rotate the API token, reset the DB password), then sops secrets/secrets.yaml, replace the value, save. For hygiene you can also rotate the underlying data key itself (so old ciphertext can't be reused even if an old recipient key leaks) with:

sops rotate -i secrets/secrets.yaml

A subtlety worth flagging: sops-nix only re-materializes /run/secrets when you rebuild. If a secret backs a running service, set sops.secrets.<name>.restartUnits = [ "myapp.service" ]; so the service is restarted when the decrypted value changes — otherwise the process keeps using the old value it read at startup.

Gotchas & troubleshooting

Most sops-nix pain falls into a handful of recognizable buckets. The broader debugging workflow lives in Troubleshooting; these are the secrets-specific ones.

  • Host key absent on a fresh install (the chicken-and-egg). A brand-new machine can't decrypt a file it isn't yet a recipient of. You need the host's SSH key to exist first, then add its ssh-to-age recipient to .sops.yaml, run sops updatekeys, and only then does that host's activation succeed. When bootstrapping, either generate the host key and rekey before the first "real" rebuild, or provision the key out of band (e.g. copy it in during install).
  • Secret used before it exists (ordering). sops-nix sets secrets up during activation, generally before normal services start, so most units find their file waiting at /run/secrets. The classic exception is user passwords: users are created very early, before ordinary secrets are decrypted. For a hashed user password, use sops.secrets.<name>.neededForUsers = true;, which decrypts it into /run/secrets-for-users ahead of user creation, and reference it via users.users.<name>.hashedPasswordFile.
  • Wrong owner or mode. If a service logs "permission denied" reading its secret, the decrypted file's owner/group/mode probably don't match the user the service runs as. Check the actual account (many services run as a DynamicUser or a dedicated system user, not root) and set owner/group to match, with a restrictive mode like "0400".
  • age vs GPG recipient mismatch. "no matching creation rules" or "failed to decrypt" usually means the identity you're presenting isn't among the file's recipients. Confirm the file was encrypted to the key you're actually using — human age key when editing, host age key at activation — and that .sops.yaml matches. Don't mix a GPG-encrypted file with an age-only host config; the backends must line up.
  • Accidentally committing cleartext. The scariest failure mode is a plaintext secret slipping into git before SOPS touched it. Install a SOPS pre-commit hook (or a git filter) that rejects any commit containing an unencrypted secrets/*.yaml — it checks for the sops: metadata block and blocks the commit if it's missing. If a plaintext secret does land in history, rotate the value immediately; assume it's burned.

Where to go next

You now have the core loop: encrypt values at rest with age, commit the ciphertext, and let sops-nix decrypt into a runtime-only tmpfs that services read by path. Two natural extensions:

  • Per-project secrets. The same file-not-value discipline applies outside NixOS system config. A dev shell can load a decrypted .env for local development so a project's tokens live encrypted in its repo rather than scattered across your shell history.
  • Deploying to remote hosts. Because each host is its own recipient, the same encrypted file can serve a fleet: add every host's age recipient to .sops.yaml, and deployment tools like deploy-rs or colmena ship the ciphertext, with each machine decrypting locally at activation. Secrets never travel in plaintext, and no host can read another's material unless you list it as a recipient.

Key Takeaways

  • The store is world-readable: anything interpolated into a derivation lands in /nix/store in cleartext (mode 0444), and your flake repo is usually pushed to git — so secrets must be encrypted at rest.
  • SOPS encrypts values, not keys: YAML/JSON keys stay readable for diff-friendly reviews; each value becomes ENC[AES256_GCM,…] via envelope encryption with a per-file data key.
  • age is the sane default: a one-line key, no keyring; recipients are your personal age key (to edit) and the host's SSH key via ssh-to-age (to decrypt at activation).
  • Decrypt to a tmpfs: sops-nix writes secrets to /run/secrets/<name> with owner/group/mode, in RAM, never in the store; services reference the path (config.sops.secrets.<name>.path), never the value.
  • Rekey vs. rotate: sops updatekeys changes who can decrypt without touching values; editing (or sops rotate) changes the value/data key.
  • Watch the edges: fresh-install host-key chicken-and-egg, neededForUsers for user passwords, matching owner/mode, and a pre-commit hook so cleartext never reaches git.

Secrets were the last thing standing between "my config builds the same everywhere" and "my config is safe to push everywhere." With sops-nix, the encrypted file is just another tracked artifact and the plaintext only ever exists in RAM on the machines entitled to it. Next, we turn to what to do when a build doesn't go to plan: Troubleshooting NixOS builds and flake gotchas.