Search code examples
ansibleansible-2.xansible-inventory

Ansible nested host_vars folders


I'm trying to group all host_vars files by their parent and I have the following folder structure:

- mail.yml
- hosts.yml
- group_vars/
  - pool1.yml
  - pool2.yml
- host_vars/
  - ns1.me.yml
.....

and hosts.yml:

all:
  children:
    pool1:
      hosts:
        ns1.me:
          ansible_host: 10.10.0.1
        ns2.me:
          ansible_host: 10.10.0.2
    pool2:
      hosts:
        ns3.me:
          ansible_host: 10.10.0.14

In this setup, it works fine but if I try to add a nested folder between host_vars and ns1.me.yml ansible will not get variables

From ansible docs: "You can also create directories named after your groups or hosts. Ansible will read all the files in these directories in lexicographical order." - https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html but isn't working ...

desired folder structure:

- host_vars/
  - pool1/
    - ns1.me.yml
    - ns2.me.yml
  - pool2/
    - ns3.me.yml

What I'm missing? :)


Solution

  • This is a misunderstanding of the statement "create directories named after your groups or hosts". You can create directories after your groups in group_vars and you can also create directories after your hosts in host_vars. But in your case

    - host_vars/
        pool1/
          ns1.me.yml
          ns2.me.yml
        pool2/
          ns3.me.yml
    

    you've created the directories after groups in host_vars. This can't work.


    This Ansible's feature is used when you have more files with variables for a host or group. For example

      mail.yml
      hosts.yml
      group_vars/
        pool1/
          vars1.yml
          vars2.yml
        pool2/
          vars1.yml
          vars2.yml
      host_vars/
        ns1.me/
          varsX.yml
          varsY.yml