Ansible Inventory Basics
What is Ansible Inventory?
Ansible Inventory is a file or set of files that defines the hosts (servers, network devices, etc.) that Ansible can manage. It provides Ansible with information about the target systems, such as their hostnames, IP addresses, and other metadata.
Inventory File Structure
The Ansible Inventory file follows a specific format. It can be in various formats, such as INI, YAML, or JSON. Here's an example of an INI-style Ansible Inventory file:
[webservers]
web01 ansible_host=192.168.1.100
web02 ansible_host=192.168.1.101
[databases]
db01 ansible_host=192.168.1.200
db02 ansible_host=192.168.1.201
[all:vars]
ansible_user=ubuntu
ansible_ssh_private_key_file=/path/to/your/ssh/key.pem
In this example, the Inventory file defines two groups: webservers
and databases
. Each group contains two hosts, with their respective IP addresses or hostnames. The [all:vars]
section defines global variables, such as the SSH user and the private key file to be used for all hosts.
Inventory Plugins
Ansible supports various Inventory Plugins, which allow you to use different sources for your Inventory, such as cloud providers, configuration management tools, or even dynamic scripts. This provides flexibility in managing your infrastructure.
For example, you can use the aws_ec2
Inventory Plugin to automatically discover and manage your AWS EC2 instances:
plugin: aws_ec2
regions:
- us-east-1
- us-west-2
filters:
tag:Environment: production
This Inventory Plugin will automatically discover and include all EC2 instances with the Environment=production
tag in your Ansible Inventory.
Dynamic Inventory
Ansible also supports Dynamic Inventory, where the Inventory is generated at runtime, rather than being statically defined in a file. This is useful when your infrastructure is constantly changing, or when you need to fetch information from external sources.
You can create a Dynamic Inventory script in any language (e.g., Python, Bash, etc.) that outputs a valid JSON format. Ansible will then use this script to populate the Inventory.
By understanding the basics of Ansible Inventory, you can effectively manage your infrastructure and ensure that Ansible can communicate with the correct hosts.