Environment variables and secrets
Keep settings and secrets out of your code: environment variables, a .env file kept out of Git, and what to do when a secret leaks.
Keep settings and secrets out of your code: environment variables, a .env file kept out of Git, and what to do when a secret leaks.
In plain words
A secret is the key to your house. You do not write it on the front door (in the code). You keep it somewhere private and hand it to the program when it starts. A setting is different: it is just a choice, like which folder to use.
Try it yourself
Settings and secrets reach a program through environment variables. Try it in the terminal:
export LOG_PATH=/tmp/requests.log
echo $LOG_PATH
python3 -c 'import os; print(os.environ.get("LOG_PATH", "requests.log"))'
The second argument is the default when the variable is not set. Put values in a .env file instead of typing them, and keep that file out of Git:
cd ~/api
git init -q # skip this if the folder is already a Git repository
printf 'LOG_PATH=/tmp/requests.log\nDB_PASSWORD=not-a-real-password\n' > .env
printf '.env\n' >> .gitignore
set -a; . ./.env; set +a # load it into this terminal
git status --short # .env must NOT be listed
A step further
set -a makes every variable you load exported, so programs started afterwards can read them. If git status lists .env, stop and fix .gitignore before any commit.
If a secret ever reaches Git, deleting it in the next commit is not enough: the history keeps it. Treat it as leaked: replace it with a new one, then clean up.
How it works in real projects
In our systems secrets live in a secret store and are put into the environment when a program starts. They are never in the repository, in a log, on a page or in a chat message. Training databases may use a simple password like app; a real one never does.