Skip to content

Instantly share code, notes, and snippets.

@diegofcornejo
Last active April 23, 2023 05:40
Show Gist options
  • Select an option

  • Save diegofcornejo/b665f3880f93aa92510b1d04f69aab76 to your computer and use it in GitHub Desktop.

Select an option

Save diegofcornejo/b665f3880f93aa92510b1d04f69aab76 to your computer and use it in GitHub Desktop.
Export SSM Parameters to Environment Variables and Append to .bashrc
#======================#
# Without dependencies #
#======================#
#!/bin/bash
# This script will export all SSM parameters under a given path as environment variables
# It will also append the export statements to the ~/.bashrc file so that they are available on future logins
# Set some parameters
APP="myapp"
SERVICE="api"
ENVIRONMENT="production"
REGION="us-east-1"
# Set the SSM path
SSM_PATH="/$APP/$SERVICE/$ENVIRONMENT"
# Get all SSM parameter names under the given path
SSM_PARAMETER_NAMES=$(aws ssm get-parameters-by-path \
--region $REGION \
--path "$SSM_PATH" \
--recursive \
--with-decryption \
--query 'Parameters[].Name' \
--output text)
# Loop through each parameter and export it as an environment variable
for name in $SSM_PARAMETER_NAMES; do
value=$(aws ssm get-parameter \
--region $REGION \
--name $name \
--with-decryption \
--query 'Parameter.Value' \
--output text)
if [ ! -z "$name" ] && [ ! -z "$value" ]; then
name=$(echo $name | awk -F/ '{print toupper($NF)}')
export "$name"="$value"
echo "Exported variable: $name=$value"
echo "export $name=$value" >> ~/.bashrc
fi
done
# Reload the bashrc file
source ~/.bashrc
#======================#
# With jq library #
#======================#
#!/bin/bash
# This script will export all SSM parameters under a given path as environment variables
# It will also append the export statements to the ~/.bashrc file so that they are available on future logins
# Set some parameters
APP="myapp"
SERVICE="api"
ENVIRONMENT="production"
REGION="us-east-1"
# Set the SSM path
SSM_PATH="/$APP/$SERVICE/$ENVIRONMENT"
# Get all SSM parameters under the given path
SSM_PARAMETERS=$(aws ssm get-parameters-by-path \
--region $REGION \
--path "$SSM_PATH" \
--recursive \
--with-decryption \
--query 'Parameters[*].{Name:Name,Value:Value}' \
--output json)
# Loop through each parameter and export it as an environment variable
echo "$SSM_PARAMETERS" | jq -r '.[] | @json' | while IFS= read -r parameter; do
name=$(echo "$parameter" | jq -r '.Name' | awk -F/ '{print toupper($NF)}')
value=$(echo "$parameter" | jq -r '.Value')
if [ ! -z "$name" ] && [ ! -z "$value" ]; then
export "$name"="$value"
echo "Exported variable: $name=$value"
echo "export $name=$value" >> ~/.bashrc
fi
done
# Reload the bashrc file
source ~/.bashrc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment