English translation
14. Using Dynamic Inventory in Ansible
AI Article Decision Snapshot
Turn the lesson into workflow, model, budget, and security checks before choosing tools.
Use this quick snapshot before leaving the article. It keeps the next search tied to practical AI software, model/API, cost, privacy, and implementation questions.
Workflow fit
Identify the real job behind the article: coding, research, document review, support, analytics, content, or internal automation.
Model or tool decision
Decide whether the next step is a software shortlist, an AI tool comparison, an API platform choice, or a model benchmark.
Budget and usage signal
Estimate seats, API calls, prompt volume, retries, review time, and fallback work before assuming the workflow is cheap.
Security and privacy review
Check whether source code, customer data, private documents, prompts, logs, or embeddings will enter the AI workflow.
In the previous article, we explored basic Inventory configuration methods, including how to define host information using a static hosts file. In this tutorial, we’ll dive deeper into Ansible’s dynamic Inventory functionality—which automatically generates host lists from cloud services, external databases, or other data sources. Dynamic Inventory offers exceptional flexibility, especially when managing infrastructure that changes frequently.
Overview of Dynamic Inventory
Dynamic Inventory is a host list generated by Ansible at runtime from external data sources. This means Ansible can fetch up-to-date host information each time a task runs—for example, by calling the AWS EC2 API, Google Compute Engine (GCE) API, or any other RESTful API.
Common use cases for dynamic Inventory include:
- Automatically discovering new instances in cloud environments
- Retrieving host information from a Configuration Management Database (CMDB)
- Integrating with container orchestration platforms such as Kubernetes
Configuring Dynamic Inventory
1. Creating a Dynamic Inventory Script
First, you need to write a script that outputs a JSON-formatted host list. Below is a simple example of a dynamic Inventory script returning two host groups:
#!/usr/bin/env python
import json
def get_inventory():
inventory = {
"web": {
"hosts": ["web1.example.com", "web2.example.com"],
"vars": {
"http_port": 80,
},
},
"db": {
"hosts": ["db.example.com"],
"vars": {
"db_port": 5432,
},
},
}
return inventory
if __name__ == "__main__":
print(json.dumps(get_inventory()))
Save the above code as dynamic_inventory.py and make it executable:
chmod +x dynamic_inventory.py
2. Configuring Ansible to Use the Dynamic Inventory Script
Next, instruct Ansible to use your dynamic Inventory script—by updating the ansible.cfg file:
[defaults]
inventory = /path/to/dynamic_inventory.py
Be sure to replace /path/to/dynamic_inventory.py with the actual path to your script.
3. Testing the Dynamic Inventory
Run the following command in your terminal to verify that the dynamic Inventory works correctly:
ansible-inventory --list
You should see the host list output in JSON format.
4. Using the Dynamic Inventory
Once configured, you can use the dynamic Inventory just like a static one. For example, run the following command to ping all hosts:
ansible all -m ping
Real-World Example: Dynamic Inventory with AWS EC2
Suppose you’re running a fleet of EC2 instances on AWS and want to manage them automatically using dynamic Inventory. You can leverage the boto3 library to fetch instance metadata. Here's an example script:
#!/usr/bin/env python
import json
import boto3
def get_inventory():
ec2 = boto3.resource('ec2')
instances = ec2.instances.filter(Filters=[{'Name': 'instance-state-name', 'Values': ['running']}])
inventory = {
'all': {
'hosts': [],
}
}
for instance in instances:
inventory['all']['hosts'].append(instance.public_ip_address)
return inventory
if __name__ == "__main__":
print(json.dumps(get_inventory()))
This script uses the boto3 client to connect to AWS and retrieve the public IP addresses of all running EC2 instances. When you run ansible-inventory --list, those IPs will appear dynamically in the output.
Summary
In this article, we thoroughly examined how to use dynamic Inventory to flexibly manage Ansible host definitions. By writing simple Python scripts, you can significantly simplify infrastructure management—especially in dynamic cloud environments. Whether integrating with AWS, GCE, or other services, dynamic Inventory enables effortless discovery and management of cloud resources, greatly enhancing automation efficiency and operational convenience.
In the next article, we’ll explore grouping hosts and configuring host variables within Inventory—stay tuned!
Apply This Lesson
Turn this article into AI software, model, API, and security decisions.
English Article FAQ
Use this article as evidence before choosing AI tools
How should I use this AI Tutorials article?
Use it as the implementation or learning layer, then connect the idea to AI software buyer guides, tool comparisons, benchmarks, API choices, and security checks before making a production decision.
Is this English article different from the Chinese original?
The English edition is localized for global AI readers while preserving the original diagrams, screenshots, prompts, code examples, and source context from the Chinese article.
What should I read after 14. Using Dynamic Inventory in Ansible?
Continue with AI Software Buyer Guides, AI Tools Workbench, Best AI Coding Agents, AI Model Benchmarks, OpenAI vs Anthropic API, or LLM Security Tools depending on the decision you need to make.
Can this article alone choose an AI product or model?
No. Treat the article as evidence and context, then validate fit with pricing, privacy requirements, integration effort, benchmark results, workflow tests, and fallback planning.
Continue