How do I Configure Environment Variables in Ansible

March 1, 2015

It’s common to use environment variables to configure applications, especially to store sensible information like passwords and keys (if you are familiar to Heroku you know what I mean). Here I will show how I do it using Ansible and Supervisor.

The solution is simple, in the same directory of your playbook create another named private_vars (it can be named anything but I like this name because of the contrast with the Ansible group_vars convention). Don’t forget to put this directory in the ignore file of your CVS (you don’t want to share your passwords, right?).

Now create an yaml file inside private_vars with your configurations, e.g.

# production.yml

app_environment: |

I like to put the name of my environment in the file, e.g., production, staging

Now lets configure Supervisor, bellow is an simple example of the Ansible template file.

# example.j2.conf
environment={{ app_environment | mandatory | replace('\n', ',') }}

The important here is the environment parameter. We are using the app_environment from production.yml. We are also applying two filters to it.

  • mandatory to fail fast and verbose if for some reason the variable isn’t defined
  • replace to format the parameter to an acceptable syntax for Supervisor (comma separated)

That’s it, you are ready to go, just run your playbook passing the environment file as parameter, e.g.

$ ansible-playbook -l production -e @private_vars/production.yml site.yml

This is the way I handle environment variables in Ansible but there is other solutions for sure.

comments powered by Disqus