Build a correct Ansible inventory, INI or YAML
The inventory tells Ansible which hosts to manage and how to reach them. Getting the group, variable, and children syntax right by hand is fiddly — especially across the INI and YAML formats. This builder lets you model groups, hosts, variables, and hierarchy once and emit either format cleanly.
How it works
In INI format, hosts are listed under a [group] header, group variables go in a [group:vars] section, and nested groups are declared in [group:children]. Per-host variables follow the host name on the same line as key=value pairs. This is the layout Ansible’s ini inventory plugin parses.
In YAML format, everything nests under the implicit all group: all → children → <group> → hosts/vars/children. Each host becomes a mapping whose values are its connection variables. The builder quotes any YAML scalar that could be misread as a number or boolean, so a value like ansible_port: "2222" stays a string when intended.
Side-by-side format comparison
The same three-host setup looks very different in each format, but Ansible parses both identically:
INI
[webservers]
web1 ansible_host=10.0.0.1 ansible_user=ubuntu
[databases]
db1 ansible_host=10.0.0.10 ansible_user=postgres
[production:children]
webservers
databases
[production:vars]
ansible_python_interpreter=/usr/bin/python3
YAML
all:
children:
production:
vars:
ansible_python_interpreter: /usr/bin/python3
children:
webservers:
hosts:
web1:
ansible_host: 10.0.0.1
ansible_user: ubuntu
databases:
hosts:
db1:
ansible_host: 10.0.0.10
ansible_user: postgres
Practical guidance
ansible_hostaliases. Name inventory hosts after their role (db-primary) while the real connection goes to an IP. This survives IP changes without touching playbooks.- Group vars vs host vars. Set values shared across a group (like
ansible_user) as group vars; override per-host only when one machine genuinely differs. This keeps the inventory readable and prevents per-host sprawl. - Hierarchy for flexible targeting. A
production:childrengroup letshosts: productionin a playbook target all sub-groups at once, while individual groups (webservers,databases) remain independently targetable. - Validate before using. Run
ansible-inventory -i inventory.yml --listto see the fully-resolved host and variable tree. This catches children loops, missing group references, and YAML quoting mistakes before a playbook run. - Dynamic inventories. For cloud environments, consider pairing this static file with a dynamic plugin (AWS EC2, Azure RM, GCP) so hosts appear automatically as they are provisioned.