Secure .envrc files
A common use case is sourcing local environment variables, for example with direnv, and storing them in a .envrc file. To prevent accidentally committing secrets to a repository and pushing them to origin, itβs best to encrypt local secrets. Although direnv does not support this by default, you can integrate it nicely with sops, GnuPG, and a helper function.
Install dependencies
We need direnv and sops to encrypt files, and GnuPG to create encryption keys.
# On macOS this can be installed with Homebrew.
# On any other OS, use your package manager.
$ brew install direnv sops gnupg
Generate encryption keys
To encrypt and decrypt, you need to generate the necessary keys.
$ gpg --full-generate-key
- Choose key type: RSA and RSA (default)
- Key size: 4096
- Expiration: choose one, or "0" for no expiry. (For convenience, best practice is to set a shorter expiration date.)
- Enter your name and email.
- Add a passphrase.
List the keys stored on your machine to get the newly generated key and add it to the sops config.
$ gpg --list-keys
pub rsa4096 2025-10-24 [SC]
ABC123DEF4567890...
uid [ultimate] Laurence Bortfeld <[email protected]>
sub rsa4096 2025-10-24 [E]
Create sops config
For sops to know which key to use, configure the sops config file.
# ~/.sops.yaml
creation_rules:
- pgp: "ABC123DEF4567890..."
Add sops helper
As mentioned, direnv does not support sops natively. To source encrypted files, add a custom helper function.
# ~/.config/direnv/direnvrc
use_sops() {
local path=${1:-$PWD/.envrc.enc}
eval "$(sops -d --output-type env "$path" | direnv dotenv bash /dev/stdin)"
watch_file "$path"
}
Encrypt and source encrypted files
To encrypt the file, run:
$ sops -e .envrc > .envrc.enc
Now replace the current content of your .envrc file with:
use sops .envrc.enc
Run direnv allow to source the encrypted environment variables.
Done! You can no longer accidentally commit readable secrets to version control. π
Miscellaneous
You can edit the encrypted environment files by running:
$ sops .envrc.enc # Opens the file decrypted in your favorite editor.
You may need to set environment variables to ensure everything works smoothly.
export EDITOR=nvim # Set your favorite editor to edit encrypted files
export GPG_TTY=$(tty) # Tell gpg to open the passphrase prompt on your tty
export DIRENV_WARN_TIMEOUT=1m # Prevent warning when entering gpg passphrase