envsubst: An easy way to inject environmental variables into a file.

Posted by Andrew Denner on September 24, 2021 · 1 min read

Install

(Assumes that you have python3 and pip already)

pip install envsubst

Use

In a text based file, you can add your variables like

My super secret environmental variable is ${MYVAR}. 

Next we set MYVAR and run the file through envsubst.

export MYVAR="Now is the time..."
envsubst < in-template.tpl > out-file.name

This will result in an out file that reads:

My super secret environmental variable is Now is the time.... 

Why?

This is especially helpful for being able to reproduce config files in multiple CI/CD environments or if you want to keep secrets that are passed into your environment, and not in your git repo.