ANSIBLE INVENTORY FILES

Introduction

Ansible Inventory is a centralized catalog that manages all hosts, servers, and devices in your IT infrastructure. It provides Ansible the information needed to connect to managed nodes, such as IP addresses, domain names, and authentication details (SSH keys, credentials, etc.).

1. Default Inventory and Groups

Tip: Even without defining groups, all and ungrouped always exist.

2. Inventory File Formats

a) INI Format

Simple, text-based structure using brackets [group_name]. Ideal for small setups or flat lists of servers.

[web]
shan_web=192.168.1.100

b) YAML Format

Structured and better for complex environments. Supports nested groups and host variables.

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

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

3. Custom Inventory Files

You can create your own inventory files and call them with the -i flag.

ansible -i shan.ini -m ping web

Running a playbook with multiple inventories:

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

4. Key Principles for Organizing Inventory

  1. Grouping: Organize hosts by function (e.g., web, db, api) or environment (e.g., stage, prod)
  2. Variables: Assign connection parameters like ansible_user, ansible_port to hosts or groups
  3. Scalability: Use multiple inventory files for different environments while reusing the same playbooks

5. Parent-Child Grouping

[Api]
192.168.11.1

[Frontend]
192.168.11.2

[Backend]
192.168.11.3

[Webapp:children]
Frontend
Backend

6. Static vs Dynamic Inventory

Static Inventory

Dynamic Inventory

AWS Example using YAML Plugin:

plugin: amazon.aws.aws_ec2
region:
  - us-east-1

Compose to connect via public IP:

compose:
  ansible_host: public_ip_address

7. How Ansible Uses Inventory and Config

  1. Inventory file → Hosts & deployment targets
  2. Config file (ansible.cfg) → Connection details, module paths, default inventory locations
This ensures Ansible knows where to deploy and how to connect to hosts.