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

  1. List Available Commands Run this to see all CLI options without triggering execution: ansible --help This gives you a categorized list of modules (commands like "copy", "package", "service") and flags. For instance, the --module-name flag restricts output to only that module’s options. If you’re new to Ansible, the --list-tasks flag under a playbook will show you each step’s output before running it.
  2. Target Specific Hosts or Groups Use the -i or --inventory flag to override the default inventory: ansible all -m ping -i /path/to/custom/inventory Or target a specific group: ansible webservers -m ping To include/exclude hosts dynamically, use variables: ansible --variables="users=web --limit="webservers[0:2]" -m ping Ansible respects priority: hosts in the host_vars or inventory file override variables set at the CLI.
  3. Control Execution Speed and Retries Use -e for ad-hoc facts (e.g., ansible all -e "host=test" -m ping), or --extra-vars for dynamic values: ansible -e "ansible_user=admin ansible_password=secret" all -m copy For retries (default: 3), adjust with: ansible --extra-vars="ansible_retry_when=failed" all -m service --skip-tag crash This is critical for tasks like database migrations where partial failures must be retried.
  4. Validate Before Execution Use --check to simulate changes without applying them: ansible-playbook playbook.yml --check This mode dumps the final state of every module (e.g., what would be copied if copy were run). Combine with --diff to compare current state vs. proposed changes: ansible-playbook playbook.yml --check --diff Always run --check before deploying changes to production.
  5. Limit Playbook Execution For playbooks, use -l to limit the number of hosts: ansible-playbook playbook.yml -l 10 Or run only specific plays in a playbook file: ansible-playbook playbook.yml --play-name "backup" Use -t to skip tags (e.g., ansible-playbook playbook.yml -t "critical" to avoid non-critical tasks).
  6. Suppress Output Quietly run tasks with --quiet or -q: ansible-playbook playbook.yml --quiet To see only errors: ansible-playbook playbook.yml --quiet --executable Warning: No output means no visibility into failures. Use sparingly.
  7. Parallelize Operations Use -f to set fork limits (default: 5). To run tasks in parallel across all hosts: ansible-playbook playbook.yml -f 50 For ad-hoc commands, use --limit="all" --forks 10. Higher fork counts increase network usage but speed up execution.
  8. Save Output to Files Redirect standard output (stdout) with --stdout-file: ansible all -m ping --stdout-file /tmp/host_status.txt For playbooks, use --limit="all" --list-playbooks | tee results.txt to log playbook metadata.
  9. Enable Verbose Logging Increase verbosity with -v (levels: 0=quiet, 9=debug): ansible-playbook playbook.yml -vvv Debug mode (9) shows connection details, variable substitutions, and module arguments. Use this only for troubleshooting.
  10. 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-task to 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:
  1. Verify Ansible Version Run ansible --version. Older versions 2.8 or below lack some modern CLI features. Update with: pip install ansible --upgrade
  2. Check Inventory Path If using -i, ensure the file exists and has proper host/group syntax (e.g., webservers: hosts: [server1]).
  3. Test Connectivity Use ansible all -u username -m ping to confirm SSH access works. Fix permissions for ~/.ssh/id_rsa.pub.
  4. Review Logs Redirect output with ansible-playbook playbook.yml -vvv > logfile.log to inspect errors.

Common Mistakes

  1. Overusing Default Inventory Always specify an inventory path or use --limit if you’re unsure about host groups. Defaults (e.g., localhost) can be misleading.
  2. Ignoring Variable Scope CLI variables like -e "host=test" override inventory/host_vars. Use --extra-vars for dynamic values per command.
  3. Skipping --check Before Production Without --check, changes apply immediately. Always validate first.
  4. Assuming Parallelism is Safe Forks >5 can overload networks or overrun disk I/O. Test with -f 10 first.
  5. Mixing CLI and Playbook Task Tags CLI flags like -t override playbook tags. Use playbook tags for granular control.

Tips

  1. Combine Flags for Efficiency Example: Run a backup playbook excluding non-critical hosts: ansible-playbook backup.yml --skip-tags "non-critical" --limit="prod"
  2. 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.
  3. Leverage Ansible Vault for Secrets Encrypt sensitive variables with ansible-vault instead of hardcoding them in CLI flags.
  4. Capture Playbook Output as Facts Use --list-hosts or --list-tasks to gather host metadata for later use in playbooks.
  5. 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

  1. Command Not Found or Syntax Errors Ensure Ansible is installed globally (not just in a virtual environment). Reinstall with: pip install --upgrade ansible Check for typos in flags (e.g., --limit vs -limit).
  2. Hosts Not Responding Wrap SSH commands with --private-key or --user: ansible webservers -m ping --private-key ~/.ssh/id_rsa Test connectivity first with ssh user@host.
  3. Playbook Fails Silently Add -vvv to debug. Look for: - Missing modules (list with ansible-doc -t module). - Permission errors (e.g., sudo ansible-playbook). - Timeouts (increase with --timeout).
  4. Parallel Execution Crashes Reduce forks with -f 20. Monitor disk/network usage during execution.
  5. 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 the json_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.