Skip to main content

Ansible Inventory

What is an Ansible Inventory?

In Ansible, the Inventory is a configuration file where you define the hosts and groups of hosts upon which you want your Ansible commands, modules, and playbooks to operate. It's the foundation for Ansible to establish connections with your nodes and start the automation tasks.

By default, Ansible looks for the Inventory file at /etc/ansible/hosts.

Static and Dynamic Inventories

There are two types of inventories: static and dynamic.

  • Static Inventory: This is the most common and simple form of inventory. It's just a text file with a list of hosts.

  • Dynamic Inventory: This type of inventory is used for managing a large number of hosts that are dynamically changing. Instead of a static text file, you use a script or a program that fetches your hosts list from a cloud provider or a CMDB.

Creating a Static Inventory

You can create a simple static inventory by defining your hosts and groups of hosts in an INI-like syntax.

[webservers]
webserver1.example.com
webserver2.example.com

[dbservers]
dbserver1.example.com
dbserver2.example.com

In this example, webservers and dbservers are groups, and the lines beneath them are the hosts in those groups.

Creating a Dynamic Inventory

Creating a dynamic inventory involves writing a script or program that can retrieve your hosts list from a source. The script should output a JSON formatted dictionary when invoked with the --list option.

For example, here's a simple Python script that generates a dynamic inventory:

#!/usr/bin/env python

import json

try:
print(json.dumps({
"dbservers": {
"hosts": ["dbserver1.example.com", "dbserver2.example.com"],
"vars": {}
},
"webservers": {
"hosts": ["webserver1.example.com", "webserver2.example.com"],
"vars": {}
}
}))
except Exception as e:
print(e)

You should adapt this script to fetch the hosts list from your actual source.

Group Variables

In an inventory file, you can also define variables that will be used in your playbooks. These variables are assigned to a particular group and all hosts in the group will have access to these variables.

[webservers]
webserver1.example.com
webserver2.example.com

[webservers:vars]
http_port=80
max_clients=200

In this example, http_port and max_clients are variables assigned to the webservers group.

Conclusion

The Ansible inventory is a powerful tool in your Ansible toolkit. It allows you to organize your hosts and define variables for them in a simple and easy-to-understand format. Whether you choose to use a static or dynamic inventory depends on your specific use case and how often your hosts list changes.