Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Inventories - Ansible

What is an Inventory?

In Ansible, an inventory is a list of managed nodes, or hosts, that are defined in a file. It can be a simple text file with a list of IP addresses or hostnames, or a more complex structure that includes variables and groups. Inventories tell Ansible what machines to work with and organize these machines into groups for more efficient management.

Basic Structure of an Inventory File

A basic inventory file in Ansible can be as simple as a list of hostnames or IP addresses. Here is an example of the simplest form of an inventory:

192.168.1.10
192.168.1.11
server1.example.com
server2.example.com

In this example, Ansible will manage four hosts with the specified IP addresses and domain names.

Grouping Hosts

Grouping hosts in an inventory file allows you to apply different roles and tasks to different sets of hosts. Here is an example of an inventory file with groups:

[webservers]
192.168.1.10
192.168.1.11

[dbservers]
server1.example.com
server2.example.com

In this example, we have two groups: webservers and dbservers. The webservers group contains two IP addresses, while the dbservers group contains two domain names.

Adding Variables to Groups and Hosts

Ansible allows you to associate variables with groups and individual hosts. These variables can be used to customize the behavior of your playbooks. Here is an example:

[webservers]
192.168.1.10 ansible_user=admin ansible_ssh_private_key_file=/path/to/key1
192.168.1.11 ansible_user=admin ansible_ssh_private_key_file=/path/to/key2

[dbservers]
server1.example.com ansible_user=root
server2.example.com ansible_user=root

In this example, each host in the webservers group has specific SSH user and key file variables associated with it. The dbservers group has a different SSH user variable.

Dynamic Inventories

In addition to static inventory files, Ansible supports dynamic inventories, which can pull information from external sources such as cloud providers, LDAP, and more. This allows for more flexible and scalable infrastructure management. Here is a simple example of how you might configure a dynamic inventory with a script:

#!/usr/bin/env python
import json

def get_inventory():
    inventory = {
        "webservers": {"hosts": ["192.168.1.10", "192.168.1.11"]},
        "dbservers": {"hosts": ["server1.example.com", "server2.example.com"]}
    }
    print(json.dumps(inventory))

if __name__ == "__main__":
    get_inventory()

This Python script outputs a JSON object that Ansible can use as a dynamic inventory source.

Conclusion

Inventories are a core component of Ansible, allowing you to define and manage the hosts and groups that your automation tasks will operate on. Whether using static files or dynamic sources, Ansible inventories provide the flexibility and scalability needed for effective infrastructure automation.