Patterns: Choosing Exactly Who to Touch
Scenario: An engineer meant to restart one database node. The pattern they typed matched every host in the estate.
New words, in plain English
- Host pattern - the expression after
hosts:in a play, or on the command line, that selects machines. - Limit - the
--limitflag, which narrows a run further at execution time. - Union / intersection / exclusion - combining patterns with
:,:&and:!.
Patterns are how blast radius is controlled, and they deserve more respect than they usually get.
The building blocks are simple: a group name selects the group; a host name selects the host; all selects everything. They combine:
webservers:dbservers- union: hosts in either group.webservers:&production- intersection: web servers that are also production.webservers:!web01- exclusion: the web tier apart from web01.web*- wildcard match on the name.
--limit applies on top of whatever the play already targets and can only ever narrow, never widen. That makes it the safe way to re-run one host after fixing it, and the right tool for a cautious first rollout.
Analogy: Patterns are a search filter on the company directory. Union is 'Backend OR Frontend'. Intersection is 'Backend AND based in Berlin'. Exclusion is 'Engineering but not contractors'. Getting the filter wrong does not just show you the wrong list - it emails all of them.
A worked example
# In a playbook
- name: Reconfigure the web tier
hosts: webservers:&production
# On the command line
ansible-playbook site.yml --limit web01
ansible-playbook site.yml --limit 'webservers:!web02'
# ALWAYS available, and free:
ansible webservers:&production --list-hosts
ansible-inventory --graph
Two safety habits are worth making automatic. Run --list-hosts before anything destructive - it prints the exact set without touching a thing. And prefer --check --diff for the first run of an unfamiliar change, so Ansible reports what it would do rather than doing it.
For genuinely dangerous operations, patterns alone are not enough protection; pre-flight assertions that refuse to run against the wrong environment are. That is covered later in this track, and it is the difference between a near miss and an incident review.
Warning:--limitcan only narrow. It cannot rescue a play whosehosts:line is already too broad - if the play sayshosts: all,--limitis the only thing standing between you and the entire estate.
Goal: Put this to work in the ansible-dynamic-inventory lab. Open/labs/ansible, pickansible-dynamic-inventory, and fix the real broken project - Ansible really does SSH into four managed hosts and converge them.