Skip to content

Instantly share code, notes, and snippets.

@ktonon
Last active July 13, 2016 00:21
Show Gist options
  • Save ktonon/770702ef4e6989a1d41d2a0780530278 to your computer and use it in GitHub Desktop.
Save ktonon/770702ef4e6989a1d41d2a0780530278 to your computer and use it in GitHub Desktop.
Apply environment variables to a plain text file that has been prepared as a configuration template
#!/usr/bin/env bash
# Usage: dockify-config-file.sh PREFIX INFILE OUTFILE
#
# Will lockup environment variables that start with PREFIX_
# and replace all occurences of ${PREFIX_...} in INFILE,
# writing to OUTFILE.
#
# Useful for converting a non-docker friendly configuration file into
# a template which can be populated at runtime.
PREFIX="$1"
INFILE="$2"
TEMPFILE="${INFILE}.tmp"
OUTFILE="$3"
KEY_VALUE_PAIRS=`env | egrep "^${PREFIX}_"`
cp "${INFILE}" "${TEMPFILE}"
for PAIR in $KEY_VALUE_PAIRS
do
KEY_VALUE=(${PAIR//=/ })
KEY=${KEY_VALUE[0]}
VAL=${KEY_VALUE[1]}
REPLACE=s/'${'${KEY}'}'/${VAL}/g
sed -i "''" "${REPLACE}" "${TEMPFILE}"
done
mv "${TEMPFILE}" "${OUTFILE}"
echo Wrote to ${OUTFILE}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment