Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mauvm
Created July 26, 2015 11:57
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mauvm/5de07085f3b51e117378 to your computer and use it in GitHub Desktop.
Save mauvm/5de07085f3b51e117378 to your computer and use it in GitHub Desktop.
An "envsubst" alternative for replacing env variables in NGinX site configurations (for using it with Docker)
#!/bin/bash
# NOTE: Brackets are not supported and '$' in values will break the script.
mkdir /etc/nginx/sites-enabled 2> /dev/null
for file in /etc/nginx/sites-available/*.conf
do
TPL=$(cat $file)
for row in $(env)
do
IFS="="
read key val <<< "$row"
if [[ $val == tcp://* ]]
then
valhttp=$(echo -n $val | sed 's#^tcp://#http://#')
TPL=$(echo -n $TPL | sed "s\$\\\$$key\_HTTP\$$valhttp\$")
fi
TPL=$(echo -n $TPL | sed "s\$\\\$$key\$$val\$")
done
echo -n $TPL > "/etc/nginx/sites-enabled/$(basename $file)"
done
nginx -g "daemon off;"
@rodlogic
Copy link

What about the following:

process_template() {
  eval "echo \"$(cat $1)\""
}

echo "=> Processing template files (.tmpl)"
TEMPLATE_FILES=$(find . -name "*.tmpl" -print)
for FILE in $TEMPLATE_FILES; do
  echo "  |- $FILE -> ${FILE%.*}"
  process_template $FILE
  [ -z $KEEP ] && rm $FILE
done

@timbrandin
Copy link

timbrandin commented Nov 5, 2017

I improved the script a bit, now it does not replace "=" in for example proxy_cache_path
and it works with the docker image nginx:alpine (if one add bash).

#!/bin/bash

# NOTE: Brackets are not supported and '$' in values will break the script.

function replace_env {
  mkdir /etc/nginx/conf.d 2> /dev/null
  for file in /etc/nginx/conf.d/*.conf
  do
    TPL=$(cat $file)
    for row in $(env)
    do
      SAVEIFS=$IFS
      IFS="="
      read key val <<< "$row"
      IFS=$SAVEIFS
      if [[ $val == tcp://* ]]
      then
        valhttp=$(echo -n $val | sed 's#^tcp://#http://#')
        TPL=$(echo -n $TPL | sed "s\$\\\$$key\_HTTP\$$valhttp\$")
      else
        TPL=$(echo -n $TPL | sed "s\$\\\$$key\$$val\$")
      fi
    done
    echo -n $TPL > "/etc/nginx/conf.d/$(basename $file)"
  done
}

replace_env
nginx -g "daemon off;"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment