You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
The inventory is the foundation of Ansible automation --- it defines which hosts Ansible manages and how they are organised. Without an inventory, Ansible has no targets to act upon.
An inventory is a file (or script) that lists the managed nodes (hosts) and organises them into groups. Ansible reads the inventory to determine which hosts to target when running commands or playbooks.
The simplest inventory format is a static INI file:
# inventory
[webservers]
web1.example.com
web2.example.com
web3.example.com
[dbservers]
db1.example.com
db2.example.com
[loadbalancers]
lb1.example.com
The same inventory in YAML:
all:
children:
webservers:
hosts:
web1.example.com:
web2.example.com:
web3.example.com:
dbservers:
hosts:
db1.example.com:
db2.example.com:
loadbalancers:
hosts:
lb1.example.com:
Ansible automatically creates two default groups:
| Group | Contains |
|---|---|
| all | Every host in the inventory |
| ungrouped | Hosts not assigned to any explicit group |
You can assign variables directly to hosts in the inventory:
[webservers]
web1.example.com ansible_port=2222 http_port=8080
web2.example.com ansible_port=22 http_port=80
[dbservers]
db1.example.com ansible_user=dbadmin db_port=5432
| Variable | Description | Default |
|---|---|---|
ansible_host | The actual IP or hostname to connect to | The inventory hostname |
ansible_port | SSH port | 22 |
ansible_user | SSH user | The control node user |
ansible_ssh_private_key_file | Path to the SSH private key | Default SSH key |
ansible_become | Enable privilege escalation | false |
ansible_python_interpreter | Path to Python on the managed node | Auto-detected |
Assign variables to all hosts in a group:
[webservers]
web1.example.com
web2.example.com
[webservers:vars]
http_port=80
document_root=/var/www/html
ansible_user=deploy
Groups can contain other groups using the :children suffix:
[webservers]
web1.example.com
web2.example.com
[dbservers]
db1.example.com
[production:children]
webservers
dbservers
[production:vars]
env=production
Now targeting production will include all hosts from webservers and dbservers.
For better organisation, store variables in separate files:
inventory/
+-- hosts # Main inventory file
group_vars/
+-- all.yml # Variables for all hosts
+-- webservers.yml # Variables for webservers group
+-- dbservers.yml # Variables for dbservers group
host_vars/
+-- web1.example.com.yml # Variables for web1
+-- db1.example.com.yml # Variables for db1
http_port: 80
document_root: /var/www/html
max_clients: 256
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.