91.2 Inventory, groups and host patterns
Story (fictional teaching scenario). At a fictional travel startup in Goa, Leila from Lisbon kept server names in a spreadsheet. Ansible could not read it. She moved the names into an inventory file, grouped them into web and db, and made a parent group lab that holds both. Now she can say "run on web only" or "run on everything except db" with a short pattern.
Why
Ansible must know which servers exist and how to reach them. Groups let you change one kind of server without touching the others.
What
- Inventory — A file (INI or YAML) that lists hosts and groups.
- Group — A name in square brackets, like
[web], holding hosts. - Child group —
[lab:children]makeslabcontain other groups. - Host variable — A setting next to a host, like
ansible_host=(the real address to connect to). - Pattern — Words that pick hosts:
web,all,web:db(either),lab:!db(lab but not db),web:&prod(in both).
How
- Write the inventory file.
- Draw it with
ansible-inventory --graphto check the groups. - Use
--list-hostswith your pattern before running anything real.
Example 1: An INI inventory
[web]
web1 ansible_host=192.0.2.11
web2 ansible_host=192.0.2.12
[db]
db1 ansible_host=192.0.2.21
[lab:children]
web
db
Line by line: [web] starts a group. web1 ansible_host=192.0.2.11 is a host name plus the address to reach it (192.0.2.x is a documentation-only address range). [lab:children] says the group lab is made of the groups web and db.
Example 2: Draw the inventory
ansible-inventory -i inventory.ini --graph
Output (tested on ansible-core 2.22.0, local practice lab)
@all:
|--@ungrouped:
|--@lab:
| |--@web:
| | |--web1
| | |--web2
| |--@db:
| | |--db1
What it means: Every inventory has all and ungrouped. lab holds web and db, exactly as written.
Example 3: Test a pattern before you run
ansible 'lab:!db' -i inventory.ini --list-hosts
Output (tested on ansible-core 2.22.0, local practice lab)
hosts (2):
web1
web2
What it means: lab:!db means "everything in lab, except db". Only the two web hosts would be touched. Quote the pattern so your shell does not read the !.
Ravindra Bagale's Tip
Always run --list-hosts with a new pattern first. It costs nothing and shows exactly who will be touched.
नवीन pattern असेल तर आधी --list-hosts चालवा. काही खर्च नाही आणि नक्की कोणाला हात लागेल ते दिसतं.
नया pattern हो तो पहले --list-hosts चलाओ. कोई खर्च नहीं और पक्का दिखता है किसे छुआ जाएगा.
Did you understand? Let us try it once more.