Skip to content

Instantly share code, notes, and snippets.

@sonodar
Last active April 3, 2024 06:24
Show Gist options
  • Save sonodar/b3c80c8b9e60f4e6dcda9108c46a6089 to your computer and use it in GitHub Desktop.
Save sonodar/b3c80c8b9e60f4e6dcda9108c46a6089 to your computer and use it in GitHub Desktop.
Get secret parameters from Amazon EC2 Parameter Store
#!/usr/bin/env bash +x
# Usage: get_ssm_parameters.sh aws_region path_prefix
# $1 aws_region : SSM Parameter Region (ex. ap-northeast-1)
# $2 path_prefix: SSM Parameter Path prefix (ex. /app/api/staging)
# IAM Policy example:
# {
# "Version": "",
# "Statement": [{
# "Sid": ""
# "Effect": "Allow"
# "Action": ["ssm:GetParametersByPath]"
# "Resource": "arn:aws:ssm:YOUR_REGION:YOUR_AWS_ACCOUNT_ID:parameter/app/api/staging/*"
# }]
# }
if [ $# -lt 2 ]; then
echo "Usage: $0 aws_region path_prefix" 1>&2
exit 1
fi
readonly AWS_REGION="${1}"
readonly PATH_PREFIX="${2}"
# $1 nextToken
get_parameters_by_path() {
local nextToken="${1}"
aws ssm get-parameters-by-path --region "${AWS_REGION}" \
--path "${PATH_PREFIX}" --recursive --with-decryption \
$([ -z ${nextToken} ] || echo "--next-token ${nextToken}")
}
# $1 parameterName
# $2 parameterValue
print_env_vars() {
local envName=$(basename "${1}")
local envValue="${2}"
echo "${envName}=\"${envValue}\""
}
print_parameters() {
local nextToken=""
while true; do
responseJson=$(get_parameters_by_path "${nextToken}")
declare -i parameterCount=$(echo ${responseJson} | jq -c '.Parameters[].Name' | wc -l)
[ ${parameterCount} -lt 1 ] && break
echo $responseJson | jq -r '.Parameters[]|[.Name,.Value] | @sh' | while read LINE; do
declare -a nameAndValue=($(echo $LINE | tr -d \'))
print_env_vars ${nameAndValue[@]}
done
nextToken=$(echo ${responseJson} | jq -r '.NextToken')
if [ -z ${nextToken} ] || [[ ${nextToken} == "null" ]]; then
break
fi
done
}
print_parameters
@realsby
Copy link

realsby commented Oct 30, 2019

get_ssm_parameters.sh it is cool but it does not work properly if the parameter's value is "*"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment