Ansible Inventory and Variable Precedence: A Practical Guide

Inventory Describes Reachability and Intent

An inventory answers two different questions: how Ansible connects to a host, and which operational groups that host belongs to. Keep connection details explicit and model roles such as webservers, dbservers, and production as groups.

[webservers]
web01 ansible_host=127.0.0.1 ansible_port=2201 ansible_user=web01
web02 ansible_host=127.0.0.1 ansible_port=2202 ansible_user=web02

[dbservers]
dbprod ansible_host=127.0.0.1 ansible_port=2203 ansible_user=dbprod

[production:children]
webservers
dbservers

Validate before changing anything:

ansible-inventory --graph
ansible-inventory --host web02
ansible production -m ping

The graph catches misspelled child groups; the host view shows the merged variables Ansible will actually use.

---

Put Values at the Narrowest Honest Scope

Shared web settings belong in group_vars/webservers.yml. A genuine exception for one machine belongs in host_vars/web02.yml. Defaults that callers should easily override belong in a role's defaults/main.yml.

Avoid play-level or extra variables as permanent fixes. They have high precedence and can make a correct inventory appear broken. When two values disagree, inspect rather than guess:

ansible-inventory --host web02 --yaml
ansible web02 -m debug -a 'var=service_port'

Then search every definition, including role defaults and vars, inventory files, play vars, included vars, registered results, and command-line -e values.

Patterns Are a Safety Boundary

The pattern after ansible-playbook -l decides which hosts are eligible. Preview it with ansible <pattern> --list-hosts. Use intersections and exclusions deliberately, and treat an unexpected empty match as a failure in CI rather than a harmless green run.

Dynamic inventory changes where host data comes from, not the need for stable grouping. Cache carefully, expose a graph for review, and tag cloud resources with the attributes your grouping rules require. A stale cache can be as dangerous as a stale static file.

Practice these failures in Repair the Broken Inventory, Which Variable Actually Wins, and Repair Dynamic Inventory.