Ansible Inventory Files Static vs Dynamic

By Anurag Singh

Updated on Nov 18, 2024

Ansible Inventory Files Static vs Dynamic

In this tutorials we're Working with Ansible Inventory Files: Static vs Dynamic Inventory.

Working with Ansible Inventory Files: Static vs Dynamic Inventory

Introduction

Ansible is a powerful automation tool for configuration management, application deployment, and task automation. A critical component of Ansible's functionality is the inventory—a file that contains information about the systems you manage. This guide will cover two types of inventories:

  • Static Inventory
  • Dynamic Inventory

Additionally, we will explore how to work with cloud providers using inventory plugins and discuss best practices for managing large inventories.

What is an Inventory in Ansible?

An inventory in Ansible is a collection of hosts that are managed. It defines the machines and devices you’ll be interacting with. Hosts can be grouped, and variables can be assigned to both groups and individual hosts. Inventories are essential because they serve as the source for the ad-hoc commands and playbooks you execute in Ansible.

1. Static Inventory

A static inventory is a simple file (usually hosts or inventory) that contains a list of your managed hosts. This file can be in either INI, YAML, or JSON format.

Creating a Static Inventory File

1.1 INI Format

The INI format is the traditional format for Ansible inventory files. Here's an example:

# File: inventory.ini

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

[databases]
db1.example.com
db2.example.com

[all:vars]
ansible_user=admin
ansible_ssh_private_key_file=/path/to/private/key

In this example:

  • webservers and databases are groups containing specific hosts.
  • all:vars section is for global variables applied to all hosts in the inventory.

1.2 YAML Format

YAML is a more modern and human-readable format. Here's the same inventory in YAML:

# File: inventory.yaml

all:
  vars:
    ansible_user: admin
    ansible_ssh_private_key_file: /path/to/private/key

  children:
    webservers:
      hosts:
        webserver1.example.com:
        webserver2.example.com:
    
    databases:
      hosts:
        db1.example.com:
        db2.example.com:

1.3 JSON Format

For those who prefer JSON:

{
  "all": {
    "vars": {
      "ansible_user": "admin",
      "ansible_ssh_private_key_file": "/path/to/private/key"
    },
    "children": {
      "webservers": {
        "hosts": {
          "webserver1.example.com": {},
          "webserver2.example.com": {}
        }
      },
      "databases": {
        "hosts": {
          "db1.example.com": {},
          "db2.example.com": {}
        }
      }
    }
  }
}

Using a Static Inventory File

To use the inventory, specify the file with the -i flag when running an Ansible command:

ansible -i inventory.ini all -m ping
ansible-playbook -i inventory.yaml site.yml

2. Dynamic Inventory

A dynamic inventory is generated on the fly using external sources like cloud providers (AWS, Azure), container orchestration systems (Kubernetes), or custom scripts. Dynamic inventories are helpful when dealing with rapidly changing environments.

2.1 What is a Dynamic Inventory?

Instead of manually maintaining a static inventory file, a dynamic inventory uses a script or plugin to pull information about your infrastructure from an external source.

2.2 Setting Up Dynamic Inventory Scripts

Ansible comes with several built-in inventory plugins for cloud providers. Here’s how you can set up dynamic inventories for AWS and Azure.

2.3 Using AWS Dynamic Inventory

To use AWS as a dynamic inventory source:

Install the AWS Inventory Plugin:

Ensure that the boto3 and botocore Python libraries are installed:

pip install boto3 botocore

Configure AWS Credentials:

Make sure you have configured AWS credentials, typically in ~/.aws/credentials.

Create an Inventory File:

Create a aws_ec2.yaml file:

plugin: aws_ec2
regions:
  - us-east-1
filters:
  tag:Environment: production
keyed_groups:
  - key: tags.Name
    prefix: aws_tag_name_
hostnames:
  - tag:Name

Run Ansible Commands:

Use the aws_ec2.yaml as the inventory:

ansible-inventory -i aws_ec2.yaml --graph
ansible -i aws_ec2.yaml all -m ping

2.4 Using Azure Dynamic Inventory

Install the Azure Collection:

ansible-galaxy collection install azure.azcollection
pip install azure-cli

Create Azure Inventory File:

Create a file named azure_rm.yaml:

plugin: azure.azcollection.azure_rm
include_vm_resource_groups:
  - MyResourceGroup
auth_source: auto

Run Ansible Commands:

Use azure_rm.yaml as the inventory:
ansible-inventory -i azure_rm.yaml --list
ansible -i azure_rm.yaml all -m ping

3. Best Practices for Managing Large Inventories

When dealing with a large-scale infrastructure, inventory management can become challenging. Here are some best practices:

3.1 Use Groups and Variables Wisely

Organize your inventory into groups and subgroups to avoid repetition. Utilize group variables to minimize the redundancy of host-specific configurations.

3.2 Implement Dynamic Inventory Where Possible

Use dynamic inventories for environments that change frequently. This reduces the overhead of manually updating static files and decreases the risk of human error.

3.3 Use Host Variables and Group Variables

Separate variables into host-specific files (host_vars) and group-specific files (group_vars). This enhances maintainability:

inventory/
  ├── group_vars/
  │   └── all.yaml
  ├── host_vars/
  │   └── host1.yaml
  └── inventory.yaml

3.4 Utilize Inventory Plugins

Leverage the built-in plugins for cloud providers to maintain a real-time inventory that reflects the current state of your infrastructure.

3.5 Use Inventory Scripts for Custom Environments

If your infrastructure isn’t on a standard cloud provider, consider writing custom Python or shell scripts for inventory generation. Ensure that the script outputs data in JSON format to be compatible with Ansible.

3.6 Keep Inventory Files Secure

Sensitive information like passwords, keys, and secrets should be handled securely. Use tools like ansible-vault to encrypt sensitive data.

ansible-vault encrypt inventory.yaml

3.7 Use Templates for Common Patterns

If multiple environments share similar configurations, use Jinja2 templates to generate inventory files dynamically.

Conclusion

Ansible inventory files are crucial for efficient infrastructure management. While static inventories are straightforward and easy to set up, dynamic inventories offer flexibility and scalability for cloud environments. Applying best practices ensures that your inventory management remains organized, secure, and effective even as your infrastructure grows.

By understanding how to manage static and dynamic inventories, you can choose the best approach for your environment and keep your Ansible workflow efficient.

This guide provides a deep dive into using Ansible inventory files, catering to both beginners and advanced users. It includes practical examples and aligns with the latest tools and techniques for managing infrastructure using Ansible.

Checkout our dedicated servers India, Instant KVM VPS, and Web Hosting India