## Dynamic Inventory Use dynamic inventory to fetch host information at runtime: ### Example Usage ```yaml - name: Fetch hosts from external source ansible.builtin.get_url: url: "https://api.example.com/hosts" dest: "hosts.json" register: inventory_data - name: Display inventory hosts debug: var: inventory_data.content # Example dynamic inventory script (hosts.py): # import json # print(json.dumps({"hosts": ["web1", "web2"], "groups": {"webservers": ["web1", "web2"]}})) ``` ### Common Inventory Sources 1. **EC2 Inventory**: - Uses AWS API to list instances - Parameters: `aws_access_key_id`, `aws_secret_access_key`, `region` - Example: ```bash ansible-inventory --list --inventory=ec2.py ``` 2. **OpenStack Inventory**: - Connects to OpenStack neutron API - Parameters: `auth_url`, `project_name`, `username`, `password` - Example: ```bash ansible-inventory --list --inventory=openstack.py ``` 3. **Custom Scripts**: - Write Python scripts to generate inventory - Must output JSON in this format: ```json { "hosts": ["host1", "host2"], "groups": { "webservers": ["host1", "host2"] } } ``` ### Best Practices - Use `ansible-inventory --list` to verify inventory structure - Test dynamic inventory with `--check` flag - Store credentials securely using Ansible Vault - Combine with `--limit` to target specific hosts/groups ### Troubleshooting Use `--debug` flag to see inventory resolution process: ```bash ansible-playbook site.yml --limit="webservers" --debug ```