Skip to content

Instantly share code, notes, and snippets.

@johngrimes
Created February 14, 2018 22:21
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save johngrimes/6162b938071f703cb35f7a8d2a336de9 to your computer and use it in GitHub Desktop.
Save johngrimes/6162b938071f703cb35f7a8d2a336de9 to your computer and use it in GitHub Desktop.
Injecting environment variables into config.json using Docker
#!/bin/bash
set -e
# Available configuration variables.
declare -A vars=( \
[optionA]=MYAPP_OPTION_A \
[optionB]=MYAPP_OPTION_B \
[optionC]=MYAPP_OPTION_C
)
# Work out which of the available variables have been set.
declare -A varsSet
for var in "${!vars[@]}"; do
value=${vars[$var]}
if [[ -v $value ]]; then
varsSet[$var]=${!value}
fi
done
keys=(${!varsSet[@]})
lastIndex=$(( ${#varsSet[@]} - 1 ))
# Iterate over the set variables and echo out the corresponding JSON.
echo "{"
for (( i=0 ; i < "${#varsSet[@]}" ; i++ )); do
key=(${keys[$i]})
value=(${varsSet[$key]})
kvPair=" \"$key\": \"$value\""
# If this is the last variable, don't print out a comma at the end of the
# line.
if [[ ! $i -eq $lastIndex ]]; then kvPair+=","; fi
echo "$kvPair"
done
echo "}"
FROM nginx
COPY docker/start.sh /
COPY docker/buildConfig.sh /
RUN chmod +x /start.sh /buildConfig.sh
COPY docker/myapp.nginx.conf /etc/nginx/conf.d/default.conf
COPY build /usr/share/nginx/html
ENV MYAPP_OPTION_A="Default option A value"
ENV MYAPP_OPTION_B="Default option B value"
ENV MYAPP_OPTION_C="Default option C value"
CMD ["/start.sh"]
#!/bin/bash
set -e
# Build a configuration file from environment variables.
/buildConfig.sh >/usr/share/nginx/html/config.json
exec nginx -g 'daemon off;'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment