Ansible_inventory
Chapter 42: Ansible Inventory
Section titled “Chapter 42: Ansible Inventory”This chapter covers Ansible inventory configuration, groups, variables, and dynamic inventory.
Inventory Overview
Section titled “Inventory Overview”The inventory file defines the hosts and groups that Ansible will manage.
┌─────────────────────────────────────────────────────────────────────────────┐│ Ansible Inventory Concept │├─────────────────────────────────────────────────────────────────────────────┤│ ││ ┌─────────────────────────────────────────────────────────────────────┐ ││ │ Inventory File │ ││ │ │ ││ │ [webservers] # Group │ ││ │ web1.example.com # Host │ ││ │ web2.example.com │ ││ │ web3.example.com │ ││ │ │ ││ │ [databases] # Group │ ││ │ db1.example.com │ ││ │ db2.example.com │ ││ │ │ ││ │ [all:vars] # Group variables │ ││ │ ansible_user=ubuntu │ ││ │ │ ││ └─────────────────────────────────────────────────────────────────────┘ ││ ││ Inventory Formats: ││ ✓ INI (default) ││ ✓ YAML ││ ✓ Dynamic (script) ││ │└─────────────────────────────────────────────────────────────────────────────┘Static Inventory
Section titled “Static Inventory”INI Format
Section titled “INI Format”# Individual hostsweb1.example.comweb2.example.comdb1.example.com
# Define groups with [groupname][webservers]web1.example.comweb2.example.com
[databases]db1.example.comdb2.example.com
[appservers]app1.example.comapp2.example.com
# Nested groups (children)[production:children]webserversdatabasesappservers
# Group variables[webservers:vars]nginx_port=80max_connections=1000
[databases:vars]postgres_version=14
# Host-specific variables[webservers]web1.example.com ansible_host=192.168.1.10web2.example.com ansible_host=192.168.1.11
[all:vars]ansible_user=ubuntuansible_python_interpreter=/usr/bin/python3ansible_ssh_private_key_file=~/.ssh/id_rsaYAML Format
Section titled “YAML Format”---all: children: webservers: hosts: web1.example.com: nginx_port: 80 web2.example.com: nginx_port: 8080 databases: hosts: db1.example.com: postgres_version: 14 db2.example.com: postgres_version: 14 vars: ansible_user: ubuntu ansible_python_interpreter: /usr/bin/python3Inventory Patterns
Section titled “Inventory Patterns”┌─────────────────────────────────────────────────────────────────────────────┐│ Inventory Patterns │├─────────────────────────────────────────────────────────────────────────────┤│ ││ Pattern Examples: ││ ┌─────────────────────────────────────────────────────────────────────┐ ││ │ all All hosts │ ││ │ * All hosts (wildcard) │ ││ │ webservers All in webservers group │ ││ │ !webservers All except webservers │ ││ │ webservers:databases Union of groups │ ││ │ webservers[0] First host in group │ ││ │ webservers[0:2] First 3 hosts in group │ ││ │ *.example.com Regex pattern │ ││ │ ~web[0-9]+ Regex pattern │ ││ └─────────────────────────────────────────────────────────────────────┘ ││ ││ Using patterns: ││ ansible all -m ping ││ ansible "webservers:!prod" -m setup ││ ansible "web[1-3]" -i inventory.ini -a "hostname" ││ │└─────────────────────────────────────────────────────────────────────────────┘Host Variables
Section titled “Host Variables”# inventory.ini with host variables
[webservers]web1.example.com ansible_host=192.168.1.10 http_port=80web2.example.com ansible_host=192.168.1.11 http_port=8080web3.example.com
[databases]db1.example.com db_port=5432 max_connections=100
# Or define separately[webservers:vars]http_port=80
# Host-specific file# host_vars/web1.example.com---ansible_host: 192.168.1.10http_port: 80app_version: "2.0"Group Variables
Section titled “Group Variables”[production]prod-web1.example.comprod-web2.example.comprod-db1.example.com
[staging]stage-web1.example.comstage-db1.example.com
# Group variables[production:vars]environment=productionmax_memory=4096backup_enabled=true
[staging:vars]environment=stagingmax_memory=2048backup_enabled=false
# Common variables for all[all:vars]ansible_user=ubuntuansible_python_interpreter=/usr/bin/python3Group Variables Directory
Section titled “Group Variables Directory”# Directory structureinventory/├── inventory.ini├── group_vars/│ ├── all.yml│ ├── production.yml│ ├── staging.yml│ └── webservers.yml└── host_vars/ ├── web1.example.com.yml └── db1.example.com.yml---ansible_user: ubuntuansible_python_interpreter: /usr/bin/python3
# group_vars/production.yml---environment: productionmax_memory: 4096log_level: info
# group_vars/webservers.yml---nginx_version: latestphp_version: "8.1"Dynamic Inventory
Section titled “Dynamic Inventory”AWS EC2 Dynamic Inventory
Section titled “AWS EC2 Dynamic Inventory”# Install aws pluginansible-galaxy collection install amazon.aws
# Configure ec2.ini# plugin: aws_ec2[aws_credentials]profile = default
[ec2]regions = us-east-1, us-west-2
[ec2_tags]Environment = developmentplugin: amazon.aws.aws_ec2regions: - us-east-1filters: instance-state-name: runningkeyed_groups: - prefix: tag key: tags.Environment - prefix: instance_type key: instance_typehost_vars_prefix: aws_Using Dynamic Inventory
Section titled “Using Dynamic Inventory”# Point to dynamic inventory scriptansible-playbook -i inventory/aws_ec2.yml playbook.yml
# Or use ec2.py (older method)chmod +x inventory/ec2.pyansible-playbook -i inventory/ec2.py playbook.ymlCustom Dynamic Inventory Script
Section titled “Custom Dynamic Inventory Script”#!/usr/bin/env python3import jsonimport os
def get_inventory(): inventory = { "all": { "hosts": {}, "children": { "webservers": { "hosts": {} }, "databases": { "hosts": {} } } } }
# Fetch from your source (API, database, etc.) inventory["all"]["hosts"]["web1.example.com"] = { "ansible_host": "192.168.1.10" } inventory["all"]["hosts"]["db1.example.com"] = { "ansible_host": "192.168.2.10" }
return inventory
if __name__ == "__main__": print(json.dumps(get_inventory()))Inventory Best Practices
Section titled “Inventory Best Practices”┌─────────────────────────────────────────────────────────────────────────────┐│ Inventory Best Practices │├─────────────────────────────────────────────────────────────────────────────┤│ ││ 1. Organize with Groups ││ ✓ Use environment (prod, staging, dev) ││ ✓ Use function (webservers, databases) ││ ✓ Use location (us-east, eu-west) ││ ││ 2. Separate Variables ││ ✓ group_vars/ for group variables ││ ✓ host_vars/ for host-specific variables ││ ││ 3. Use Dynamic Inventory for Cloud ││ ✓ Auto-discover hosts ││ ✓ Keep inventory up-to-date ││ ✓ Tag-based grouping ││ ││ 4. Security ││ ✓ Never commit secrets to version control ││ ✓ Use ansible-vault for sensitive data ││ ✓ Use secrets management ││ │└─────────────────────────────────────────────────────────────────────────────┘Inventory Commands
Section titled “Inventory Commands”# List all hostsansible all --list-hosts
# List hosts in groupansible webservers --list-hosts
# List group hierarchyansible-inventory -i inventory.ini --graph
# Show inventory as JSONansible-inventory -i inventory.ini --list
# Show specific host variablesansible-inventory -i inventory.ini --host web1.example.com
# Validate inventory fileansible-inventory -i inventory.ini --list --yamlComplete Inventory Example
Section titled “Complete Inventory Example”# Define hosts[loadbalancers]lb1.example.com ansible_host=10.0.1.10lb2.example.com ansible_host=10.0.1.11
[webservers]web1.example.com ansible_host=10.0.2.10web2.example.com ansible_host=10.0.2.11web3.example.com ansible_host=10.0.2.12
[databases]db1.example.com ansible_host=10.0.3.10db2.example.com ansible_host=10.0.3.11
[cache]cache1.example.com ansible_host=10.0.4.10cache2.example.com ansible_host=10.0.4.11
# Environment group[production:children]loadbalancerswebserversdatabasescache
# Variables[all:vars]ansible_user=ubuntuansible_python_interpreter=/usr/bin/python3ansible_ssh_common_args='-o StrictHostKeyChecking=no'
[webservers:vars]nginx_workers=4php_fpm_children=10
[databases:vars]postgres_max_connections=200postgres_shared_buffers=256MBSummary
Section titled “Summary”In this chapter, you learned:
- Inventory Overview: What is inventory and why use it
- Static Inventory: INI and YAML formats
- Inventory Patterns: Selecting hosts with patterns
- Host Variables: Host-specific configuration
- Group Variables: Group-level configuration
- Dynamic Inventory: AWS and custom scripts
- Best Practices: Organizing and securing inventory