How to handle environment specific role vars?

47 views
Skip to first unread message

Bo Vial

unread,
Nov 9, 2017, 5:49:03 PM11/9/17
to Ansible Project
I am trying to work out the best way to handle multiple environments (dev/stage/prod) in Ansible?

I have read the best practices outlined in the Ansible docs here: http://docs.ansible.com/ansible/latest/playbooks_best_practices.html

Having an entirely different inventory for dev/stage/prod makes sense but I am unsure how to achieve a similar separation for role vars.

For example, I have split the inventory per environment as follows:

inventories/
  production/
    hosts/
      groups_vars/
        group1
        group2
      host_vars/
        hostname1
        hostname2
  staging/
    hosts/
      group_vars/
        group1
      host_vars/
        stagehost1

The above works great for group vars and host vars, but I can't figure out a nice way to do something similar for role vars.

Currently, I have two possible candidate solutions

Option 1.
Set an environment variable 'ENVIRONMENT' to either 'production' or 'staging'. The first task in a role then includes a different vars file based on this environment variable. The directory structure would be:

roles/
  myrole/
    tasks/
      main.yml
    vars/
      main.yml <- common role vars
      production.yml <- production sepcific role vars
      staging.yml <- staging specific role vars

The first task in roles/myrole/tasks/main.yml would be
---
- name: Include environment specific role vars
  include_vars: "{{ lookup('env','ENVIRONMENT') }}.yml"

Option 2.
All my Ansible files will be stored in git. I could just keep a single roles/myroles/vars/main.yml file that is different between git branches "production" and "staging". I could then use git attributes to prevent this file from being modified during a merge so that they always remain independant. This solution would then result in a different main.yml depending on the git branch I am deploying.

I am currently leaning towards option 1, or are there better ways to manage this?
Reply all
Reply to author
Forward
0 new messages