env_secrets_expand.sh 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #!/bin/sh
  2. : ${ENV_SECRETS_DIR:=/run/secrets}
  3. function env_secret_debug()
  4. {
  5. if [ ! -z "$ENV_SECRETS_DEBUG" ]; then
  6. echo -e "\033[1m$@\033[0m"
  7. fi
  8. }
  9. # usage: env_secret_expand VAR
  10. # ie: env_secret_expand 'XYZ_DB_PASSWORD'
  11. # (will check for "$XYZ_DB_PASSWORD" variable value for a placeholder that defines the
  12. # name of the docker secret to use instead of the original value. For example:
  13. # XYZ_DB_PASSWORD={{DOCKER-SECRET:my-db.secret}}
  14. env_secret_expand() {
  15. var="$1"
  16. eval val=\$$var
  17. if secret_name=$(expr match "$val" "{{DOCKER-SECRET:\([^}]\+\)}}$"); then
  18. secret="${ENV_SECRETS_DIR}/${secret_name}"
  19. env_secret_debug "Secret file for $var: $secret"
  20. if [ -f "$secret" ]; then
  21. val=$(cat "${secret}" | grep "${var}" | cut -d "=" -f 2)
  22. export "$var"="$val"
  23. env_secret_debug "Expanded variable: $var=$val"
  24. else
  25. env_secret_debug "Secret file does not exist! $secret"
  26. fi
  27. fi
  28. }
  29. env_secrets_expand() {
  30. for env_var in $(printenv | cut -f1 -d"=")
  31. do
  32. env_secret_expand $env_var
  33. done
  34. if [ ! -z "$ENV_SECRETS_DEBUG" ]; then
  35. echo -e "\n\033[1mExpanded environment variables\033[0m"
  36. printenv
  37. fi
  38. }
  39. env_secrets_expand