Dynamic Inventory in Ansible
Introduction
Dynamic inventory in Ansible refers to the ability to generate inventory on-the-fly using scripts or cloud services. This allows Ansible to adapt to changing environments, such as cloud instances, without the need for static inventory files.
Key Concepts
- Dynamic Inventory: Automatically generated host list based on external data sources.
- Inventory Scripts: Scripts that output JSON format to provide host information.
- Cloud Providers: Many cloud services (AWS, GCP, Azure) offer APIs that can be queried for inventory.
Dynamic Inventory Scripts
Dynamic inventory scripts can be written in any language, but they must output data in JSON format. Below is a simple example of a Python script that returns inventory.
#!/usr/bin/env python
import json
def main():
inventory = {
"web": {
"hosts": ["web1.example.com", "web2.example.com"],
"vars": {
"http_port": 80
}
},
"_meta": {
"hostvars": {
"web1.example.com": {
"ansible_host": "192.168.1.1"
},
"web2.example.com": {
"ansible_host": "192.168.1.2"
}
}
}
}
print(json.dumps(inventory))
if __name__ == "__main__":
main()
Make sure to give execute permissions to the script:
chmod +x dynamic_inventory.py
Example Usage
To use the dynamic inventory script in your Ansible playbook, specify the script in your inventory file:
ansible-inventory -i dynamic_inventory.py --list
Best Practices
- Keep your scripts simple and focused on returning host information.
- Test your scripts thoroughly to ensure correct output.
- Use caching to speed up repeated calls to the inventory script.
- Secure your scripts if they interact with sensitive data.
FAQ
What is a dynamic inventory?
A dynamic inventory is an inventory that is generated automatically based on external data sources, allowing for more flexibility in managing hosts.
How do I use a dynamic inventory script?
Simply write a script that outputs JSON and use it with the -i option in Ansible commands.
Can I use cloud provider APIs for dynamic inventory?
Yes, many cloud providers offer APIs that can be queried to get instance information and automatically populate your inventory.