Skip to main content
Infrastructure as Code (IaC) Cheat Sheets

Ansible Hosts File: Syntax, Examples, Flags & Production Guide

ansible hosts file is the static inventory file (INI or YAML) defining managed nodes and groups for Ansible automation. Default location /etc/ansible/hosts; location overridden via -i flag or ansible.cfg.

# /etc/ansible/hosts
[webservers]
www01.example.com
www02.example.com

Ansible inventory supports two syntaxes: INI (legacy, flat) and YAML (structured, recommended). INI uses brackets for groups and key=value for variables; YAML uses dictionaries and lists. The parser automatically detects format based on file extension or content.

Syntax Reference

INI Format (default)

# /etc/ansible/hosts (INI)
[webservers]
www01.example.com
www02.example.com

[dbservers]
db-[a:f].example.com   # range: a, b, c, d, e, f

[all:vars]
ansible_user=deploy
ansible_port=22

YAML Format

# inventory.yml
all:
  children:
    webservers:
      hosts:
        www01.example.com:
        www02.example.com:
      vars:
        http_port: 80
    dbservers:
      hosts:
        db-a.example.com:
        db-b.example.com:

CLI Usage

# Validate and list inventory
ansible-inventory --list -i ./production.yml

# Target a group from custom inventory
ansible webservers -i ./hosts -m ping

# Run playbook with multiple inventory sources
ansible-playbook -i ./inventory/ -i ./cloud.yml site.yml

Tested on Ansible core 2.15 (Ubuntu 24.04) with default INI parser.

Command Reference

Action CLI Command Provider/Context Key Flag Impact/Result
List all hosts ansible-inventory --list -i inventory.yml Any --list JSON output of groups and host variables
Target specific group ansible webservers -i hosts -m ping Any -i Pings all hosts in webservers group
Use multiple inventories ansible-playbook -i prod.ini -i staging.ini site.yml Multi-environment -i (repeatable) Merges hosts from both files
Override default location export ANSIBLE_INVENTORY=./custom/hosts Environment variable ANSIBLE_INVENTORY Changes default without -i flag
Set host variables inline db1 ansible_host=10.0.0.5 ansible_port=3306 INI per-host N/A Runtime connection override
Use ranges www[01:50].example.com INI/YAML [start:end] Expands to 50 host entries
See also  Git Squash Commits: Syntax, Flags, Examples & Troubleshooting

Advanced Implementation & Parameters

Group inheritance (parent/child)

Groups can contain other groups using the :children suffix:

# INI
[usa:children]
east
west

[east]
nyc.example.com
[west]
la.example.com

Host variables in YAML

# inventory.yml
all:
  children:
    database:
      hosts:
        db-prod:
          ansible_host: 192.168.1.100
          ansible_user: dba
          postgres_version: 15

Dynamic inventory via script

Replace static file with executable script returning JSON. Ansible runs it on each playbook invocation.

# ec2.py (returns JSON)
ansible-playbook -i ec2.py deploy.yml

Ignored files in inventory directories

Ansible skips files matching INVENTORY_IGNORE_PATTERNS (default: ~, .orig, .bak, .ini in some versions). Set via ansible.cfg:

[defaults]
INVENTORY_IGNORE_PATTERNS = *.bak ~* .swp

Error Resolution & Troubleshooting

Error Code / Signal Root Cause Remediation Command
UNREACHABLE Host not reachable on SSH port (wrong IP/port/firewall) ansible all -i inventory -m ping -v and check ansible_host / ansible_port
PERMISSION DENIED SSH user does not exist or wrong key Verify ansible_user and ansible_ssh_private_key_file in inventory variables
Invalid inventory: could not parse Syntax error in INI/YAML (e.g., missing colon, unclosed bracket) ansible-inventory --list -i inventory 2>&1 for parser details; test with yamllint
Host list is empty Group definition missing hosts, or pattern mismatch ansible-inventory --graph -i inventory to visualize groups
No inventory was supplied -i not provided and no default inventory found Set inventory=./hosts in ansible.cfg or use ANSIBLE_INVENTORY env var

