Amazon Web Services

How to load parameter store values into an EC2’s environment variables

Reading Time: < 1 minute

In this article I’m going to show you how to take all the parameters you have stored in the AWS Parameter store and load them into EC2 as environment variables.

It’s pretty simple and I’ll jump right into the code.

I created a shell script named: load_ssm_parameters.sh. For simplicity, I have the project and environment variables hardcoded below, but in reality, those values get set automatically from my EC2 instances tags.

#!/bin/bash
project=geekcafe/cms   
environment=dev          
parameter_store_prefix=“/${project}/${environment}"

For my parameters in the SSM Parameter store, my pattern is:

/company/project/environment/parameter_name, but you can easily shorten that to project/environment/parameter_name

Depending on how many levels you go down will define the array element on the split(“/”)[4]. In my case, it was 4 levels into the array.

export_statement=$(aws ssm get-parameters-by-path \
    --path "$parameter_store_prefix" \
    --region us-east-1 --recursive \
    --with-decrypt \
    | jq -r '.Parameters[] | "export " + (.Name | split("/")[4] | ascii_upcase | gsub("-"; "_")) + "=\"" + .Value + "\""')

The statement above will execute the AWS CLI command line app and pull back all of my parameters and put them into a variable named export_statement. That variable will be evaluated which will load each one key/value pair into memory and make it readily available for my application to consume.

Execute the statement below it accomplish what I mentioned above.

eval $export_statement

In order to persist the values after a reboot, I essentially need to make sure that this same script executes during the instance launch.

You can accomplish this by placing the script into the /etc/profile.d directory. Anything in that directory is launched during the boot process. I’ll have everything ready for waiting for me.

Quick note: make sure you give the script execution access:

chmod +x /etc/profile.d/load_ssm_parameters.sh