elasticsearch-env-from-file 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/bin/bash
  2. set -e -o pipefail
  3. # Allow environment variables to be set by creating a file with the
  4. # contents, and setting an environment variable with the suffix _FILE to
  5. # point to it. This can be used to provide secrets to a container, without
  6. # the values being specified explicitly when running the container.
  7. #
  8. # This script is intended to be sourced, not executed, and modifies the
  9. # environment.
  10. for VAR_NAME_FILE in $(env | cut -f1 -d= | grep '_FILE$'); do
  11. if [[ -n "$VAR_NAME_FILE" ]]; then
  12. VAR_NAME="${VAR_NAME_FILE%_FILE}"
  13. if env | grep "^${VAR_NAME}="; then
  14. echo "ERROR: Both $VAR_NAME_FILE and $VAR_NAME are set. These are mutually exclusive." >&2
  15. exit 1
  16. fi
  17. if [[ ! -e "${!VAR_NAME_FILE}" ]]; then
  18. # Maybe the file doesn't exist, maybe we just can't read it due to file permissions.
  19. # Check permissions on each part of the path
  20. path=''
  21. if ! echo "${!VAR_NAME_FILE}" | grep -q '^/'; then
  22. path='.'
  23. fi
  24. dirname "${!VAR_NAME_FILE}" | tr '/' '\n' | while read part; do
  25. if [[ "$path" == "/" ]]; then
  26. path="${path}${part}"
  27. else
  28. path="$path/$part"
  29. fi
  30. if ! [[ -x "$path" ]]; then
  31. echo "ERROR: Cannot read ${!VAR_NAME_FILE} from $VAR_NAME_FILE, due to lack of permissions on '$path'" 2>&1
  32. exit 1
  33. fi
  34. done
  35. if ! [[ -r "${!VAR_NAME_FILE}" ]]; then
  36. echo "ERROR: File ${!VAR_NAME_FILE} from $VAR_NAME_FILE is not readable." 2>&1
  37. else
  38. echo "ERROR: File ${!VAR_NAME_FILE} from $VAR_NAME_FILE does not exist" >&2
  39. fi
  40. exit 1
  41. fi
  42. FILE_PERMS="$(stat -L -c '%a' ${!VAR_NAME_FILE})"
  43. if [[ "$FILE_PERMS" != "400" && "$FILE_PERMS" != "600" ]]; then
  44. if [[ -L "${!VAR_NAME_FILE}" ]]; then
  45. echo "ERROR: File $(readlink "${!VAR_NAME_FILE}") (target of symlink ${!VAR_NAME_FILE} from $VAR_NAME_FILE) must have file permissions 400 or 600, but actually has: $FILE_PERMS" >&2
  46. else
  47. echo "ERROR: File ${!VAR_NAME_FILE} from $VAR_NAME_FILE must have file permissions 400 or 600, but actually has: $FILE_PERMS" >&2
  48. fi
  49. exit 1
  50. fi
  51. echo "Setting $VAR_NAME from $VAR_NAME_FILE at ${!VAR_NAME_FILE}" >&2
  52. export "$VAR_NAME"="$(cat ${!VAR_NAME_FILE})"
  53. unset VAR_NAME
  54. # Unset the suffixed environment variable
  55. unset "$VAR_NAME_FILE"
  56. fi
  57. done