Production-Grade Implementation

  • Use version control – Store inventory files in Git; never commit plain-text passwords (use ansible-vault).
  • Separate by environment – Maintain prod.yml, stage.yml, dev.yml with distinct vault keys.
  • Prefer YAML over INI – YAML allows comments, nested structures, and easier validation with linters.
  • Leverage dynamic inventory – For cloud (AWS EC2, Azure VMs), use official dynamic inventory scripts to avoid stale host lists.
  • Set ansible.cfg to point to inventory directory – Avoid repeating -i across all commands.
  • Validate inventory in CI – Run ansible-inventory --list and check exit code before playbook execution.
  • Limit scope with --limit – Target subsets during rollouts: ansible-playbook -i prod.yml --limit webservers[0:5].

Performance Considerations and Tuning

Performance of inventory file parsing in Ansible is affected by file size, variable complexity, and the number of host groups. Key tuning levers are exposed via configuration variables that control how Ansible reads and resolves the inventory.

  • INVENTORY_IGNORE_EXTS and INVENTORY_IGNORE_PATTERNS — Setting these in ansible.cfg or via environment variables prevents Ansible from scanning irrelevant files (e.g., .bak, .swp). This reduces file I/O and speeds up startup, especially in shared repositories.
  • DEFAULT_HASH_BEHAVIOUR — When set to merge, variable overrides from multiple inventory sources are merged instead of replaced. This reduces the overhead of deep copy operations at the cost of slightly more memory. For large inventories, replace (faster) may be preferable if merge logic is not required.
  • ANSIBLE_INVENTORY environment variable — Use a single, consolidated inventory file or a directory with only necessary files. Avoid globbing patterns that match many unused files.
  • File size reduction — Use range syntax (e.g., www[01:50].example.com) instead of listing individual hosts. This directly reduces parsing time and memory consumption.
# Inspect current inventory configuration values
ansible-config dump | grep -E 'INVENTORY|DEFAULT_HASH_BEHAVIOUR'
# Expected output (values may vary):
# DEFAULT_HASH_BEHAVIOUR(...) = replace
# INVENTORY_IGNORE_EXTS(...) = ['~', '.orig', '.bak', '.ini', '.cfg', '.retry', '.pyc', '.pyo']
# ANSIBLE_INVENTORY(...) = /etc/ansible/hosts

For large-scale deployments, consult the Ansible Configuration Settings documentation (vendor docs) to adjust forks (parallelism) and timeout values, though these do not directly alter inventory file parsing. The knobs above are the primary means to tune the hosts file layer itself.

See also  Define PBX: CLI Cheat Sheet with Verified Cisco & Asterisk

Frequently Asked Questions

What is the difference between INI and YAML inventory formats in the Ansible hosts file?

Answer: INI uses brackets for groups and key=value for variables; YAML uses structured dictionary/array syntax for hierarchy and complex data.

INI is simpler for flat groups but fails with nested variables. YAML supports richer structures (lists, dictionaries) for advanced inventory. Always use YAML if your inventory requires dynamic groups, group-of-groups, or variable inheritance beyond basic key-value. Convert INI to YAML with

ansible-inventory -i inventory.ini --list --export

and redirect to a .yml file.

When should I use the `ansible-inventory –list` subcommand on my hosts file?

Answer: Use it to validate inventory parsing, expose all variable values, and debug group membership before running a playbook.

This subcommand dumps the fully resolved inventory as JSON, showing inherited variables, group hierarchies, and ungrouped hosts. Essential when troubleshooting dynamic inventory or complex group variables (prefixed with group_vars or host_vars). Example:

ansible-inventory -i production.ini --list --yaml

outputs YAML for readability.

How do I fix the “could not match supplied host pattern” error in an Ansible hosts file?

Answer: Verify the hostname or wildcard pattern exactly matches inventory entries; use ansible-inventory --graph to confirm groups and hosts.

Common causes: case mismatch, trailing whitespace, or pattern before host definition. Enable --verbose with ansible-inventory --graph to visualize groups. Example:

ansible all -i hosts --list-hosts | grep <pattern>

Check for invisible characters in file using cat -A inventory.ini.

What is the fastest way to validate and test your Ansible hosts file before running a playbook?

Answer: Use ansible-inventory --list --graph with a single command to catch syntax errors and view all groups/hosts.

A rapid two-step validation:

ansible-inventory -i inventory.yml --list --export > /dev/null && echo "Valid syntax"

then

ansible-inventory -i inventory.yml --graph --yaml

to verify group structure. For ad-hoc host connectivity: ansible webservers -i inventory -m ping --limit host1.