Skip to content

Instantly share code, notes, and snippets.

@slavone
Last active May 1, 2017 10:14
Show Gist options
  • Save slavone/f24450a1a70db6cb91f35b63792d4a71 to your computer and use it in GitHub Desktop.
Save slavone/f24450a1a70db6cb91f35b63792d4a71 to your computer and use it in GitHub Desktop.
basic static config templater in bash
#!/bin/sh
# Basic shell templater script for static configs in docker
# made to be run before container start inside entrypoint.sh
# reads $1 file, replaces all variables, enclosed into <%= VAR %>
# with values of env variable with that name
# writes the new file into $2
# Fails if any of the matched variables is empty
set -o errexit
IFS=''
PATTERN='<%=[[:space:]]*([a-zA-Z_0-9]+)[[:space:]]*%>'
RESULT=""
while IFS='' read -r line || [[ -n "$line" ]]; do
while [[ "$line" =~ $PATTERN ]] ; do
VAR_NAME=${BASH_REMATCH[1]}
VAR_VAL="`eval echo "$\"$VAR_NAME\""`"
if [[ -z $VAR_VAL ]]; then
echo "Variable $VAR_NAME is not set, quitting..."
exit 1;
fi
TEMPLATE="`eval echo "\<%=[[:space:]]*\"$VAR_NAME\"[[:space:]]*%\>"`"
SED_REGEX="s/$TEMPLATE/$VAR_VAL/"
line="`IFS=''; echo $line | sed $SED_REGEX`"
done
RESULT+="$line\n"
done < "$1"
echo $RESULT > $2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment