Ansible’s command line options let you control execution precision, optimize performance, and manage complex tasks without configuration files, giving you direct control over every step of your automation workflow. With the right CLI flags, you can pinpoint which servers to target, adjust execution speed, validate results, and even bypass manual steps for fully automated runs. The key is understanding which flags do what—and when—so you can write scripts that behave as intended.
What You'll Need
- A Linux, macOS, or Windows (WSL) machine with Ansible installed (version 2.9+ recommended). Windows users must use PowerShell or WSL for full CLI flexibility.
- An inventory file (hosts.ini or similar) mapping your managed servers, or access to a cloud/on-prem network where Ansible can discover hosts automatically.
- Basic familiarity with Ansible playbooks (though not required for this guide).
- Optional: A local test environment (e.g., VirtualBox with Ubuntu guests) to practice commands without risking production systems.
Step-by-Step: Core Ansible CLI Options
- List Available Commands
Run this to see all CLI options without triggering execution:
ansible --helpThis gives you a categorized list of modules (commands like "copy", "package", "service") and flags. For instance, the--module-nameflag restricts output to only that module’s options. If you’re new to Ansible, the--list-tasksflag under a playbook will show you each step’s output before running it. - Target Specific Hosts or Groups
Use the
-ior--inventoryflag to override the default inventory:ansible all -m ping -i /path/to/custom/inventoryOr target a specific group:ansible webservers -m pingTo include/exclude hosts dynamically, use variables:ansible --variables="users=web --limit="webservers[0:2]" -m pingAnsible respects priority: hosts in thehost_varsor inventory file override variables set at the CLI. - Control Execution Speed and Retries
Use
-efor ad-hoc facts (e.g.,ansible all -e "host=test" -m ping), or--extra-varsfor dynamic values:ansible -e "ansible_user=admin ansible_password=secret" all -m copyFor retries (default: 3), adjust with:ansible --extra-vars="ansible_retry_when=failed" all -m service --skip-tag crashThis is critical for tasks like database migrations where partial failures must be retried. - Validate Before Execution
Use
--checkto simulate changes without applying them:ansible-playbook playbook.yml --checkThis mode dumps the final state of every module (e.g., what would be copied ifcopywere run). Combine with--diffto compare current state vs. proposed changes:ansible-playbook playbook.yml --check --diffAlways run--checkbefore deploying changes to production. - Limit Playbook Execution
For playbooks, use
-lto limit the number of hosts:ansible-playbook playbook.yml -l 10Or run only specific plays in a playbook file:ansible-playbook playbook.yml --play-name "backup"Use-tto skip tags (e.g.,ansible-playbook playbook.yml -t "critical"to avoid non-critical tasks). - Suppress Output
Quietly run tasks with
--quietor-q:ansible-playbook playbook.yml --quietTo see only errors:ansible-playbook playbook.yml --quiet --executableWarning: No output means no visibility into failures. Use sparingly. - Parallelize Operations
Use
-fto set fork limits (default: 5). To run tasks in parallel across all hosts:ansible-playbook playbook.yml -f 50For ad-hoc commands, use--limit="all" --forks 10. Higher fork counts increase network usage but speed up execution. - Save Output to Files
Redirect standard output (stdout) with
--stdout-file:ansible all -m ping --stdout-file /tmp/host_status.txtFor playbooks, use--limit="all" --list-playbooks | tee results.txtto log playbook metadata. - Enable Verbose Logging
Increase verbosity with
-v(levels: 0=quiet, 9=debug):ansible-playbook playbook.yml -vvvDebug mode (9) shows connection details, variable substitutions, and module arguments. Use this only for troubleshooting. - Skip Tags and Restart
Skip tagged tasks entirely with
--skip-tags "non-critical", or restart specific hosts:ansible -a "reboot" --limit "webservers[1:]" --skip-tags "critical"Use--start-at-taskto resume from a playbook step:ansible-playbook playbook.yml --start-at-task "backup_files"
If That Did Not Work
Common failures stem from misconfiguration. Start with these checks:- Verify Ansible Version
Run
ansible --version. Older versions 2.8 or below lack some modern CLI features. Update with:pip install ansible --upgrade - Check Inventory Path
If using
-i, ensure the file exists and has proper host/group syntax (e.g.,webservers: hosts: [server1]). - Test Connectivity
Use
ansible all -u username -m pingto confirm SSH access works. Fix permissions for ~/.ssh/id_rsa.pub. - Review Logs
Redirect output with
ansible-playbook playbook.yml -vvv > logfile.logto inspect errors.
Common Mistakes
- Overusing Default Inventory
Always specify an inventory path or use
--limitif you’re unsure about host groups. Defaults (e.g.,localhost) can be misleading. - Ignoring Variable Scope
CLI variables like
-e "host=test"override inventory/host_vars. Use--extra-varsfor dynamic values per command. - Skipping
--checkBefore Production Without--check, changes apply immediately. Always validate first. - Assuming Parallelism is Safe
Forks >5 can overload networks or overrun disk I/O. Test with
-f 10first. - Mixing CLI and Playbook Task Tags
CLI flags like
-toverride playbook tags. Use playbook tags for granular control.
Tips
- Combine Flags for Efficiency
Example: Run a backup playbook excluding non-critical hosts:
ansible-playbook backup.yml --skip-tags "non-critical" --limit="prod" - Use Templates for Dynamic Commands
Save complex CLI commands (e.g.,
ansible all -m copy -e "src=file" -e "dest=/tmp" --stdout-file=output.log) in a YAML template and reuse. - Leverage Ansible Vault for Secrets
Encrypt sensitive variables with
ansible-vaultinstead of hardcoding them in CLI flags. - Capture Playbook Output as Facts
Use
--list-hostsor--list-tasksto gather host metadata for later use in playbooks. - Bookmark Common Commands
Ansible’s CLI is powerful but complex. Create aliases (e.g.,
alias pingall="ansible all -m ping"*) for your most-used tasks.
Troubleshooting
- Command Not Found or Syntax Errors
Ensure Ansible is installed globally (not just in a virtual environment). Reinstall with:
pip install --upgrade ansibleCheck for typos in flags (e.g.,--limitvs-limit). - Hosts Not Responding
Wrap SSH commands with
--private-keyor--user:ansible webservers -m ping --private-key ~/.ssh/id_rsaTest connectivity first withssh user@host. - Playbook Fails Silently
Add
-vvvto debug. Look for: - Missing modules (list withansible-doc -t module). - Permission errors (e.g.,sudo ansible-playbook). - Timeouts (increase with--timeout). - Parallel Execution Crashes
Reduce forks with
-f 20. Monitor disk/network usage during execution. - Output Not Saving
Ensure the target file is writable. Use absolute paths (e.g.,
/tmp/output.txt).
Frequently Asked Questions
How do I run an Ansible command only on specific hosts?
Use the-l or --limit flag with host/group names. Example:
ansible -l "webservers[1:3]" -m ping
Lists hosts 1–3 in the "webservers" group.
Can I combine CLI flags and playbooks?
Yes! For example, run a playbook but skip certain hosts:ansible-playbook playbook.yml --limit="dbservers"
What’s the difference between -e and --extra-vars?
Use -e for simple key-value pairs (e.g., -e "port=8080"), and --extra-vars for complex expressions (e.g., --extra-vars "host=prod[0:2]").
How do I save playbook results as JSON?
Use thejson_query filter with --list-tasks, then parse with Python:
ansible-playbook playbook.yml --list-tasks | jq '
Why does --skip-tag not work?
Tags must match exactly (case-sensitive). Verify tags exist with:
ansible-playbook playbook.yml --list-tasks | grep "tag"
If tags are nested, use --tags="tag1.tag2".
How do I debug a slow playbook?
1. Increase verbosity: -vvv
2. Limit hosts: -l "webservers"
3. Check network connectivity: ping hosts individually
4. Monitor disk I/O with htop during execution.