Inventory linter and limit

January 7, 2022 - Reading time: 2 minutes

Ansible requires an inventory with the name of targets (hosts) where it will run the modules.
The inventory allows multiple levels of grouping, and can also include variables for each host.
You can also add specific options like ansible_connection

root@f12d33c83ada:~# cat inventory.yaml
---
all:
  hosts:
    mylocal:
      ansible_connection: local
  children:
    webservers:
      hosts:
        w1:
          ansible_host: 172.17.0.3
          http_port: 80
    database:
      vars:
        ntp_server: time.google.com
      hosts:
        d1:
          ansible_host: 172.17.0.4
        d2:
          ansible_host: 172.17.0.5

You can use a linter to confirm that the syntax of the file is correct before trying to use it:

root@f12d33c83ada:~# pip install yamllint
root@f12d33c83ada:~# yamllint inventory.yaml
root@f12d33c83ada:~#

Then we can run the module in a single host, a group, or use --limit to run it only in one host or a sub-group in a group.

# Single host
root@f12d33c83ada:~# ansible mylocal -i inventory.yaml -m ping
mylocal | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
# Group
root@f12d33c83ada:~# ansible webservers -i inventory.yaml -m ping
w1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}
# Group with limit
root@f12d33c83ada:~# ansible database -i inventory.yaml -m ping --limit d1
d1 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
}