Selecting Hosts Using Patterns
Two more pattern forms, and the flag that lets you apply any of this course’s pattern syntax without ever touching a playbook’s own hosts: line.
Numeric Ranges
[start:end] expands a range directly, for hosts following a numbered naming convention:
ansible 'web[01:10]' -m ansible.builtin.pingMatches web01 through web10 — genuinely useful the moment hosts are named with a predictable numeric sequence, without needing to define a group listing every single one by hand.
Regex Patterns With ~
A pattern prefixed with ~ is treated as a full regular expression, for matching beyond what wildcards and ranges can express:
ansible '~web\d+\.prod\..*' -m ansible.builtin.pingReach for this only when wildcards and ranges genuinely can’t express what you need — a regex pattern is powerful, but noticeably harder to read at a glance than the simpler forms covered in the previous chapter.
--limit: Applying A Pattern Without Touching The Playbook
Every pattern from this chapter and the previous one works directly on the command line with ansible, targeting an ad hoc command. --limit applies that same pattern power to an ansible-playbook run, restricting which hosts from the playbook’s own hosts: line actually get touched, without editing the playbook file at all:
ansible-playbook site.yaml --limit 'webservers:&staging'If site.yaml targets hosts: all, this run still only touches whichever hosts satisfy the pattern — genuinely useful for a one-off, targeted run against a subset of a much broader playbook, without maintaining a separate copy of it just for that narrower case.
A Realistic Combination
ansible-playbook site.yaml --limit 'web[01:20]:!maintenance'Every web server numbered 01 through 20, excluding anything currently flagged as under maintenance — a genuinely practical, real-world targeting expression, built entirely from this chapter’s and the previous one’s pieces.
Best Practices
- Use numeric ranges for predictably-numbered hosts, rather than hand-listing them in a group.
- Reserve regex patterns (
~) for cases wildcards and ranges genuinely can’t express — they’re the least readable option, appropriate only when nothing simpler will do. - Use
--limitfor one-off, targeted runs against a broader playbook, rather than maintaining a near-duplicate playbook that only differs in which hosts it targets.