Part 05: Ansible YAML Inventory Setting

1 minute read

Updated:

Ansible Inventory YAML Format

Our last inventory file was the INI format. There is also another format called .yaml or .yml which is more readable and may be required depending on the version of Ansible or module. Therefore, it is a good idea to learn how to create an inventory file in YAML format.

Default groups

There are two default groups all and ungrouped. The all group contains every host. The ungrouped group contains all hosts that don’t have another group aside from all. Every host will always belong to at least 2 groups (all and ungrouped or all and some other group).

There are essential keys that are primarily used in the inventory file in Ansible.

  • children to create groups of group
  • hosts to add device to the group
  • vars to define variables.

Another important point about the YAML file is indentation. This means that all keys and values at the same level must have the same indentation. This is the only way to separate key/value pairs without parentheses or brackets.

Let’s first create the groups, add devices and then the variables.

In our previous inventory file, we have network as all group, switch and router as sub-groups. So first we create all group, and then with the help of the “children” key and create sub-groups as below:

  network:
    children:
      switch:
      router:

Then we will add devices with the help of “hosts” key in sub-groups.

  network:
    children:
      switch:
        hosts:
          sw1:
      router:
        hosts:
          r1:
          r2:

Lastly, we create variables under the network group with the help of “vars” key.

---
  network:
    vars:
      ansible_user: admin
      ansible_password: cisco
      ansible_network_os: ios
      ansible_connection: network_cli
    children:
      switch:
        hosts:
          sw1:
      router:
        hosts:
          r1:
          r2: 

Above is the result of the inventory file in the format of YAML. You can read more How to build your inventory on the website.

In Part 04 we define the location of the inventory in ansible.cfg as named hosts file, now we changed the file name to hosts.yml to use YAML format inventory file.

[defaults]
inventory = ./hosts.yml 
timeout = 60
host_key_checking = false

Now Ping module result:

root@NetworkAutomation-1:~# ansible all -m ping
r2 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
r1 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}
sw1 | SUCCESS => {
    "changed": false,
    "ping": "pong"
}

Comments