Skip to content

Instantly share code, notes, and snippets.

@alexeyp0708
Last active March 21, 2024 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexeyp0708/d244d0c6714d937bbcac55769c2bd392 to your computer and use it in GitHub Desktop.
Save alexeyp0708/d244d0c6714d937bbcac55769c2bd392 to your computer and use it in GitHub Desktop.
Creates a configuration file from a template where environment variables are replaced with values. See command `createFromTpl.sh -h`
#!/bin/sh
# Some of the code was borrowed from the NGINX docker image
# https://github.com/nginxinc/docker-nginx/blob/master/mainline/debian/20-envsubst-on-templates.sh
set -e
ME=$(basename "$0")
entrypoint_log() {
echo "$@"
}
auto_envsubst() {
local template_dir="$(pwd)/env_tpls"
local suffix=".tpl"
local output_dir="$(pwd)"
local filter=""
while getopts "f:o:t:h" options; do
case "${options}" in
h)
echo "Replaces variables (all or by filter \"${filter}\") in \"${template_dir}/*${suffix}\" files and saves them into files of the same name in the output directory (${output_dir})."
echo "[-f \"\\\${env_var} \\\${env_var2}\"] - Set variables filter"
echo "[-o \"${output_dir}\"]- Set output directory for parsed files"
echo "[-t \"${template_dir}\"] - Set templates directory"
echo "----"
echo "Template file sufix (extension) - ${suffix}"
echo "Templates directory - ${template_dir}"
echo "Output directory - ${output_dir}"
echo "Designation of variables in template file - \${variable}"
return 0
;;
f)
filter="${OPTARG}"
;;
t)
template_dir="${OPTARG}"
;;
o)
output_dir="${OPTARG}"
;;
esac
done
local template defined_envs relative_path output_path subdir
defined_envs=$(printf '${%s} ' $(awk "END { for (name in ENVIRON) { print ( name ~ /${filter}/ ) ? name : \"\" } }" < /dev/null ))
[ -d "$template_dir" ] || return 0
if [ ! -w "$output_dir" ]; then
entrypoint_log "$ME: ERROR: $template_dir exists, but $output_dir is not writable"
return 0
fi
find "$template_dir" -follow -type f -name "*$suffix" -print | while read -r template; do
relative_path="${template#"$template_dir/"}"
output_path="$output_dir/${relative_path%"$suffix"}"
subdir=$(dirname "$relative_path")
# create a subdirectory where the template file exists
mkdir -p "$output_dir/$subdir"
entrypoint_log "$ME: Running envsubst on $template to $output_path"
envsubst "$defined_envs" < "$template" > "$output_path"
done
}
auto_envsubst "$@"
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment