Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env bash
- # aws-entrypoint.sh
- # Translates environment variables that contain aws secrets into their
- # secret values. This script is useful as an entrypoint into docker:
- #
- # Dockerfile:
- # ENTRYPOINT ["/aws-entrypoint.sh", "/your-original-entrypoint.sh"]
- #
- # Dockerfile Alphine Linux Required installation
- # # install bash, jq, aws-cli
- # RUN apk -v --update add \
- # bash \
- # grep \
- # jq \
- # python \
- # py-pip \
- # groff \
- # less \
- # mailcap \
- # && \
- # pip install awscli python-magic --upgrade && \
- # apk -v --purge del py-pip && \
- # rm /var/cache/apk/*
- #
- # Example environment variable format:
- # string value of key 'username' stored into FOO: FOO={{runtime-secret:my-secret-name:username}}
- # raw json value stored into FOO: FOO={{runtime-secret:my-secret-name}}
- #
- split_newlines() {
- # split lines into array $split_parts
- local IFS=$'\n'
- split_parts=($@)
- }
- # read from `env` and split on '='
- while IFS='=' read -r name value ; do
- # we are only interested in values starting with {{runtime-secret:
- if [[ "$OSTYPE" == "darwin"* ]]; then
- matches=$(grep -E -o '{{runtime-secret:.*?}}'<<< "${value}")
- else
- matches=$(grep -P -o '{{runtime-secret:.*?}}'<<< "${value}")
- fi
- split_newlines "${matches}"
- if [[ ${split_parts[@]} == "" ]]; then
- # doesn't have any secrets, skip
- continue
- fi
- # replace all secrets
- for rt_value in "${split_parts[@]}"; do
- # remove the last '}}' and then split on ':'
- IFS=':' read -r -a parts <<< "${rt_value%??}"
- # grab secret from aws
- my_secret=$(aws secretsmanager get-secret-value --secret-id "${parts[1]}" --query "SecretString")
- if [[ $? -ne 0 ]]; then
- if ! hash aws 2>/dev/null; then
- echo "The aws cli command was not found but an environment variable ${name} requiring it was specified. Halting execution." 1>&2
- exit 1
- fi
- echo "Failed to find expected aws secret for environment variable ${name}, halting execution." 1>&2
- exit 1
- fi
- if [[ ${#parts[@]} -gt 2 ]]; then
- # if a key was specified, then get that key's value
- my_value=$(jq -r 'fromjson | .'${parts[2]}' | select (.!=null)'<<<"${my_secret}")
- else
- # otherwise just turn it into nice json
- my_value=$(jq -r 'fromjson'<<<"${my_secret}")
- fi
- if [[ $? -ne 0 ]]; then
- if ! hash jq 2>/dev/null; then
- echo "The jq command was not found but an environment variable ${name} requiring it was specified. Halting execution." 1>&2
- exit 1
- fi
- echo "Failed to parse expected json from environment variable ${name}, ${value}, halting execution." 1>&2
- exit 1
- fi
- # replace the runtime secret string with the requested secret value
- value="${value//${rt_value}/${my_value}}"
- done
- # declare the variable again, with the interpreted value
- declare ${name}="${value}"
- done < <(env)
- exec "$@"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement