ansible-playbook --limit: Run Playbooks on Specific Hosts (Complete Guide)
By Luca Berton · Published 2024-01-01 · Category: troubleshooting
Complete guide to ansible-playbook --limit. Target specific hosts, groups, and patterns. Use regex limits, exclude hosts, and safely restrict playbook execution.
What Is --limit?
The --limit flag restricts playbook execution to specific hosts or groups from your inventory, without modifying the playbook or inventory file.
Basic Syntax
Host Patterns
Wildcard Patterns
Regex Patterns
Use ~ prefix for regex:
Exclude Hosts
Use ! to exclude:
Intersection (AND Logic)
Use & for intersection:
Combined Patterns
Using --limit with retry Files
When a playbook fails, Ansible creates a .retry file listing failed hosts:
Practical Examples
Rolling Deployments
Testing on Single Host
Emergency Patching
In-Playbook Host Limiting
Using hosts Directive
Using run_once
Using when with inventory_hostname
Using delegate_to
Common Mistakes
Forgetting Quotes
Limit vs Hosts Directive
--limit further restricts the hosts directive — it can't expand it:
FAQ
Can --limit override the hosts directive in a playbook?
No. --limit can only further restrict which hosts from the playbook's hosts directive are targeted. It cannot add hosts that aren't already matched by the hosts line.
How do I limit to a single host safely?
Use --limit hostname --check --diff first to preview changes, then remove --check to apply. This is the safest way to test playbooks on individual hosts before rolling out to the full inventory.
What happens if --limit matches no hosts?
Ansible skips the play and shows a warning. No tasks execute. You can force an error with any_errors_fatal: true or check with --list-hosts first.
How do I list which hosts --limit would target?
Use --list-hosts to preview without running:
Related Articles • Ansible Playbook Structure Guide • Ansible Inventory Guide • Ansible delegate_to Guide • Ansible run_once Guide
Category: troubleshooting