Organizing Group Vars Files in Ansible

Osvaldo Toja bio photo By Osvaldo Toja Comment

from here

In addition to the storing variables directly in the INI file, host and group variables can be stored in individual files relative to the inventory file.

directory layout

production/
├── group_vars
│   └── server.yml
└── inventory
staging/
├── group_vars
│   └── server
└── inventory
group-vars.yml

playbook

# group-vars.yml
- hosts: all
  user: osvaldo
  sudo: no
  gather_facts: False

  tasks:
     - debug: msg="reading from {{env_name}}"

files in production directory

inventory

# production/inventory
[server]
localhost   ansible_connection=local

vars

# production/group_vars/server.yml
env_name: production

files in staging directory

inventory

# staging/inventory
[server]
localhost   ansible_connection=local

vars

# staging/group_vars/server
env_name: staging

executing the playbook

using data from staging directory

$ ansible-playbook -i staging group-vars.yml

PLAY [all] ********************************************************************

TASK: [debug msg="reading from "] *********************************
ok: [localhost] => {
    "msg": "reading from staging"
}

PLAY RECAP ********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0

using data from production directory

$ ansible-playbook -i production group-vars.yml

PLAY [all] ********************************************************************

TASK: [debug msg="reading from "] *********************************
ok: [localhost] => {
    "msg": "reading from production"
}

PLAY RECAP ********************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0

Interesting fact: ansible-playbook when provided a directory as the inventory, will search by default a file named inventory so no need to specify -i production/inventory, only -i production will work just fine.

comments powered by Disqus