How to create a dynamic inventory script?

QuestionsQuestions8 SkillsProAnsible Ad-Hoc CommandsOct, 08 2025
0109

To create a dynamic inventory script for Ansible, you need to write a script that outputs the inventory in JSON format. This script can be written in any programming language, but Python is commonly used due to its simplicity and the availability of libraries.

Steps to Create a Dynamic Inventory Script:

  1. Choose a Programming Language: You can use Python, Bash, or any language that can output JSON.

  2. Output JSON Format: The script must output the inventory in a specific JSON format that Ansible understands.

  3. Make the Script Executable: Ensure the script has executable permissions.

Example: Python Dynamic Inventory Script

Here’s a simple example of a Python script that generates a dynamic inventory:

#!/usr/bin/env python

import json

def main():
    inventory = {
        "webservers": {
            "hosts": ["web1.example.com", "web2.example.com"],
            "vars": {
                "http_port": 80,
                "max_clients": 200
            }
        },
        "databases": {
            "hosts": ["db1.example.com"],
            "vars": {
                "db_port": 5432
            }
        },
        "_meta": {
            "hostvars": {
                "web1.example.com": {
                    "ansible_host": "192.168.1.10"
                },
                "web2.example.com": {
                    "ansible_host": "192.168.1.11"
                },
                "db1.example.com": {
                    "ansible_host": "192.168.1.20"
                }
            }
        }
    }

    print(json.dumps(inventory))

if __name__ == "__main__":
    main()

Steps to Use the Script:

  1. Save the Script: Save the above script to a file, e.g., dynamic_inventory.py.

  2. Make it Executable:

    chmod +x dynamic_inventory.py
  3. Run Ansible with the Script:

    ansible -i dynamic_inventory.py all -m ping

Notes:

  • The script should return a JSON object with groups of hosts and their variables.
  • The _meta section is optional but allows you to define host-specific variables.
  • You can enhance the script to fetch data from cloud providers or other sources as needed.

This basic structure can be expanded based on your requirements, such as querying a database or an API to get the list of hosts dynamically.

0 Comments

no data
Be the first to share your comment!