Sobes.tech
Middle

What is a dynamic inventory?

sobes.tech AI

Answer from AI

Dynamic inventory is a list of hosts or objects managed by an automation platform (e.g., Ansible), which is generated in real-time based on data from external sources. Unlike static inventory, where the list of hosts is fixed in a file, dynamic inventory automatically updates with each request, reflecting the current state of the infrastructure.

Data sources can include:

  • Cloud providers (AWS EC2, Azure VMs, Google Cloud Engine)
  • Virtualization systems (VMware vSphere, OpenStack)
  • Monitoring and discovery systems (CMDB, Zabbix)
  • Custom scripts

Advantages of dynamic inventory:

  • Relevance: Always reflects the current state of the infrastructure, including added or removed hosts.
  • Scalability: Simplifies management of large and dynamically changing environments.
  • Automation: Integrates with orchestration and automation tools.
  • Flexibility: Allows grouping hosts based on various attributes (tags, region, OS type).

Example of usage in Ansible:

#!/usr/bin/env python
# This is a simplified example of a dynamic inventory script for Ansible
# based on reading test data from a JSON file.
# In a real scenario, this script would query a cloud API or CMDB.

import json
import os

def main():
    # Assume test data is stored in 'inventory_data.json'
    inventory_file = 'inventory_data.json'

    if not os.path.exists(inventory_file):
        # Return empty structures if file doesn't exist
        inventory = {"_meta": {"hostvars": {}}}
        print(json.dumps(inventory))
        return

    try:
        with open(inventory_file, 'r') as f:
            inventory_data = json.load(f)

        # Transform data into Ansible dynamic inventory format
        inventory = {}
        inventory["_meta"] = {"hostvars": {}}

        for group, hosts_info in inventory_data.items():
            inventory[group] = {"hosts": []}
            for host_info in hosts_info:
                hostname = host_info["hostname"]
                inventory[group]["hosts"].append(hostname)
                # Add host-specific variables
                inventory["_meta"]["hostvars"][hostname] = host_info.get("vars", {})

        print(json.dumps(inventory))

    except Exception as e:
        # Handle errors appropriately in a real script
        print(f"Error processing inventory data: {e}")
        inventory = {"_meta": {"hostvars": {}}}
        print(json.dumps(inventory))

if __name__ == '__main__':
    main()

Example content of inventory_data.json for the above script:

{
  "webservers": [
    {
      "hostname": "webserver1.example.com",
      "vars": {
        "http_port": 80,
        "max_clients": 200
      }
    },
    {
      "hostname": "webserver2.example.com",
      "vars": {
        "http_port": 8080,
        "max_clients": 500
      }
    }
  ],
  "databases": [
    {
      "hostname": "db1.example.com",
      "vars": {
        "db_type": "postgresql"
      }
    }
  ]
}

Dynamic inventory is critical for effective management of modern, dynamic infrastructures.