Stage 4 · Provision
Dynamic Inventory & Scale
Groups & Host Patterns
Group hierarchies, patterns, and limiting with --limit.
Group Hierarchies
Ansible groups can contain other groups using the :children suffix. This creates a hierarchy — the all group contains everything, and you create parent groups for different tiers or environments.
all:
children:
production:
children:
webservers:
hosts:
web1.prod.example.com:
web2.prod.example.com:
dbservers:
hosts:
db1.prod.example.com:
monitoring:
hosts:
mon1.prod.example.com:
staging:
children:
webservers:
hosts:
web1.staging.example.com:
dbservers:
hosts:
db1.staging.example.com:The production and staging groups both contain webservers and dbservers subgroups. This hierarchy enables environment-specific targeting.
Host Pattern Syntax
# All hosts
ansible all -m ping
# A group
ansible webservers -m ping
# A subgroup (dot notation)
ansible production.webservers -m ping
# Individual host
ansible web1.prod.example.com -m ping
# Wildcard
ansible 'web*.prod.example.com' -m ping
# Union (OR)
ansible 'webservers:dbservers' -m ping
# Intersection (AND)
ansible 'production:&webservers' -m ping
# Exclusion (NOT)
ansible 'all:!staging' -m ping
# Complex expression
ansible 'production:&webservers:!web2*' -m pingPatterns combine groups, wildcards, and set operations. Use single quotes to prevent shell expansion of special characters.
The --limit Flag
# Limit to specific hosts
ansible-playbook site.yml --limit web1.prod.example.com
# Limit to a group
ansible-playbook site.yml --limit webservers
# Limit to a pattern
ansible-playbook site.yml --limit 'web*.prod.example.com'
# Multiple limits
ansible-playbook site.yml --limit webservers --limit monitoring--limit restricts which hosts the playbook runs against, even if the playbook targets a larger group. It is essential for testing and staged rollouts.
Group Variables
all:
vars:
ansible_user: deploy
ansible_port: 22
children:
webservers:
vars:
http_port: 80
app_root: /var/www
hosts:
web1.example.com:
web2.example.com:Group variables apply to all hosts in the group. They can be defined inline in inventory or in group_vars/ files.
Pattern Examples
Use ansible all --list-hosts -i inventory.yml to verify which hosts a pattern matches before running playbooks.
Mark this lesson complete to store local progress and unlock a cleaner resume path the next time you visit.