0PricingLogin
Linux Command Line & Bash Scripting Mastery · Lesson

Templating Configs with envsubst and heredocs

Generate runtime configuration from environment variables using envsubst and quoted heredocs.

Why Runtime Config Templating Matters

In DevOps and container workflows, configuration files like nginx.conf, prometheus.yml, and docker-compose.yml often need to change between environments — staging, production, DR. Hardcoding values creates drift and secrets exposure.

The solution is runtime config templating: ship a template with placeholders, then inject real values at startup from environment variables. This keeps your image immutable and your config auditable.

  • No secrets baked into images
  • Same artifact promoted across environments
  • Config generated just before the process starts

Two complementary tools make this trivial in Bash: envsubst and quoted heredocs.

envsubst: The One-Liner Config Generator

envsubst is a small GNU utility that reads stdin, substitutes $VARIABLE and ${VARIABLE} placeholders with their values from the current environment, and writes to stdout.

It ships with the gettext package and is available in virtually every Linux distro and Docker base image.

  • Works with any text format: NGINX, YAML, TOML, JSON, INI
  • Does not evaluate shell syntax — only replaces variable references
  • Safe: it will not execute commands inside the template
#!/usr/bin/env bash
# Install check (usually already present)
which envsubst || apt-get install -y gettext-base

# Minimal demo
export APP_PORT=8080
export APP_HOST=api.example.com

echo 'server { listen ${APP_PORT}; server_name ${APP_HOST}; }' | envsubst
# Output: server { listen 8080; server_name api.example.com; }

All lessons in this course

  1. Writing Lean Dockerfiles and Shell Entrypoints
  2. Templating Configs with envsubst and heredocs
  3. Scripting Cloud Resources via CLI and jq
  4. Health Probes, Readiness Gates, and Wait Loops
← Back to Linux Command Line & Bash Scripting Mastery