Inventory Management: Configuring Hosts
Understanding Ansible Inventory
The Ansible inventory is a file or a dynamic source that defines the hosts or systems that Ansible will manage. The inventory can be a simple text file, a script that generates the inventory dynamically, or a cloud-based inventory service.
Static Inventory
The simplest form of an Ansible inventory is a static text file, typically named hosts
or inventory.ini
. This file contains a list of hosts, grouped by their function or environment.
[webservers]
web01.example.com
web02.example.com
[databases]
db01.example.com
db02.example.com
In this example, the inventory defines two groups: "webservers" and "databases", each containing two hosts.
Dynamic Inventory
While static inventories are useful for small-scale deployments, Ansible also supports dynamic inventories, which can be generated by scripts or cloud-based inventory services. This is particularly useful for managing infrastructure in cloud environments, where the number and configuration of hosts can change frequently.
Here's an example of a simple Python script that generates a dynamic inventory:
#!/usr/bin/env python
import json
inventory = {
"webservers": {
"hosts": [
"web01.example.com",
"web02.example.com"
]
},
"databases": {
"hosts": [
"db01.example.com",
"db02.example.com"
]
}
}
print(json.dumps(inventory))
Inventory Variables and Groups
Ansible inventory supports the use of variables, which can be defined at the host or group level. These variables can be used within your Ansible Playbooks to customize the behavior of your automation tasks.
[webservers]
web01.example.com ansible_user=ubuntu ansible_ssh_private_key_file=/path/to/key.pem
web02.example.com ansible_user=centos ansible_ssh_private_key_file=/path/to/key.pem
[databases]
db01.example.com ansible_user=ec2-user
db02.example.com ansible_user=ec2-user
In this example, the inventory defines the ansible_user
and ansible_ssh_private_key_file
variables for the "webservers" group, and the ansible_user
variable for the "databases" group.
By understanding and properly configuring your Ansible inventory, you can ensure that your automation tasks are executed on the correct hosts and with the appropriate settings.