Ansible inventory structure

inventory

The inventory is Ansible’s source of truth. It is where all your hosts and groups, along with data like NTP and VLANs, are defined. Building and maintaining an inventory for Ansible can be difficult, but less so if you get the structure right.

$ tree inventory
inventory
├── group_vars
│   ├── all
│   │   └── ansible.yml
│   ├── bergen
│   │   └── vlan.yml
│   └── oslo
│       └── vlan.yml
├── groups_and_hosts
└── host_vars
    ├── switch1
    │   ├── ansible.yml
    │   ├── ntp.yml
    └── switch2
        ├── ansible.yml
        ├── ntp.yml

I define my groups and hosts in a (ini) file named groups_and_hosts. In addition to all the hosts, this file holds two groups that describe “where” and “what”. No variables are defined here – they live in separate (yaml) files in the host_vars or group_vars directories.

$ cat groups_and_hosts
[campus:children]
access

[access]
switch1
switch2

[norway:children]
bergen
oslo

[bergen]
switch1

[oslo]
switch2

If you have a role named NTP, I suggest creating a corresponding inventory file in host_vars or group_vars named ntp.yml. The default variables configured in the role are then replaced by those defined in the inventory and in this example the ntp.yml file. Additionally, I find it logical to give each host a host_vars file named ansible.yml for Ansible-specific variables (those starting with ansible_).

$ cat host_vars/switch1/ansible.yml
---
ansible_connection: ansible.netcommon.network_cli
ansible_host: 192.0.2.10
ansible_network_os: cisco.ios.ios

Should you define variables in host_vars or group_vars? Some variables, like ansible_host, obviously belong in host_vars, but in most cases, you can use both. If there is no apparent reason to use one over the other, then I prefer to use host_vars. I find host_vars to be more explicit while also, in most cases, allowing for more flexibility down the road. For example, some switches might require a VRF and dedicated interface to reach the NTP servers. In this example, one option is to place the NTP servers in group_vars based on locations, and then add separate NTP files in host_vars with the VRF-related stuff for the devices that require it. However, in this case, I tend to write all the NTP-related variables as host_vars, skipping groups_vars altogether.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *