Simplistic templating with envsubst

Have you ever wanted to write out a large, templated config file using only shell script code? Maybe you are working with a small IoT device with limited power or some other device and you want to avoid additional dependencies for single task. In these situations using a larger config management system tool can be too heavy or just not practical. In this post I’ll explore the envsubst utility as a way to write out a config file from a template. In the end you’ll see that envsubst is a great and lightweight utility that can be used to create config files.

envsubst is a utility provided by the gettext package. You will most likely have this package installed already but if you don’t check out https://command-not-found.com/envsubst for information on how to install it and basic info on how to use it. Once installed you can get started.

Using envsubst is as easy as creating a file with shell format strings and then running envsubst against it. The input file doesn’t need to be a shell script at all, it just needs to contain shell format strings. For example, let’s say you want to generate an nginx config for a site and the only thing you need to set is the hostname. Your overly simple nginx config might look this:

server {
  listen 80;
  server_name ${SERVER_NAME};

  root /var/www/html;
}

Given this config file template you can use envsubst to generate a full config like this:

SERVER_NAME=dustinrue.com envsubst < config.template > config.conf

And in return you’ll get this:

server {
  listen 80;
  server_name dustinrue.com;

  root /var/www/html;
}

There are a few things to keep in mind when using envsubst. The biggest being that envsubst is essentially doing a search and replace on the file. It is not evaluating the variables so you cannot use any expressions in there to set default values or modify them. It is a strict 1:1 match. The other is that this is not a full templating system you are stuck only replacing tokens in a file, there are no loops or logic systems of any kind. If what you are doing fits within those limitations then you may find envsubst saves you from installing more dependencies.