Ansible playbook --limit: Run on Specific Hosts (Complete Guide)
By Luca Berton · Published 2024-01-01 · Category: troubleshooting
How to use Ansible playbook --limit to target specific hosts, groups, and patterns. Limit execution to one host, exclude hosts, use regex patterns. Practical examples for precise targeting.
Ansible playbook --limit: Run on Specific Hosts (Complete Guide)
The --limit flag (or -l) restricts playbook execution to specific hosts or groups from your inventory. It's essential for targeted deployments, testing on single hosts, and rolling updates.
Basic Usage
Host Patterns
Single Host
Multiple Hosts (Comma-Separated)
Entire Group
Multiple Groups (Union)
Group Intersection (AND)
Exclude Hosts/Groups (NOT)
Wildcard Patterns
Regex Patterns
Numeric Range
Combining Patterns
Using --limit with retry files
When a playbook fails on some hosts, Ansible creates a .retry file:
Limit in Playbook (hosts directive)
You can also limit at the playbook level:
Practical Examples
Rolling Deployment (One Host at a Time)
Test on Staging Before Production
Emergency Fix on Single Server
Canary Deployment
--limit with Ad-Hoc Commands
Common Mistakes
1. Forgetting quotes with special characters
2. Limit doesn't override hosts directive
3. Case sensitivity
Host names and group names are case-sensitive in the inventory:
FAQ
How do I run an Ansible playbook on one specific host?
Use --limit hostname: ansible-playbook playbook.yml --limit web01. The host must be in your inventory and match the play's hosts directive.
How do I exclude a host from an Ansible playbook run?
Use the ! (NOT) pattern: --limit "all:!web03" or --limit "webservers:!web03". Quote the pattern to prevent shell interpretation of !.
Can I use --limit with ansible-playbook and ad-hoc commands?
Yes. Both ansible-playbook and ansible ad-hoc commands accept --limit (or -l). The pattern syntax is identical.
What happens if --limit matches no hosts?
Ansible will show "no hosts matched" and skip the play. No tasks will execute. Use --list-hosts to preview which hosts would be targeted: ansible-playbook site.yml --limit "pattern" --list-hosts.
How do I retry only failed hosts?
After a failure, Ansible creates a playbook.retry file listing failed hosts. Run ansible-playbook playbook.yml --limit @playbook.retry to retry only those hosts.
Conclusion
The --limit flag is essential for targeted Ansible execution. Use it for single-host testing, rolling deployments, canary releases, and emergency fixes. Combine with patterns (:& for intersection, :! for exclusion) for precise host targeting.
Related Articles • Ansible Inventory: Complete Guide • Ansible Playbook: Complete Guide • Run Ansible Playbook on One Host
Category: troubleshooting