TIL: setting env vars from KeePassXC
I don’t like having secrets stored in plain text in files lurking around my computer. I prefer to have them safely stored in a password manager and query it only when needed, even when I’m in the terminal and need some environment variable.
I used to copy secrets from KeePassXC (my favourite
password manager) and paste into the terminal to export an environment
variable. That always terrified me, as my secrets ended up in my Bash history
file. I was periodically rotating secrets as a precaution.
One way to get a secret from KeePassXC is using its CLI:
$ export GH_TOKEN=$(keepassxc-cli show -sa Password ~/secrets/personal.kdbx 'Tokens/GitHub')
This will prompt for the password to unlock the database and then query the
secret and save it in the new GH_TOKEN environment variable. Note that this
command unlocks the database only during its execution.
When I need to retrieve multiple secrets at the same time, having to type my password for each environment variable becomes tedious. I’m too lazy for that.
We can use a Bash script to query the password only once and retrieve all secrets we need:
DB="${HOME}/secrets/personal.kdbx"
IFS= read -rsp "KeePassXC password: " PASSWORD
secret() {
echo "${PASSWORD}" | keepassxc-cli show -qsa Password "${DB}" "$1"
}
export GH_TOKEN=$(secret 'Tokens/GitHub')
export COGNITO_CLIENT_ID=$(secret 'AWS/Cognito client ID')
export COGNITO_CLIENT_SECRET=$(secret 'AWS/Cognito client secret')
unset -v PASSWORD DB
unset -f secret
It is very important to unset the variable holding your password, to not
leave it in the current shell.
If the code above is saved as .env.secrets, loading these variables into your
environment is a matter of:
$ source .env.secrets
Note that this is a Bash script, not a conventional dotenv file. Also, there’s no error handling in there, if you mistype your password or query a non-existent secret, you won’t know. I leave as an exercise to the reader to handle errors here.
It will ask your password once (the second line of the script above reads the
password into the variable PASSWORD) and use it for every keepassxc-cli
invocation.
In case you need to query KeePassXC for a username, use this function:
username() {
echo "${PASSWORD}" | keepassxc-cli show -qsa Username "${DB}" "$1"
}
No more secrets in plaintext files!
