Inventory Configuration Techniques
Inventory File Structure and Syntax
Ansible supports multiple inventory configuration techniques to organize and manage infrastructure efficiently. Understanding these techniques enables precise host management and connection settings.
graph LR
A[Inventory Configuration] --> B[Static Inventory]
A --> C[Dynamic Inventory]
B --> D[INI Format]
B --> E[YAML Format]
C --> F[Script-based Inventory]
Static Inventory Configuration
INI-style Inventory
[webservers]
web1 ansible_host=192.168.1.100 ansible_user=ubuntu
web2 ansible_host=192.168.1.101 ansible_user=ubuntu
[databases]
db1 ansible_host=192.168.1.200 ansible_user=ubuntu
[production:children]
webservers
databases
YAML-style Inventory
all:
hosts:
web1:
ansible_host: 192.168.1.100
ansible_user: ubuntu
db1:
ansible_host: 192.168.1.200
ansible_user: ubuntu
children:
webservers:
hosts:
web1:
databases:
hosts:
db1:
Connection Parameters Configuration
Parameter |
Description |
Example |
ansible_host |
Target machine IP |
192.168.1.100 |
ansible_user |
SSH username |
ubuntu |
ansible_port |
Custom SSH port |
22 |
ansible_ssh_private_key_file |
SSH key path |
/home/user/.ssh/id_rsa |
Advanced Grouping Techniques
[datacenter:children]
webservers
databases
[datacenter:vars]
ansible_connection=ssh
environment=production
Dynamic Inventory Scripts
Dynamic inventory allows generating host lists programmatically:
#!/usr/bin/env python3
import json
def get_inventory():
return {
'webservers': {
'hosts': ['web1', 'web2'],
'vars': {'http_port': 80}
}
}
print(json.dumps(get_inventory(), indent=2))
This approach provides flexible, automated host management for complex infrastructure environments.