Populate Ansible from AWS Secrets Manager

Shane Dowling
Sep 3, 2020 · 2 min read

One of the ways to improve your security and avoid passing around env files is to follow the twelve factor app and start populating your secrets from the environment. Another improvement is to pull those secrets from a known secret store, with features like rotation, auditing etc.


  • Ansible

It’s worth testing your AWS calls to just extract the secret you’re interested in to stdout, from the terminal tests some calls like:

aws secretsmanager get-secret-value --secret-id some/secret/name --query SecretString --output text

Or for json you might do something like:

aws secretsmanager get-secret-value --secret-id secrets| jq --raw-output '.SecretString' | jq -r .API_KEY

Ansible Config

Once you have secrets manager outputting your secrets to stdout, you can utilise it in Ansible. In this example I’m outputting to an env file but this could but used anywhere in Ansible. Instead of outputting to a file you could set its own environment variables then spin up the project from Ansible without outputting to a file anywhere.

- name: Setting env with some secret
executable: /bin/bash
shell: |
aws secretsmanager get-secret-value --secret-id some/secret/name --query SecretString --output text
register: some_secret
- name: pass response of ssm to .env file
become: no
dest: '{{ some_environment_path }}/.env'
state: present
create: yes
marker: "# {mark} MY SECRET FROM AWS #"
block: |
SOME_SECRET='{{ some_secret.stdout }}'

And that’s it! Anything I could’ve done better(which I’m sure there is), do let me know!

Tech Blog

Random smattering of technical posts

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store