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:
-
Choose a Programming Language: You can use Python, Bash, or any language that can output JSON.
-
Output JSON Format: The script must output the inventory in a specific JSON format that Ansible understands.
-
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:
-
Save the Script: Save the above script to a file, e.g.,
dynamic_inventory.py. -
Make it Executable:
chmod +x dynamic_inventory.py -
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
_metasection 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.
