4. inventory files

Ansible Inventory

Ansible inventory is a centralized catalog used to manage hosts, servers, and devices within an IT infrastructure. It provides Ansible with the necessary data to connect to managed nodes, including IP addresses, domain names, and authentication details such as SSH keys or credentials.


Default Groups and Locations

Ansible looks for a default inventory file at /etc/ansible/hosts. Regardless of your configuration, Ansible automatically creates two internal groups:


Inventory Formats

INI Format

The INI format is a simple, text-based structure using brackets to define groups. It is ideal for smaller setups or flat lists of servers.

Example:

[web]
shan_web=192.168.1.100
[web]
shan_web=192.168.1.100

In this example:


YAML Format

YAML is more structured and better suited for complex environments. It supports nested groups and rich variable definitions.

Example:

webservers:
  hosts:
    web1.example.com:
    web2.example.com:

databases:
  hosts:
    db1.example.com:
      ansible_user: myuser
webservers:
  hosts:
    web1.example.com:
    web2.example.com:

databases:
  hosts:
    db1.example.com:
      ansible_user: myuser

Custom Inventory Management

You can create custom inventory files, such as shan.ini, and call them directly in your commands using the -i flag.

Testing connectivity with a custom inventory

ansible -i shan.ini -m ping web
ansible -i shan.ini -m ping web

Running a playbook against multiple inventory files

ansible-playbook logs_collector.yml -i development.ini -i production.ini
ansible-playbook logs_collector.yml -i development.ini -i production.ini

Key Principles for Inventory Organization