Skip to content

Instantly share code, notes, and snippets.

@thomashartm
Last active June 20, 2024 12:55
Show Gist options
  • Save thomashartm/cf171ca4d52443ee809f255899127ddc to your computer and use it in GitHub Desktop.
Save thomashartm/cf171ca4d52443ee809f255899127ddc to your computer and use it in GitHub Desktop.
Output environment variables based on AWS SSM params and write .env files. This might be helpful when relying on centrally managed environments variables for local development or CICD
#!/bin/bash
set -e
# Enable -x only for debug purposes
#set -x
# Retrieves a JSON parameter from SSM and output them as key/values
# ./create-env.sh -p <system manager param name>
# Write the output to .env.local
# ./create-env.sh -p <system manager param name> > .env.local
#
# Expects an existing Systems Manager Param with the following structure:
# {
# key_1: property_1,
# key_2: property_2,
# key_3: property_3,
# }
check_arg() {
local argument_name=$1
local argument=$2
if [[ -z $argument ]]; then
echo "Missing required argument: $argument_name" >&2
usage
exit 1
fi
}
# Function to display script usage
usage() {
echo "Basic Usage: $0 -p <system manager param name> "
echo "Usage to persist an env file: $0 -p <system manager param name> > .env"
}
not_authenticated() {
echo "Unable to access AWS services due to missing or timed out AWS credentials. Please re-login to AWS."
}
# Parse command line arguments
while getopts ":p:" opt; do
case $opt in
p)
parameter_name=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
usage
exit 1
;;
esac
done
check_arg "SystemParam" $parameter_name
sts_string=$(aws sts get-caller-identity | jq -r '.Arn')
if [[ $sts_string == *"Unable to locate credentials"* ]]; then
not_authenticated
exit 1
fi
get_config_json() {
local parameter_name=$1
json=$(aws ssm get-parameter --name "$parameter_name" --with-decryption --query 'Parameter.Value' --output text)
json=$(echo "$json" | tr -d "'")
echo $json
}
parameters_json=$(get_config_json $parameter_name)
PROPERTY_1=$(echo $parameters_json | jq -r '.property_1')
PROPERTY_2=$(echo $parameters_json | jq -r '.property_2')
PROPERTY_3=$(echo $parameters_json | jq -r '.property_3')
ENV_FILE=$(cat <<EOF
KEY_1=$PROPERTY_1
KEY_2=$PROPERTY_2
KEY_3=$PROPERTY_3
EOF)
# Use this to write .env from within this script
# echo "$ENV_FILE" | sed 's/\\n/\n/g' > .env
echo "$ENV_FILE" | sed 's/\\n/\n/g'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment