Ansible Tutorial · Getting Started · Lesson 3 of 20
Ansible Inventory
List and group managed hosts in inventory files.
What is an inventory?
An inventory tells Ansible which machines to manage. The simplest form is a text file with one hostname per line.
INI format
The traditional format uses INI-style sections for groups:
# inventory.ini
[webservers]
web-1.example.com
web-2.example.com
[databases]
db-1.example.com ansible_port=5432
[all:vars]
ansible_user=deploy
ansible_python_interpreter=/usr/bin/python3
YAML format
YAML inventories are more expressive and support nested data:
# inventory.yml
all:
vars:
ansible_user: deploy
ansible_python_interpreter: /usr/bin/python3
children:
webservers:
hosts:
web-1.example.com:
web-2.example.com:
databases:
hosts:
db-1.example.com:
ansible_port: 5432
Groups and children
Every host automatically belongs to two groups: all and ungrouped (if not in any explicit group).
Groups can contain other groups with children:
production:
children:
webservers:
databases:
Host and group variables
Variables set at the host level override group variables. You can also store them in separate files:
inventory/
├── hosts.yml
├── group_vars/
│ ├── all.yml # applies to every host
│ ├── webservers.yml # applies to webservers group
│ └── production.yml
└── host_vars/
└── db-1.example.com.yml
Inspect the inventory
ansible-inventory -i inventory.yml --list # JSON output
ansible-inventory -i inventory.yml --graph # tree view
Patterns for targeting hosts
| Pattern | Meaning |
|---|---|
all |
Every host |
webservers |
Hosts in the webservers group |
web-* |
Hosts matching the glob |
webservers:&production |
Intersection of two groups |
webservers:!web-2.example.com |
Exclude a host |
cat > /tmp/inventory.yml << 'EOF'
all:
children:
webservers:
hosts:
web-1.example.com:
web-2.example.com:
databases:
hosts:
db-1.example.com:
EOF
ansible-inventory -i /tmp/inventory.yml --graph
Output
@all: |--@databases: | |--db-1.example.com |--@ungrouped: |--@webservers: | |--web-1.example.com | |--web-2.example.com
Run this on your computer — see “Get Started” for setup.
ansible-inventory -i /tmp/inventory.yml --list --yaml
Output
all:
children:
databases:
hosts:
db-1.example.com: {}
ungrouped: {}
webservers:
hosts:
web-1.example.com: {}
web-2.example.com: {}Run this on your computer — see “Get Started” for setup.
Test yourself
Which two default groups does every host belong to?
all and ungroupeddefault and globalhosts and groupsmain and other
Show answer
Answer: all and ungrouped
Every host is in 'all'. Hosts not assigned to any explicit group are also in 'ungrouped'.