Credentials or any other sensitive data should never be stored in configuration files (e.g. Terraform, Dockerfile, Kubernetes YAML files, etc.) and of course should never be committed to Git repositories.
Much better practice is to set some placeholders inside such files, and when needed, replace them with values from your environment variables, that can be done, for example, using a envsubst command.
In this post you will find how to install the envsubst command and examples of how to use it to replace environment variables in the files.
Cool Tip: How to set environment variables in Docker Compose! Read more →
EnvSubst Examples
Install EnvSubst
The envsubst command is a part of the gettext package.
If you get the message “envsubst: command not found” after executing the envsubst command, run one of the commands below, depending on your operating system, to install the gettext package:
# Ubuntu, Debian, Raspberry Pi OS, Kali Linux $ apt install gettext-base # macOS $ brew install gettext # Alpine Linux $ apk add gettext # Arch Linux $ pacman -S gettext # CentOS, RHEL $ yum install gettext # Fedora $ dnf install gettext
Replace Environment Variables using EnvSubst
Let’s say you have a file app-cm.yaml where you have replaced plain-text credentials with ${USERNAME} and ${PASSWORD} placeholder variables:
# app-cm.yaml # --- kind: ConfigMap apiVersion: v1 metadata: name: app-cm data: username: ${USERNAME} password: ${PASSWORD}
To replace these variables with your values, firstly you have to export them to your environment, for example, by executing the commands as follows:
$ export USERNAME="admin" $ export PASSWORD="secret"
Alternatively, you can create some file and store variable=value pairs there, for example:
# .env # --- USERNAME="admin" PASSWORD="secret"
If you are working inside a Git repository, it would be a good idea to add this file to .gitignore to avoid any confidential data from being committed:
# .gitignore # --- .env
The variables from the .env file can be exported to your environment as follows:
$ . .env
To replace the variables in the file app-cm.yaml with the values that have been exported to your environment, execute:
$ envsubst < app-cm.yaml
- sample output -
kind: ConfigMap
apiVersion: v1
metadata:
name: app-cm
data:
username: admin
password: secret
The command above won’t actually change the file app-cm.yaml but will just print its content populated with the values from your environment to the screen.
You can save this output to another file, for example:
$ envsubst < app-cm.yaml > app-cm-output.yaml
As the app-cm.yaml file in the example above is a Kubernetes manifest file, it can be directly applied to a Kubernetes cluster using a kubectl command, as follows:
$ envsubst < app-cm.yaml | kubectl apply -f -