nginx利用envsubst注入环境变量

  • envsubst可以将一个文件中的占位符标志如${xxx}/$xxx用环境变量替换掉。因此可以用来动态注入nginx的配置。在使用docker镜像时通过这个方式可以实现较为方便地修改ng反向代理配置。
  • 但是此时会存在一个问题,nginx约定好的$host/$remote等变量也会被这个命令替换掉,基本上都会造成问题。
  • 但envsubst还有一个参数,就是只替换指定的环境变量,这样就不会替换掉nginx约定好的变量了。
  • 但是环境变量是不确定有哪些的,或者说,如果环境变量较多时,一个个指定也很麻烦

解决方法

拿到当前环境所有已定义的环境变量,使用文本处理,得到所有想要替换的环境变量。此时使用envsubst指定替换功能,就不会替换掉$host/$remote等信息了

nginx官方是这么做的,此文件来自nginx镜像。妙啊

#!/bin/sh

set -e

ME=$(basename $0)

auto_envsubst() {
  local template_dir="${NGINX_ENVSUBST_TEMPLATE_DIR:-/etc/nginx/templates}"
  local suffix="${NGINX_ENVSUBST_TEMPLATE_SUFFIX:-.template}"
  local output_dir="${NGINX_ENVSUBST_OUTPUT_DIR:-/etc/nginx/conf.d}"

  local template defined_envs relative_path output_path subdir
  # 这里拿到了所有定义的环境变量
  # [root@iZwz9hmxhr8nh716gmser4Z tmp]# printf '${%s} ' $(env | cut -d= -f1)
  # ${XDG_SESSION_ID} ${HOSTNAME} ${TERM} ${SHELL} ${HISTSIZE} ${SSH_CLIENT} ${NNHOST} ${OLDPWD} ${SSH_TTY} ${NGINX_HOST} ${USER} ${LS_COLORS} ${MAIL} ${PATH} ${PWD} ${LANG} ${HISTCONTROL} ${SHLVL} ${HOME} ${LOGNAME} ${SSH_CONNECTION} ${LESSOPEN} ${XDG_RUNTIME_DIR} ${_}
  defined_envs=$(printf '${%s} ' $(env | cut -d= -f1))
  [ -d "$template_dir" ] || return 0
  if [ ! -w "$output_dir" ]; then
    echo >&3 "$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"
    echo >&3 "$ME: Running envsubst on $template to $output_path"
    # 这里指定只替换定义的环境变量,因此不会覆盖掉nginx约定好的$host...等变量
    # 相当于执行了
    # envsubst "${XDG_SESSION_ID} ${HOSTNAME} ${TERM} ${SHELL} ${HISTSIZE} ${SSH_CLIENT} ${NNHOST} ${OLDPWD} ${SSH_TTY} ${NGINX_HOST} ${USER} ${LS_COLORS} ${MAIL} ${PATH} ${PWD} ${LANG} ${HISTCONTROL} ${SHLVL} ${HOME} ${LOGNAME} ${SSH_CONNECTION} ${LESSOPEN} ${XDG_RUNTIME_DIR} ${_}" <"$template" >"$output_path"
    envsubst "$defined_envs" <"$template" >"$output_path"
  done
}

auto_envsubst

exit 0
原文地址:https://www.cnblogs.com/xiaojiluben/p/15578946.html