Manage your secrets inside containers using AWS SSM

Sagar Gangurde
Data Engineering
Published in
2 min readSep 11, 2022

Let’s say, we are working on a python application which is running inside a docker container and it needs access to database hosted on AWS RDS. Storing the database credentials inside repository is not recommended. So we need a solution to securely store and retrieve database credentials.

There are 2 options available. AWS secret manager and AWS SSM.
AWS SSM looks like a suitable match here, as it solves the problem and unlike AWS secret manager we don’t end up paying price for each secret that we store.

AWS SSM (Systems Manager Parameter Store) provides secure storage for secrets management. We can store data such as usernames/passwords as parameter values. We just need a name of the parameter and the corresponding value. We can store parameter values as plain text or secured strings i.e. encrypted data. We can query Systems Manager parameters in our applications through AWS SDK, AWS command line using the unique name that we specify when we created the parameter.

Let’s create AWS SSM parameter for database username as plain string and password as encrypted string.

aws ssm put-parameter --name "/myapp/db-username" --value "SomeUser" --type "String"aws ssm put-parameter --name "/myapp/db-password" --value "P@sSwW)rd" --type "SecureString"

In order to pass database username and password SSM parameters as environment variables to docker image, we need to add following to Dockerfile:

ARG DB_USERNAME
ARG DB_PASSWORD
ENV DB_USERNAME=${DB_USERNAME}
ENV DB_PASSWORD=${DB_PASSWORD}

Then we need to add following commands to docker build script (lets call it docker_build.sh) to query credentials from AWS SSM.

DB_USERNAME=`aws ssm get-parameters --region us-east-1 --name "/myapp/db-username" --query Parameters[0].Value | tr -d '"'`DB_PASSWORD=`aws ssm get-parameters --region us-east-1 --name "/myapp/db-password" --with-decryption --query Parameters[0].Value | tr -d '"'`docker buildx build --platform linux/amd64 . -t <image_tag> -f <docker_file_path> --build-arg DB_USERNAME=$DB_USERNAME --build-arg DB_PASSWORD=$DB_PASSWORD --load

Now that our database credentials are available as environment variables inside docker container, python application running inside container can access the database credentials like any other environment variables.

import os
db_username = os.environ.get('DB_USERNAME')
db_password = os.environ.get('DB_PASSWORD')

We can also delete any obsolete AWS SSM parameters as follows:

aws ssm delete-parameter --name "/myapp/db-username"
aws ssm delete-parameter --name "/myapp/db-password"

AWS SSM Parameters also supports versioning. i.e. we can have multiple values of the same parameter with different associated version. This is useful while rotating secrets.

--

--