Ansible inventory

Andrea Dainese
September 30, 2023
Post cover

In this article, we’ll explore the two methods for defining an inventory usable by Ansible. The inventory serves as the source of truth containing the information that Ansible will use to connect to devices. The inventory also allows for defining variables at the host or group level. Specifically, variables can be used, in advanced scenarios, to define all infrastructure parameters, such as interfaces, IP addresses, router IDs…

Ansible supports both static and dynamic inventories. The static inventory is defined by a file in INI or YAML format, while the dynamic inventory is an executable that prints JSON to standard output.

Static Inventory in INI Format

The static inventory in INI format follows the following structure:

[all]
r1.example.com ansible_host=169.254.1.21

[routers]
r[1:9].example.com

[routers:vars]
ansible_user=admin
ansible_ssh_pass=cisco
ansible_connection=ansible.netcommon.network_cli
ansible_network_os=cisco.ios.ios

Static Inventory in YAML Format

The static inventory in YAML format follows the following structure:

all:
  hosts:
    r1.example.com:
      ansible_host: 169.254.1.21
routers:
  hosts:
    r[1:9].example.com:
  vars:
    ansible_user: admin
    ansible_ssh_pass: cisco
    ansible_connection: ansible.netcommon.network_cli
    ansible_network_os: cisco.ios.ios

Dynamic Inventory in JSON Format

As described earlier, the dynamic inventory must use the JSON format according to the following structure:

{
  "_meta": {
    "hostvars": {
     "r1.example.com": {
        "ansible_host": "169.254.1.21"
      }
    }
  },
  "routers": {
    "hosts": [
      "r1.example.com"
    ],
    "vars": {
      "ansible_connection": "ansible.netcommon.network_cli",
      "ansible_network_os": "cisco.ios.ios",
      "ansible_ssh_pass": "cisco",
      "ansible_user": "admin"
    }
  }
}