--- title: "SOPS: A Complete Guide To Encrypting Secrets in Git With Secrets OPerationS" canonical: "https://infisical.com/blog/mozilla-sops" published: "2026-11-30" tags: ["SOPS", "Secrets Management", "DevOps"] source-index: https://infisical.com/llms.txt --- # SOPS: A Complete Guide To Encrypting Secrets in Git With Secrets OPerationS Your application needs a database password, an API key, and an email server password. The code lives in Git, but those three values obviously can't. So, what happens? They end up in a .env file that gets copied from laptop to laptop, stored in a password manager, and eventually deployed to each service's servers. But my .env isn’t the same as your .env, and if Alice left for Anthropic six months ago, why does she still have all our keys? SOPS (Secrets OPerationS) is a neat, open-source command-line tool to solve this problem. Originally built by Mozilla in 2015 (and donated to the CNCF in 2023), it encrypts values in YAML, JSON, ENV, INI, and binary files while keeping the keys readable. This means the encrypted file can sit in the repo next to the code, and a pull request still shows which value changed without showing what it changed to. That seems like magic. You install a binary, generate a key, and you’re encrypting files. No server to run, and nothing to pay for. Anyone whose key is listed in the file can decrypt it. But it is still a file. Only the people whose keys are listed inside can read it. So adding Bob means re-encrypting the file for him. Removing Alice means re-encrypting without her, which does nothing about the six months of commits already on her laptop. Rotating the database password means a commit, then redeploying everything that reads the file. And if you want to know who read the production key last Tuesday, there is no record anywhere. SOPS also has no concept of machine identity because identity is “anyone who can access the keys”. That means a secret can only get to a machine if a human manually copy-pastes the ciphertext there. A secrets manager such as Infisical takes a different route. The secret stays on a server, anything that needs it asks at runtime, and the server decides who can read it and sees each read. Which works best for you depends on how many people and machines need to read your secrets, how often that list changes, and what you personally want to manage. ## How a SOPS file works Let’s say you have a plain YAML file full of production secrets at secrets/prod/app.yaml. Something like this:
``` DATABASE_URL: postgres://app:[email protected]:5432/app API_KEY: sk_live_fake_prod_7d3e9a1b SMTP_PASSWORD: fake-smtp-prod-pass-4410 ```
Committing that as is is obviously a no-go. It puts those passwords in Git history for good. So instead you reach for [SOPS](https://github.com/getsops/sops), and run:
``` sops encrypt --in-place secrets/prod/app.yaml ```
The same file now looks something like this:
``` DATABASE_URL: ENC[AES256_GCM,data:R14lYlllhIq2sy3jNa2eSXvFXoWs6VegupqWYo5j8FJWo6zdgEM+W9cRTTAz1pADENt5,iv:pgpfjHNHVlqkz73ZetM/sAPAK2EnyVpNyYlQ/G9iB6E=,tag:P+8TYZR+ObZzaIyLRZ5vhQ==,type:str] API_KEY: ENC[AES256_GCM,data:hTfWLPPdiuzK7/AYQkPTqdHNNCoS309XNjU=,iv:TgxSySobeh+YzPhexBXLJR60tE3x3DCuI4UmznM87ho=,tag:ql6KkJ8i6koQTyNH4QAsJQ==,type:str] SMTP_PASSWORD: ENC[AES256_GCM,data:/g3t++TP+crw3ULniIydllIqRKF+Ybfy,iv:DYdKFJRy5ish12kkHelC1H0vMdNiWcsYbMga7t6LrZs=,tag:O3ieaOsy/eFix6McH6r9Iw==,type:str] sops: age: - enc: | -----BEGIN AGE ENCRYPTED FILE----- YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBCcGxERk5DSkkvdzZWbW5X UlhYRCtMMG9LMm10L2EvY1hrMTk4MHB4MEhVCk1Pdzd5bTdaNzA0MW5CTGprMGJD N1JsRXp5K3JPcWRQMGhLWjBnRm1sTncKLS0tIENuYVpSTkc1dEFubWkvK1ZKV0JD T3hLV3VzMHFtMU5WVzdNcXV1UVp2NjQK8v2S7Gb29B+WDREX3v9L5JjmwiICB4BW 0/kpqadTMHCOyfJmMmqUXFYUZc9Gvn/pmnllmg6YLUjRNpk/AIpoRQ== -----END AGE ENCRYPTED FILE----- recipient: age1eqaj8pzcs26j4jyyn4zv5gq89gt39pk30wx9h68v6asmrnqfdfqsh64x6r - enc: | ... recipient: age1af43rzs20meqeqw6vx0r750xwwm0p03thkxhcu30qe8duhmvgvnqzzrm30 lastmodified: "2026-11-02T02:28:05Z" mac: ENC[AES256_GCM,data:mWrNWRys5SFeq/hrWZP0N3Q3tZhs/8cw5VtmnCPbn3kkzPG4gdesCzZgX5iO9pECKNZw7SMBH6rKLFQ3BYhjASreUWdpwmvGiSOUuDtLGrqzWCQmk2lIq26+zqmxW4gK1fw9EL/GpXZFcqbKC9JLArysM8p9oYwcbf8CdTovWhg=,iv:E/xrRu31p73L/GSYQnK81D3+JRGgpRbv8V6L+9tdjCU=,tag:4qV3TOHjj13atg99bhiIow==,type:str] unencrypted_suffix: _unencrypted version: 3.13.3 ```
What happened? Let’s look at the first line.
``` DATABASE_URL: ENC[AES256_GCM,data:R14lYlll...,iv:pgpfjHNH...,tag:P+8TYZR+...,type:str] ```
The keys are still there, but every value has turned into one of these ENC\[...\] blobs. SOPS generated a random key for this file (the data key) and encrypted each value separately with it using AES-256-GCM.  Inside the brackets are: * `AES256_GCM`, the cipher used for every value. * `data`, the encrypted value itself, base64 encoded. * `iv`, the random initialization vector SOPS picked for this one value, so two identical passwords don't produce identical ciphertext. * `tag`, the authentication tag GCM produces, which lets SOPS know the value hasn't been tampered with. * `type`, the value's original type, so a number comes back as a number and a boolean as a boolean. Then there’s the `sops` block. Here, the critical part is `age`.
``` age: - enc: | -----BEGIN AGE ENCRYPTED FILE----- ... -----END AGE ENCRYPTED FILE----- recipient: age1eqaj8pzcs26j4jyyn4zv5gq89gt39pk30wx9h68v6asmrnqfdfqsh64x6r - enc: | ... recipient: age1af43rzs20meqeqw6vx0r750xwwm0p03thkxhcu30qe8duhmvgvnqzzrm30 ```
`age` stands for Actually Good Encryption ([maybe](https://www.bleepingcomputer.com/news/security/new-agelocker-ransomware-uses-googlers-utility-to-encrypt-files/amp/)). Every value in this file was encrypted with the same key, a random 256-bit number SOPS generated just for this file. That’s the data key. It’s symmetric, so the same number encrypts and decrypts. With it, you can read every value. Don’t, and you can’t. That turns “who can read this file” into “who has the data key.” SOPS can’t write it into the file in plain text, and it doesn’t want you passing it around by hand. So it does this instead: 1. Each person or machine that should be able to read the file has an [age](https://github.com/FiloSottile/age) key pair, made with `age-keygen`. The public key is the `age1...` string in the `recipient` lines. It can only encrypt, so it’s safe to put in a repo. The private key stays on its owner’s machine. 2. SOPS encrypts the data key with alice’s public key. That’s the first `enc` block. 3. It encrypts the same data key again with the deploy job’s public key. That’s the second block. Both blocks hold the same data key, and each one opens with a different private key. Decrypting runs it backward: 1. alice runs `sops decrypt`. 2. SOPS finds the `enc` block made for her public key. 3. Her private key, a file on her laptop, decrypts that block. Out comes the data key. 4. The data key decrypts the three values. The deploy job does the same with its own block. bob, who isn’t in the list, has a private key that opens neither block, so he gets an error and nothing else.  So Git contains three encrypted values and two encrypted copies of the key that decrypts them. None of it is readable without a private key from the list, and the private keys never go in the repo. “Never commit secrets” still holds. ## Setting up SOPS with age On a Mac, you can `brew install sops age` to get both packages. On Linux, SOPS is a [binary](https://github.com/getsops/sops/releases) (or a .deb or .rpm) from the [releases page](https://github.com/getsops/sops/releases), and age comes baked in to Debian, Ubuntu, Fedora, and most other distros. The first thing to do is generate a key pair:
```sh age-keygen -o alice.txt ```
This will print your public key in the terminal and create `alice.txt` with both private and public keys:
``` # created: 2026-11-04T09:21:45-05:00 # public key: age1lk7e3vveyja5fl5nxrlkr099k85j4jlvqkjknh4j0ek6ans86u5q3lvjje AGE-SECRET-KEY-17YCJSKGTL0KPQZXTYXEFCHD2JP7Y682X8708C2VDCA493JC2JC6S0W9990 ```
The public key goes in the repo, in plain text. It can only encrypt, so it isn’t a secret. The private key decrypts, and it stays with Alice and is never committed. Each individual, machine, or service that needs access can get its own key pair. Next, tell SOPS who the recipients are. You could pass `--age <public key>` on every command, but the normal way is a `.sops.yaml` at the root of the repo:
``` creation_rules: # dev: both developers - path_regex: ^secrets/dev/.*\.yaml age: >- age1eqaj8pzcs26j4jyyn4zv5gq89gt39pk30wx9h68v6asmrnqfdfqsh64x6r, age1ajt20qx7pmg2lxlft69grkhn2m4tjcgvafdzlp3jr98tucemp5nqvga7gd # prod: alice and the deploy job - path_regex: ^secrets/prod/.*\.yaml age: >- age1eqaj8pzcs26j4jyyn4zv5gq89gt39pk30wx9h68v6asmrnqfdfqsh64x6r, age1af43rzs20meqeqw6vx0r750xwwm0p03thkxhcu30qe8duhmvgvnqzzrm30 ```
Each entry under `creation_rules` is a rule with two parts (and an optional comment): 1. A pattern for which files it covers (`path_regex`) 2. The public keys those files get encrypted for (`age`) When you encrypt a file, SOPS finds [the first rule whose pattern matches](https://github.com/getsops/sops) the file’s path and uses that rule’s keys as the recipients. So here, anything under secrets/dev/ is encrypted for two keys. The first is alice’s (`age1eqaj...`), the second is bob’s. Anything under secrets/prod/ is encrypted for alice again and for the deploy job’s key (`age1af43...`). With that in place, `sops encrypt --in-place secrets/prod/app.yaml` picks alice and ci. Bob isn’t in the prod rule, so he can read the dev secrets but not the production ones. That is fundamentally how permissions work with SOPS: which key appears in which rule. [SOPS looks](https://getsops.io/docs/reference/) for `.sops.yaml` in the working directory and its parents. The rules apply when a file is first encrypted. Change the list later, and existing files stay as they were until you run `sops updatekeys` on them. ## Where SOPS looks for your age key The private key is the one thing SOPS can't get from the repo, so you have to tell it where it is. There is no `--age-key-file` flag. Instead, the private key comes from an environment variable or a default file. On a laptop, the usual way is `SOPS_AGE_KEY_FILE`:
```sh SOPS_AGE_KEY_FILE=~/sops-demo-keys/alice.txt sops decrypt secrets/prod/app.yaml ```
There are three other ways to hand SOPS the key to use anywhere that isn't a laptop: * `SOPS_AGE_KEY` holds the key itself. This is for CI, where the key lives in the CI system's secret store and the job exposes it as a variable. * `SOPS_AGE_KEY_CMD` holds a command that prints the key, so it can come from a password manager. * If nothing is set, SOPS reads a default file called keys.txt. On Linux that's `~/.config/sops/age/keys.txt`, on macOS `~/Library/Application Support/sops/age/keys.txt`, and on Windows `%AppData%\sops\age\keys.txt`. Put Alice's key there, and sops decrypt works automatically. When it goes wrong, the error says, "`Failed to get the data key required to decrypt the SOPS file`," and the line underneath tells you what's wrong. * `failed to load age identities` means SOPS found no key anywhere, and the message goes on to list every place it looked, so check the path. * `no identity matched any of the recipients` means it found your key, but your public key isn't in the file's recipient list. No path setting fixes that one. Someone who can already decrypt the file has to add you. ## Running the app in production So far, everything has been about the file. Now you have a service to run in production, and it needs those three values. The machine that runs your app must be able to decrypt the file, so it must be a recipient, the same as Alice. That means: 1. Give it a key pair. For instance, above we generated a key for a CI job with `age-keygen -o ci.txt`. 2. Put that public key in the prod rule in `.sops.yaml`. If the prod file already exists, run `sops updatekeys secrets/prod/app.yaml` afterward to re-wrap the data key for the new list of recipients. 3. Get the private key onto the machine. SOPS can't do this part for you. Put the key into whatever that environment already uses for secrets: a CI secret, a Kubernetes Secret, or a file with tight permissions on a VM. 4. Start the app through SOPS, so the values are decrypted straight into its environment:
```sh SOPS_AGE_KEY_FILE=/etc/app/ci.txt sops exec-env secrets/prod/app.yaml "python3 app.py" ```
Nothing is written to disk. The process gets the values, and when it exits, they're gone. If the program reads a config file rather than variables, `sops exec-file` passes it the decrypted contents as a temporary file. So the pattern is a key on the machine, exposed to SOPS, and the app started through SOPS. Where the app runs changes steps 3 and 4\. * **CI**. The private key is a secret in the CI system (a GitHub Actions repository secret, a GitLab CI/CD variable) and is exposed to the job as `SOPS_AGE_KEY`. The step is the same `exec-env` command. * **Kubernetes with Flux.** You don't run `exec-env`. [Flux decrypts for you](https://fluxcd.io/flux/guides/mozilla-sops). Put the private key in a Secret (`kubectl create secret generic sops-age --namespace=flux-system --from-file=age.agekey=ci.txt`), add a `decryption` block with `provider: sops` and `secretRef: {name: sops-age}` to the Kustomization, and commit Secret manifests encrypted with the `encrypted_regex` rule from the setup section. Flux turns them into real Secrets on the next reconcile. Argo CD needs [KSOPS](https://github.com/viaduct-ai/kustomize-sops) or [helm-secrets](https://github.com/jkroepke/helm-secrets) to do the same. * **Terraform**. The [carlpett/sops provider](https://registry.terraform.io/providers/carlpett/sops/latest/docs) reads the file as a `sops_file` data source, and you use `data.sops_file.prod.data["DATABASE_URL"]` like any other value. The decrypted value then ends up in Terraform state, so [the state file needs the same protection as the secrets](https://infisical.com/blog/terraform-secrets-management). Each of those places now holds a private key. Because the process decrypts the file at startup, it has the values as of that moment, so when the file changes, the process has to start again. Infisical takes a different path to the same place. The machine gets an identity, a client ID, and a secret created in Infisical instead of a key and a copy of the file. When the app starts, it asks the server for the current values:
```sh infisical secrets-manager run --env=prod -- python3 app.py ```
The three values it injected are the ones sitting in the project's prod environment.  Same result as SOPS. On a developer's machine `infisical secrets-manager run` uses their login, and in CI it logs in as the machine identity. You create an `InfisicalStaticSecret` resource naming the project, environment, and path, point it at an `InfisicalAuth` that holds the identity’s client ID and secret, and the [operator](https://infisical.com/docs/integrations/platforms/kubernetes/overview) writes the values into a Kubernetes Secret and refreshes it on the interval you set. The server decides who gets what when they ask, so nothing needs to be encrypted in the repo and no recipient list needs to stay up to date. ### Rotating a value The database password has to change. With SOPS, that's an edit and a commit:
```sh SOPS_AGE_KEY_FILE=~/sops-demo-keys/bob.txt sops set secrets/prod/app.yaml '["DATABASE_URL"]' '"postgres://app:[email protected]:5432/app2"' ```
`git diff` will show three changed lines: 1. The `DATABASE_URL` value. 2. `Lastmodified`, the timestamp SOPS writes each time it saves the file. 3. `mac`, the checksum over all the values. One value is different now, so the checksum is too. Then each process that decrypted the old file has to start again to get the new value. That means redeploying every service, worker, and cron job that reads the file in each repo where this value is encrypted. You still have to change the password in the database, keeping the old one valid until the last consumer has restarted. With Infisical, the change is one command against the one place the value lives:
```sh infisical secrets set --env=prod DATABASE_URL=postgres://app:[email protected]:5432/app2 ```
 The server records it as version 2 and keeps version 1 in [the secret's history](https://infisical.com/docs/documentation/platform/secret-versioning), so if the new password turns out to be wrong, the old one is a click away.  Consumers still have to pick up the new value, but from one place. A restart does that, or in Kubernetes, the operator refreshes it, which can [restart the Deployments that use the Secret](https://infisical.com/docs/integrations/platforms/kubernetes/infisical-static-secret-crd) for you. For database passwords specifically, Infisical can also change the password on the database itself, or issue [short-lived credentials](https://infisical.com/docs/documentation/platform/dynamic-secrets/overview) that expire on their own. ### Giving someone access Bob needs production. He's a recipient like anyone else, so his public key goes in the prod rule, and someone who can already read the file runs updatekeys:
```sh SOPS_AGE_KEY_FILE=~/sops-demo-keys/alice.txt sops updatekeys -y secrets/prod/app.yaml The following changes will be made to the file's groups: Group 1 age1eqaj8pzcs26j4jyyn4zv5gq89gt39pk30wx9h68v6asmrnqfdfqsh64x6r age1af43rzs20meqeqw6vx0r750xwwm0p03thkxhcu30qe8duhmvgvnqzzrm30 +++ age1ajt20qx7pmg2lxlft69grkhn2m4tjcgvafdzlp3jr98tucemp5nqvga7gd ```
The data key gets wrapped a third time, for bob's key. The values don't change, and the commit is a normal pull request. A new service gets access the same way, with steps 1 to 3 from above. In Infisical, you invite a person and give them the project. A service is a [machine identity](https://infisical.com/docs/documentation/platform/identities/universal-auth) with a role, and the role can be narrower than a whole file. You can create custom roles that allow reading secrets only in prod.  Running the app as that identity against prod works. Against dev, it injects zero secrets, and the app just prints `<not set>`. Asking the API for a dev secret by name returns a 403 with the applicable rule. The CLI treats a forbidden environment as empty instead of failing, so when a new identity gets no secrets, check its role first. ### Taking access away Alice is leaving. Her key comes out of both rules, and `updatekeys` runs on both files (as bob, who can read both):
```sh SOPS_AGE_KEY_FILE=~/sops-demo-keys/bob.txt sops updatekeys -y secrets/dev/app.yaml SOPS_AGE_KEY_FILE=~/sops-demo-keys/bob.txt sops updatekeys -y secrets/prod/app.yaml ```
After the commit, bob and the deploy job decrypt the prod file as before, and alice's key is refused with `no identity matched any of the recipients`. Now take the previous commit's version of the file out of Git history and decrypt it with her key:
```sh git show HEAD~1:secrets/prod/app.yaml | SOPS_AGE_KEY_FILE=~/sops-demo-keys/alice.txt sops decrypt --input-type yaml --output-type yaml /dev/stdin ```
`updatekeys` changed who can unwrap the data key from this commit onward. It didn't change the data key or the values, and alice's clone has the whole history.  So removing a recipient stops alice reading anything written from now on, and everything she could read before has to be rotated in each file that listed her. That's the rotation from the last subsection, once per secret and once per repo. In Infisical, removing the user is one action on the Users page. Before and after, `git status` is clean, the values are unchanged, and `infisical secrets-manager run` prints the same output, because nothing was ever encrypted for that person. The org audit log has the whole sequence: invite, project access, removal, with times.
```json { "id": "01a1a7ff-ecd4-7eb8-993f-46a35ebba12e", "ipAddress": "64.37.40.132", "userAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36", "userAgentType": "web", "expiresAt": "2027-02-02T19:18:49.812Z", "createdAt": "2026-11-04T19:18:49.812Z", "updatedAt": "2026-11-04T19:18:49.812Z", "orgId": "761da7de-99b0-447a-9150-f6f00d3da9e6", "projectId": null, "projectName": null, "event": { "type": "delete-user-org-membership", "class": "management", "metadata": { "membershipId": "7d7dab47-e594-42c5-8c4d-137fdc63c2d1", "userId": "8a54fc7b-f633-4cd6-a96c-ec969d8b63b5" } }, "actor": { "type": "user", "metadata": { "authMethod": "google", "email": "[email protected]", "username": "[email protected]", "userId": "4933e76c-674d-4bbd-af08-e0f14c089f00" } } } ```
They still know whatever they read while they had access, same as alice. The project audit log shows which environments and folders they read and when, which is your rotation list, and each rotation is the one-line `secrets set` above. ### Finding out who read what With an age key, there's no answer. Decryption happens on someone's machine with a file, and SOPS writes nothing anywhere. With a KMS key as the recipient, CloudTrail logs each Decrypt call, telling you which IAM identity unwrapped a file's data key and when. It doesn't say which value was read or what happened to it after. In Infisical, every read goes through the server, so the server logs it. The entries for our machine identity:
``` 2026-11-04T19:09:05.503Z get-secrets sops-demo-prod-reader {"environment": "prod", "numberOfSecrets": 3, "secretPath": "/"} 2026-11-04T19:09:05.962Z get-secrets sops-demo-prod-reader {"environment": "dev", "numberOfSecrets": 0, "secretPath": "/"} 2026-11-04T19:09:49.308Z update-secret [email protected] {"environment": "prod", "secretKey": "DATABASE_URL", "secretPath": "/", "secretVersion": 2} ```
Here, we see: * The identity read prod and got three secrets back. * Half a second later it tried dev and got zero, because its role only allows prod. * Forty seconds later, a user changed DATABASE\_URL in prod, creating version 2 of that secret. Reads are logged per environment and folder with a count, not by secret name. Writes name the secret and its version. Reading one secret by name through the API, or revealing it in the UI, logs `get-secret` or `reveal-secret` with the key. Denied requests are a separate event class that's off by default, so the earlier 403 isn't in this list. ## When SOPS is the right choice SOPS is a good fit when: * The team is small, under ten or so engineers, with a handful of repos. * You already run GitOps with Flux or Argo CD and want secrets to go through pull requests like everything else. * You don't want to run or pay for a server, and you already have a cloud KMS that can hold the master key. * Secrets change rarely, and the people who can read them change rarely too. * You have the resources to route every secret through a human. All five of those mean the list of keys is short and stable. When it stops being that, the tasks above are where you feel it, and the move is mechanical: 1. Create an Infisical project with one environment per directory under secrets/, and link the repo with `infisical init`. 2. Decrypt each file and load it with `infisical secrets-manager secrets set --env=prod --file prod.yaml`, then delete the plaintext file. 3. Switch consumers one environment at a time: `infisical secrets-manager run` on laptops and in CI, the operator in Kubernetes, the [agent](https://infisical.com/docs/integrations/platforms/infisical-agent) on VMs. 4. Rotate each secret once nothing reads the SOPS files, since the old values are in every clone's history, then remove the encrypted files and `.sops.yaml`. If you're on SOPS today, you already have what the move needs. The files tell you which secrets exist and which environment each one belongs to, and the steps above take them the rest of the way. You can try it with your own files on [Infisical Cloud](https://infisical.com/)'s free tier, or [self-host Infisical](https://infisical.com/docs/self-hosting/overview) if you'd rather everything stayed inside your network. Next time someone leaves for Anthropic, remove the one, and let the server handle saying goodbye to their keys.
/blog/mozilla-sops.md · raw source