Environment Configuration for Deployment Scripts
A deployment script usually deploys the same application to several environments: a developer's machine, a staging server where changes are tested, and production. The steps are the same everywhere; what differs is the configuration: database host, number of worker processes, log level, public URL, passwords. Keeping these values out of the script, and supplying them per environment, means one script can deploy everywhere, and changing a setting does not require changing code.
This lesson explains where configuration comes from in Bash scripts, why loading it with source is risky, how to read configuration files safely, how to check that every required setting is present and valid before anything is changed, how to handle secrets, and how to generate an application's configuration file from a template. The complete example combines all of this into a small configuration library and a deployment script.
Where Configuration Comes From
Deployment scripts typically combine three sources, in increasing order of priority:
- Defaults written in the script or in a shared file, for settings that are the same everywhere.
- Environment files, one per environment, such as
config/staging.envandconfig/production.env, kept in version control so that changes are reviewed and recorded. - Variables already in the environment when the script starts, set by the person running it or by a CI system. They allow a single run to deviate from the file without editing it, for example
LOG_LEVEL=debug ./deploy.sh -e staging.
The idea that configuration should live in the environment, separate from the code, is one of the principles of the widely cited "twelve-factor app" methodology. For a Bash script, environment variables are the natural interface: every program it starts inherits them (lesson 36).
Defaults and Required Settings with Parameter Expansion
Bash's parameter expansion (lesson 45) handles the simplest cases in one line each. ${NAME:=default} assigns a default when the variable is unset or empty, and ${NAME:?message} stops the script with an error when it is unset or empty. The : command does nothing itself, and only serves to trigger the expansions:
#!/usr/bin/env bash
: "${APP_PORT:=8080}"
: "${DB_HOST:?is not set}"
echo "port=$APP_PORT db=$DB_HOST"
bash req.sh; echo "[status $?]"
DB_HOST=db1 bash req.sh; echo "[status $?]"
APP_PORT=9000 DB_HOST=db1 bash req.sh
req.sh: line 3: DB_HOST: is not set
[status 1]
port=8080 db=db1
[status 0]
port=9000 db=db1
This is enough for small scripts. Its limitation is that the script stops at the first missing variable: someone who forgot three settings learns about them one per attempt. The library in the complete example checks all required settings and reports every missing one at once.
Loading Environment Files
The problem with source
Environment files look like shell assignments:
APP_ENV=staging
LOG_LEVEL=debug
The obvious way to load such a file is source config/staging.env. Two things go wrong with that.
First, source assigns shell variables, which are not passed to child processes unless they are exported. set -a (the allexport option) makes every assignment export the variable automatically:
printf 'APP_ENV=staging\nLOG_LEVEL=debug\n' > plain.env
source plain.env; bash -c 'echo "child sees APP_ENV=[${APP_ENV:-}]"'
set -a; source plain.env; set +a; bash -c 'echo "child sees APP_ENV=[${APP_ENV:-}]"'
child sees APP_ENV=[]
child sees APP_ENV=[staging]
Second, and more serious, source executes the file as Bash code. Every line goes through the full shell syntax: $ starts an expansion, spaces split words, and $(...) runs commands. A password containing a dollar sign is silently changed:
printf 'DB_PASSWORD=Pr0d$ecret!\n' > pw.env
(source pw.env; echo "sourced: [$DB_PASSWORD]")
sourced: [Pr0d!]
$ecret was expanded as a variable, which was empty. And a value containing a command substitution runs that command:
GREETING=hello $(touch /tmp/PWNED) world
(source evil.env; echo "GREETING=[$GREETING]"); ls /tmp/PWNED
evil.env: line 1: world: command not found
GREETING=[]
/tmp/PWNED
Bash read the line as the temporary assignment GREETING=hello for a command consisting of the substitution and the word world. The substitution ran touch, and world was then executed as a command. With source, anyone who can write to a configuration file can run commands as the user who deploys, often a user with considerable privileges. source is appropriate only for files that are trusted code; for configuration data, a parser is safer.
A safe parser
Reading the file line by line and assigning each value as plain text avoids both problems: nothing in the value is interpreted.
# load_env_file FILE: read KEY=VALUE lines and export them, without executing anything
load_env_file() {
local file=$1 line key value n=0
[[ -r $file ]] || { config_error "cannot read $file"; return 1; }
while IFS= read -r line || [[ -n $line ]]; do
n=$(( n + 1 ))
line=${line%$'\r'} # tolerate Windows line endings
[[ $line =~ ^[[:space:]]*(#|$) ]] && continue # comment or empty line
if [[ ! $line =~ ^[[:space:]]*(export[[:space:]]+)?([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]]; then
config_error "$file:$n: expected NAME=VALUE"
return 1
fi
key=${BASH_REMATCH[2]} value=${BASH_REMATCH[3]}
if [[ $value =~ ^\"(.*)\"$ || $value =~ ^\'(.*)\'$ ]]; then
value=${BASH_REMATCH[1]} # remove one pair of quotes
fi
if [[ -n ${CONFIG_PRESET[$key]:-} ]]; then
CONFIG_SOURCE[$key]=environment
continue # the environment wins
fi
export "$key=$value"
CONFIG_SOURCE[$key]=${file##*/}:$n
done < "$file"
}
How the parser works:
while IFS= read -r line || [[ -n $line ]]reads lines exactly as written (lesson 114). The||part also processes a last line that lacks a final newline, which editors sometimes produce.- Comments and empty lines are skipped, and a trailing carriage return is removed, because files edited on Windows end each line with
\r\n. - The regular expression accepts an optional
exportprefix (common in files that are also used by other tools), a valid variable name,=, and the rest of the line as the value. Anything else is rejected with the file name and line number, instead of being silently ignored. - One pair of surrounding quotes is removed, so
PUBLIC_URL="https://shop.example.com"works as people expect, but nothing inside the value is interpreted. export "$key=$value"assigns the value as text. Because the whole assignment is a single quoted word, the value can contain spaces,$, quotes or anything else. The variable name has already been validated, so it cannot inject anything either.
With the parser, the two problem files are read literally, and a malformed line is reported:
load_env_file pw.env; echo "parsed: [$DB_PASSWORD]"
load_env_file evil.env; echo "GREETING=[$GREETING]"
printf 'APP_PORT 8080\n' > bad.env; load_env_file bad.env; echo "[status $?]"
parsed: [Pr0d$ecret!]
GREETING=[hello $(touch /tmp/PWNED) world]
config: bad.env:1: expected NAME=VALUE
[status 1]
Keeping the environment's priority
Values set in the environment before the script started should override the files. The parser cannot simply skip variables that are already set, because then the first file loaded would win over later, more specific ones. Instead, the library records the names of the environment variables once, when it is loaded, before any file has been read:
declare -A CONFIG_PRESET=() # NAMEs that were set in the environment at startup
for _name in $(compgen -e); do CONFIG_PRESET[$_name]=1; done
compgen -e lists the names of all exported variables. The parser skips only those names, so files loaded later still override files loaded earlier. It also records where each value came from in CONFIG_SOURCE, which makes the configuration traceable when it is displayed.
Validating Before Changing Anything
A deployment that discovers a missing database password after it has already stopped the old version leaves the system broken. All configuration checks therefore belong at the beginning, before the first change, and they should report every problem in one run:
# require NAME...: fail, listing every missing name, if any of them is unset or empty
require() {
local name missing=()
for name; do [[ -n ${!name:-} ]] || missing+=("$name"); done
(( ${#missing[@]} == 0 )) || { config_error "missing required settings: ${missing[*]}"; return 1; }
}
# check_int NAME MIN MAX / check_one_of NAME VALUE...: validate a setting's value
check_int() {
local v=${!1}
[[ $v =~ ^[0-9]+$ ]] && (( 10#$v >= $2 && 10#$v <= $3 )) ||
{ config_error "$1=$v: expected a number from $2 to $3"; return 1; }
}
check_one_of() {
local name=$1 v=${!1} ok
shift
for ok; do [[ $v == "$ok" ]] && return 0; done
config_error "$name=$v: expected one of: $*"
return 1
}
The functions receive variable names, not values, and read the values with indirect expansion: ${!name} expands to the value of the variable whose name is stored in name (lesson 152). This lets error messages name the setting. In check_int, the regular expression ensures the value consists only of digits before it is used in arithmetic: Bash arithmetic evaluates variable names and expressions inside the value, so unchecked input must never reach (( )) (lesson 155). 10# forces base 10, so that a value such as 08 is not read as an invalid octal number.
Secrets
Passwords, API tokens and private keys need more care than other settings:
- They do not belong in version control. Environment files in the repository contain everything except secrets.
- They should not be in the process environment longer than necessary, because environment variables are visible to every child process, may end up in crash reports and debug output, and can be read through
/proc/PID/environby the same user. - They must not appear in logs, including output from
set -x(lesson 158).
A widespread convention, used by the official Docker images for databases among others, is to give the path of a file containing the secret in a variable whose name ends in _FILE: instead of DB_PASSWORD=..., the configuration contains DB_PASSWORD_FILE=/etc/shop/secrets/staging_db_password. The file is created on the deployment machine by an administrator or a secrets manager, with permissions that only allow its owner to read it. The library reads such files for an explicit list of names:
# load_secrets NAME...: for each NAME whose NAME_FILE variable is set, read the
# first line of that file into NAME (the *_FILE convention used by Docker secrets)
load_secrets() {
local name var file
for name; do
var=${name}_FILE
[[ -n ${!var:-} ]] || continue
file=${!var}
[[ -r $file ]] || { config_error "$var: cannot read $file"; return 1; }
if [[ $(stat -c %a "$file") != [46]00 ]]; then
config_error "$var: $file is readable by other users (run: chmod 600 $file)"
return 1
fi
IFS= read -r "$name" < "$file" || [[ -n ${!name} ]] ||
{ config_error "$var: $file is empty"; return 1; }
export "$name"
CONFIG_SOURCE[$name]="file $file"
done
}
The list is explicit for a reason. A first version of this function processed every variable ending in _FILE, and failed immediately on the test machine, because an unrelated variable with such a name already existed in the environment. Configuration code should only interpret the names it is responsible for. The permission check, stat -c %a with the pattern [46]00, accepts modes 600 and 400 and rejects secret files that other users can read, a mistake that is easy to make and hard to notice.
Generating Configuration Files from Templates
Many applications read their settings from a configuration file rather than from the environment. A deployment script can generate that file from a template containing placeholders such as ${DB_HOST}. The envsubst tool from GNU gettext does this, but it is not installed everywhere, and it replaces placeholders of unset variables with empty text, which produces a broken file without any error. A pure Bash version can refuse instead:
# render_template FILE: print FILE with every ${NAME} replaced by its value;
# fails if a placeholder names an unset variable
render_template() {
local text rest name out='' status=0
text=$(< "$1") || return 1
rest=$text
while [[ $rest =~ \$\{([A-Za-z_][A-Za-z0-9_]*)\} ]]; do
name=${BASH_REMATCH[1]}
out+=${rest%%"${BASH_REMATCH[0]}"*}
if [[ -v $name ]]; then out+=${!name}
else config_error "$1: \${$name} is not set"; status=1; fi
rest=${rest#*"${BASH_REMATCH[0]}"}
done
(( status == 0 )) && printf '%s\n' "$out$rest"
return "$status"
}
The loop finds the first placeholder in the remaining text, appends everything before it to the output (${rest%%"$match"*} removes the longest suffix starting at the placeholder), appends the variable's value, and continues after the placeholder. The quotes around ${BASH_REMATCH[0]} inside the expansions make Bash treat the placeholder as literal text rather than a pattern. Only ${NAME} with braces is a placeholder, so a dollar sign in ordinary text, such as $5, is left alone:
printf 'Hello ${DB_USER} on ${DB_HOST}, cost $5 ${MISSING}\n' > t.tmpl
render_template t.tmpl; echo "[status $?]"
MISSING=x; render_template t.tmpl
config: t.tmpl: ${MISSING} is not set
[status 1]
Hello u on db1, cost $5 x
Values are inserted as text, so a value containing ${...} is not expanded a second time.
A Complete Example: Configuration for a Deployment Script
The example deploys the configuration of a web shop to staging or production. Its files:
deploy.sh the deployment script
lib/config.sh the functions shown above
config/common.env settings shared by all environments
config/staging.env staging settings
config/production.env production settings
templates/app.conf.tmpl template for the application's configuration file
lib/config.sh consists of the declarations and functions from this lesson, plus two small ones:
config_error() { echo "config: $*" >&2; }
# show_config NAME...: print settings and their sources, hiding secret values
show_config() {
local name value
for name; do
value=${!name-<unset>}
case $name in
*PASSWORD*|*SECRET*|*TOKEN*|*_KEY) [[ -n ${!name:-} ]] && value='******' ;;
esac
printf ' %-14s %-28s (%s)\n' "$name" "$value" "${CONFIG_SOURCE[$name]:-default}"
done
}
The configuration files and the template:
# config/common.env - settings shared by every environment
APP_NAME=shop
APP_PORT=8080
LOG_LEVEL=info
WORKERS=4
# config/staging.env - one small server, verbose logs
APP_ENV=staging
DB_HOST=db.staging.internal
DB_NAME=shop_staging
DB_USER=shop
DB_PASSWORD_FILE=/etc/shop/secrets/staging_db_password
LOG_LEVEL=debug
WORKERS=2
# config/production.env
APP_ENV=production
DB_HOST=db1.prod.internal
DB_NAME=shop
DB_USER=shop
DB_PASSWORD_FILE=/etc/shop/secrets/production_db_password
PUBLIC_URL="https://shop.example.com"
WORKERS=8
# Generated by deploy.sh for ${APP_ENV} - do not edit on the server
[server]
port = ${APP_PORT}
workers = ${WORKERS}
log_level = ${LOG_LEVEL}
[database]
url = postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}/${DB_NAME}
The deployment script loads and checks the configuration, asks for confirmation before production, and writes the application's configuration file. A real deployment would then continue with the steps of lesson 180; this script stops after the configuration so that the configuration handling can be seen on its own.
#!/usr/bin/env bash
#
# deploy.sh - prepare the configuration for a deployment of the shop application
#
# Usage: deploy.sh -e ENVIRONMENT [-o FILE] [-n]
# -e ENVIRONMENT staging or production
# -o FILE where to write the generated configuration (default: ./app.conf)
# -n dry run: show the settings and the generated file, write nothing
#
# Settings come from config/common.env, then config/ENVIRONMENT.env; variables
# already set in the environment override both. Secrets are read from the
# files named by *_FILE variables, such as DB_PASSWORD_FILE.
set -euo pipefail
here=$(dirname "$(readlink -f "$0")")
source "$here/lib/config.sh"
usage() { echo "usage: ${0##*/} -e ENVIRONMENT [-o FILE] [-n]" >&2; exit 2; }
env_name='' output=app.conf dry_run=0
while getopts ':e:o:n' opt; do
case $opt in
e) env_name=$OPTARG ;;
o) output=$OPTARG ;;
n) dry_run=1 ;;
*) usage ;;
esac
done
[[ -n $env_name ]] || usage
[[ $env_name =~ ^[a-z]+$ && -f $here/config/$env_name.env ]] ||
{ echo "${0##*/}: unknown environment '$env_name' (have: $(cd "$here/config" && ls *.env | grep -v '^common' | sed 's/\.env$//' | paste -sd ' '))" >&2; exit 2; }
# 1. load and check the configuration; report every problem, then stop
load_env_file "$here/config/common.env"
load_env_file "$here/config/$env_name.env"
load_secrets DB_PASSWORD
problems=0
require APP_NAME APP_ENV APP_PORT DB_HOST DB_NAME DB_USER DB_PASSWORD || problems=1
check_int APP_PORT 1 65535 || problems=1
check_int WORKERS 1 64 || problems=1
check_one_of LOG_LEVEL debug info warning error || problems=1
[[ $APP_ENV == "$env_name" ]] || { config_error "APP_ENV=$APP_ENV does not match -e $env_name"; problems=1; }
(( problems == 0 )) || exit 1
echo "configuration for $env_name:"
show_config APP_NAME APP_ENV APP_PORT WORKERS LOG_LEVEL DB_HOST DB_NAME DB_USER DB_PASSWORD PUBLIC_URL
# 2. production needs an explicit confirmation, which CI gives with CONFIRM_PRODUCTION=yes
if [[ $env_name == production && $dry_run == 0 && ${CONFIRM_PRODUCTION:-} != yes ]]; then
if [[ -t 0 ]]; then
read -r -p "Deploy to PRODUCTION? Type 'production' to continue: " answer
[[ $answer == production ]] || { echo "aborted"; exit 1; }
else
echo "${0##*/}: refusing to deploy to production without CONFIRM_PRODUCTION=yes" >&2
exit 1
fi
fi
# 3. render the configuration file
if (( dry_run )); then
echo "--- $output (dry run, not written)"
render_template "$here/templates/app.conf.tmpl" | sed 's/:[^:@/]*@/:******@/'
exit
fi
tmp=$(mktemp "$output.XXXXXX")
trap 'rm -f "$tmp"' EXIT
render_template "$here/templates/app.conf.tmpl" > "$tmp"
chmod 600 "$tmp"
mv "$tmp" "$output"
echo "wrote $output"
How It Works
- The environment name is validated against the files that exist: it must consist of lowercase letters and have a matching
.envfile. The check also prevents a value such as../../etc/passwdfrom being used to build a path. The error message lists the environments that do exist. - Loading order defines precedence.
common.envis loaded first andENVIRONMENT.envsecond, so environment-specific values override common ones; values from the caller's environment override both. - All checks run before anything is written. Each check sets
problems=1instead of exiting, so one run reports every problem.APP_ENVmust match the requested environment, which catches a production file accidentally copied into the staging file, or the reverse. - The effective configuration is displayed with its sources, so it is clear whether a value came from a file (with its line number), from the environment, or from a secret file. Values whose names suggest secrets are masked.
- Production requires confirmation. Interactively, the person must type the word
production, which is harder to do by reflex than answeringy. Without a terminal, as in CI, the script requiresCONFIRM_PRODUCTION=yes; a CI pipeline sets it only in the job that deploys to production. - The generated file is written atomically. It is rendered into a temporary file in the same directory, made readable only by its owner because it contains the password, and moved into place with
mv, which replaces the old file in one step (lesson 113). The application never sees a half-written file, and a failed rendering leaves the previous file untouched; theEXITtrap removes the temporary file in that case. - The dry run masks the password in the rendered file with
sed, replacing the text between:and@in the database URL.
Running the Complete Example
A dry run for staging shows every setting with its source and the file that would be generated:
$ deploy.sh -e staging -n
configuration for staging:
APP_NAME shop (common.env:2)
APP_ENV staging (staging.env:2)
APP_PORT 8080 (common.env:3)
WORKERS 2 (staging.env:8)
LOG_LEVEL debug (staging.env:7)
DB_HOST db.staging.internal (staging.env:3)
DB_NAME shop_staging (staging.env:4)
DB_USER shop (staging.env:5)
DB_PASSWORD ****** (file /etc/shop/secrets/staging_db_password)
PUBLIC_URL <unset> (default)
--- app.conf (dry run, not written)
# Generated by deploy.sh for staging - do not edit on the server
[server]
port = 8080
workers = 2
log_level = debug
[database]
url = postgresql://shop:******@db.staging.internal/shop_staging
[status 0]
WORKERS and LOG_LEVEL are defined in both files; the staging values won. Variables set on the command line override the files, and the source column shows it. This time the file was written, with permissions -rw-------:
$ LOG_LEVEL=warning WORKERS=3 deploy.sh -e staging -o app.conf
configuration for staging:
...
WORKERS 3 (environment)
LOG_LEVEL warning (environment)
...
wrote app.conf
[status 0]
$ cat app.conf
# Generated by deploy.sh for staging - do not edit on the server
[server]
port = 8080
workers = 3
log_level = warning
[database]
url = postgresql://shop:st4ging-pass@db.staging.internal/shop_staging
The production password file had been created with the default permissions 644. The script refused to use it until it was fixed:
$ deploy.sh -e production -n
config: DB_PASSWORD_FILE: /etc/shop/secrets/production_db_password is readable by other users (run: chmod 600 /etc/shop/secrets/production_db_password)
[status 1]
$ chmod 600 /etc/shop/secrets/production_db_password
$ deploy.sh -e production -n
configuration for production:
APP_NAME shop (common.env:2)
APP_ENV production (production.env:2)
APP_PORT 8080 (common.env:3)
WORKERS 8 (production.env:8)
LOG_LEVEL info (common.env:4)
DB_HOST db1.prod.internal (production.env:3)
DB_NAME shop (production.env:4)
DB_USER shop (production.env:5)
DB_PASSWORD ****** (file /etc/shop/secrets/production_db_password)
PUBLIC_URL https://shop.example.com (production.env:7)
--- app.conf (dry run, not written)
# Generated by deploy.sh for production - do not edit on the server
[server]
port = 8080
workers = 8
log_level = info
[database]
url = postgresql://shop:******@db1.prod.internal/shop
[status 0]
PUBLIC_URL lost its quotes, and LOG_LEVEL came from common.env because the production file does not override it. A real production run without a terminal and without confirmation is refused; with CONFIRM_PRODUCTION=yes it proceeds, and the password, which contains $ and !, arrives in the generated file exactly as written in the secret file:
$ deploy.sh -e production < /dev/null
configuration for production:
...
deploy.sh: refusing to deploy to production without CONFIRM_PRODUCTION=yes
[status 1]
$ CONFIRM_PRODUCTION=yes deploy.sh -e production -o prod.conf
...
wrote prod.conf
[status 0]
$ grep url prod.conf
url = postgresql://shop:Pr0d$ecret!@db1.prod.internal/shop
Finally, configuration mistakes. An unknown environment is rejected with the list of known ones; invalid values are all reported together; and so are missing ones. A variable set to an empty value in the environment still counts as set by the caller and overrides the file, so require reports it as missing:
$ deploy.sh -e qa
deploy.sh: unknown environment 'qa' (have: production staging)
[status 2]
$ APP_PORT=80800 WORKERS=two LOG_LEVEL=verbose deploy.sh -e staging -n
config: APP_PORT=80800: expected a number from 1 to 65535
config: WORKERS=two: expected a number from 1 to 64
config: LOG_LEVEL=verbose: expected one of: debug info warning error
[status 1]
$ APP_ENV= DB_HOST= deploy.sh -e staging -n
config: missing required settings: APP_ENV DB_HOST
config: APP_ENV= does not match -e staging
[status 1]
In none of these failing cases was anything written: every check ran before the first change.