Ansible Commands Cheat Sheet — Practical DevOps Guide
A battle-tested reference of essential commands for day-to-day DevOps infrastructure automation, configuration management, production outage triage, and technical interview preparation.
🔹 1. Basic Ansible CLI Commands
These fundamental commands help you inspect installed versions, active configuration files, module search paths, and default runtime settings across your workstation or CI/CD runners.
# Check installed Ansible version, configuration path, and Python interpreter
ansible --version
# Display general CLI options and global runtime flags
ansible --help
# Dump the entire active configuration with source annotations (defaults vs user overrides)
ansible-config dump
# View the currently active ansible.cfg file directly
ansible-config view
# Generate a clean starter ansible.cfg template with all parameters commented
ansible-config init --disabled > ansible.cfg
ansible-config dump --only-changed filters the output down to only the configuration values you have explicitly customized, making troubleshooting unexpected behavior fast and clean.
🔹 2. Ansible Inventory Management Commands
Ansible operates against managed nodes defined in static hosts files or dynamically fetched from cloud APIs. Use these commands to validate grouping, host variables, and inheritance structures before launching tasks.
# Output the full inventory in JSON format, including host variables and group memberships
ansible-inventory --list
# Render an intuitive visual tree of all host groups and their nested parent-child hierarchies
ansible-inventory --graph
# Print all matched target hostnames without executing any tasks
ansible all --list-hosts
# List hosts belonging to a specific group (e.g. webservers or databases)
ansible webservers --list-hosts
# Verify pattern intersections: target nodes present in 'staging' AND 'us-east-1'
ansible 'staging:&us-east-1' --list-hosts
🔹 3. Ansible Ad-Hoc Commands for Incident Triage
Ad-hoc commands are perfect for quick, single-task operations during live outages. Rather than writing a full YAML playbook, you can fire targeted modules across your entire fleet in seconds.
# Verify SSH connectivity, key authentication, and Python interpreter reachability
ansible all -m ping
# Execute a binary directly without shell overhead (safe from shell injection)
ansible all -m command -a "uptime"
# Run a full shell command supporting pipes (|), redirects (>), and environment variables
ansible all -m shell -a "df -h | grep -v tmpfs"
# Check free memory and swap utilization across all staging nodes
ansible staging -m shell -a "free -m"
# Execute a command in parallel with custom concurrency forks (e.g., 20 simultaneous workers)
ansible all -m command -a "uptime" -f 20
command and shell modules! The command module does not invoke a subshell, preventing unexpected variable expansion and pipe risks. Use shell only when pipes, redirection, or stream processing are strictly required.
🔹 4. Privilege Escalation Commands (become & sudo)
By default, tasks execute as the connecting SSH user. When operations require root or administrative privileges, use the -b (become) flag.
# Execute command with root privileges using sudo (become)
ansible all -m command -a "whoami" -b
# Prompt interactively for the sudo password (--ask-become-pass)
ansible all -m command -a "whoami" -b -K
# Escalate to a specific service user (e.g. postgres or www-data) instead of root
ansible db_servers -m command -a "whoami" -b --become-user postgres
# Specify custom become method (sudo, su, pbrun, doas)
ansible all -m command -a "id" -b --become-method sudo
🔹 5. Package & Service Management Commands
Manage the installation, upgrading, and lifecycle states of critical OS services idempotently across Debian, Ubuntu, RHEL, Amazon Linux, and CentOS.
# Ensure package is installed using the OS-agnostic generic package module
ansible all -m package -a "name=nginx state=present" -b
# Ensure package is updated to the latest available upstream release
ansible all -m package -a "name=nginx state=latest" -b
# Start the service daemon if it is stopped (idempotent, no-op if already running)
ansible all -m service -a "name=nginx state=started" -b
# Restart the service daemon to reload disk configurations
ansible all -m service -a "name=nginx state=restarted" -b
# Ensure service is enabled to launch automatically upon system boot
ansible all -m service -a "name=nginx state=started enabled=yes" -b
# Stop service cleanly during emergency maintenance windows
ansible all -m service -a "name=nginx state=stopped" -b
🔹 6. File Management & Log Extraction Commands
Handle directory provisioning, file deployment, ownership management, and retrieving diagnostic log bundles from remote production servers.
# Idempotently create directory structure with strict permission modes
ansible all -m file -a "path=/opt/app state=directory mode=0755 owner=root group=root" -b
# Copy a local configuration file to remote targets with backup creation
ansible all -m copy -a "src=app.conf dest=/etc/app.conf backup=yes mode=0644" -b
# Fetch remote log files from target nodes back to your local central controller
ansible all -m fetch -a "src=/var/log/app.log dest=/tmp/logs/ flat=no"
# Remove temporary files or lock files safely
ansible all -m file -a "path=/tmp/app.lock state=absent" -b
# Set SELinux file contexts and ownership recursively
ansible webservers -m file -a "path=/var/www/html state=directory recurse=yes owner=nginx" -b
🔹 7. Playbook Execution & Runtime Flags
Playbooks orchestrate complex multi-tier architectures. Mastering execution flags ensures safe deployments and rapid rollouts.
# Execute standard site playbook using default inventory
ansible-playbook site.yml
# Execute playbook against a designated custom inventory file
ansible-playbook site.yml -i inventory/production
# Execute with root privilege escalation enabled globally
ansible-playbook site.yml -b
# Run with increased parallel worker forks (e.g. 50 parallel SSH connections)
ansible-playbook site.yml -i inventory -f 50
# Pass extra runtime variables dynamically from the command line
ansible-playbook site.yml -e "app_version=v2.4.0 env=production"
# Step-by-step interactive execution: prompts for confirmation before each task
ansible-playbook site.yml --step
-f 50 reduces deployment time down to ~2 minutes.
🔍 8. Validate Commands Before Production Deployment
Never push changes blind into production. These validation checks give you 100% confidence by catching YAML typos, verifying logic, and previewing diffs.
# 1. Syntax check: validates YAML format and task parameters locally without connecting to hosts
ansible-playbook site.yml --syntax-check
# 2. Check mode (Dry Run): connects to hosts and simulates execution without modifying any system state
ansible-playbook site.yml --check
# 3. Diff mode: displays unified line-by-line diffs of files that would be modified
ansible-playbook site.yml --diff
# 4. The Gold Standard Pre-Flight Check: combines dry run and diff previews together
ansible-playbook site.yml --check --diff
# 5. List all tasks that will run in execution order without invoking them
ansible-playbook site.yml --list-tasks
🏷️ 9. Tags, Limits & Targeted Task Execution
When an incident occurs or only a single microservice needs an emergency patch, use tags and limits to restrict execution blast radius.
# Run only tasks tagged with 'install' or 'packages'
ansible-playbook site.yml --tags install
# Run multiple tagged operations together
ansible-playbook site.yml --tags "nginx,ssl"
# Skip long-running configuration tasks during an emergency security patch
ansible-playbook site.yml --skip-tags configure
# Limit execution to a single specific host (e.g. canary testing on web01)
ansible-playbook site.yml --limit web01
# Limit execution to a specific failure group
ansible-playbook site.yml --limit "failed_hosts"
# List all tags declared across the entire playbook
ansible-playbook site.yml --list-tags
🔐 10. Ansible Vault Secrets Management Commands
Ansible Vault encrypts sensitive variables, TLS private keys, API credentials, and database passwords directly inside Git repositories using AES-256 encryption.
# Create and encrypt a new secrets file in one step
ansible-vault create secrets.yml
# Decrypt, open in your configured $EDITOR, and re-encrypt automatically upon save & exit
ansible-vault edit secrets.yml
# View encrypted secrets in your terminal without saving decrypted text to disk
ansible-vault view secrets.yml
# Encrypt an existing unencrypted plaintext file
ansible-vault encrypt secrets.yml
# Permanently decrypt an encrypted file back into plaintext
ansible-vault decrypt secrets.yml
# Rekey an existing vault file with a new password
ansible-vault rekey secrets.yml
# Run a playbook referencing vault-encrypted files with password prompt
ansible-playbook site.yml --ask-vault-pass
# Run a playbook referencing vault password stored in an external file (ideal for CI/CD)
ansible-playbook site.yml --vault-password-file ~/.vault_pass.txt
📦 11. Ansible Galaxy Roles & Collections Commands
Ansible Galaxy provides community-tested modular roles and official vendor collections (AWS, Azure, GCP, Kubernetes) for enterprise infrastructure automation.
# Initialize standard role directory skeleton structure with tasks, handlers, vars, and meta
ansible-galaxy role init nginx
# Install a community-verified production role from Galaxy
ansible-galaxy role install geerlingguy.nginx
# Install an official cloud collection (e.g., AWS modules: ec2, s3, iam, rds)
ansible-galaxy collection install amazon.aws
# Install the official Kubernetes collection for kubectl and Helm integrations
ansible-galaxy collection install kubernetes.core
# Install all roles and collections declared in a declarative requirements.yml manifest
ansible-galaxy install -r requirements.yml
# List all locally installed roles
ansible-galaxy role list
🔧 12. Ansible Troubleshooting & Module Documentation
When an SSH handshake fails, tasks hang, or module arguments are unclear, use these diagnostic utilities to inspect systems and module documentation offline.
# Quick SSH reachability and authentication sanity check
ansible all -m ping
# Gather all system facts (IP addresses, memory, CPU, disk partitions, cgroups, OS details)
ansible all -m setup
# Filter system facts to reduce output volume (e.g. memory statistics only)
ansible all -m setup -a "filter=ansible_mem*"
# View built-in module documentation and parameter specs directly in terminal
ansible-doc copy
# View parameters and production code examples for the package module
ansible-doc -s package
# Run playbook with verbose output (-v: result, -vv: input/output, -vvv: SSH, -vvvv: connection plugins)
ansible-playbook site.yml -vvv
☁️ 13. AWS Dynamic Inventory EC2 Commands
Modern cloud architectures feature autoscaling EC2 instances whose IP addresses constantly change. The amazon.aws.aws_ec2 plugin dynamically queries AWS APIs to discover targets.
# Visualize all discovered AWS EC2 instances grouped by tags, VPCs, and regions
ansible-inventory -i aws_ec2.yml --graph
# Output full EC2 metadata (instance ID, public/private IPs, security groups) in JSON
ansible-inventory -i aws_ec2.yml --list
# Ping all discovered EC2 instances matching dynamic inventory filters
ansible all -i aws_ec2.yml -m ping
# Execute playbook exclusively against dynamic EC2 instances tagged 'Role: webserver'
ansible-playbook site.yml -i aws_ec2.yml --limit "tag_Role_webserver"
plugin: amazon.aws.aws_ec2
regions:
- us-east-1
filters:
instance-state-name: running
keyed_groups:
- key: tags.Environment
prefix: env
- key: tags.Role
prefix: role
hostnames:
- private-ip-address
🧠 14. Quick Memory Trick & Binary Architecture Reference
Keep this mental map in mind during interviews to immediately distinguish between Ansible's core command-line binaries.
| CLI Command | Primary Purpose | Key Flag to Remember | Interview Talking Point |
|---|---|---|---|
ansible |
Ad-hoc commands & incident triage | -m module -a "args" |
Zero-code quick execution; ping, uptime, df |
ansible-playbook |
Execute structured YAML workflows | --check --diff -f 50 |
Orchestration, idempotency, parallel forks |
ansible-inventory |
Query static & dynamic cloud hosts | --graph --list |
Validates dynamic groups, tags, and hostvars |
ansible-vault |
Encrypt sensitive keys & tokens | --vault-password-file |
AES-256 encryption; safe Git secrets handling |
ansible-galaxy |
Roles & collection package manager | role init / install -r |
Modular architecture; reusable community roles |
ansible-doc |
Module reference & code examples | -s module_name |
Offline documentation; parameter signatures |
ansible-config |
Engine configuration audit | dump --only-changed |
Audits forks, pipelining, SSH parameters |
❓ 15. Frequently Asked Questions: Ansible Interview Scenarios
What is the difference between command and shell modules in Ansible?
command module executes binaries directly without spawning a shell interpreter (/bin/sh). It is faster, more secure, and immune to shell injection risks, but does not support pipes (|), redirects (>), or environment variable expansion. The shell module executes commands through the remote shell, enabling pipelines and stream operations, but requires careful sanitization of untrusted variables.
How do you optimize Ansible playbook execution speed when managing 100+ servers?
- Increase concurrency using
forks = 50or-f 50. - Enable SSH pipelining (
pipelining = Trueinansible.cfg) to eliminate intermediate Python script file writes. - Disable fact gathering (
gather_facts: false) when system facts are not required. - Enable SSH multiplexing (
ControlMasterandControlPersist). - Use
asyncandpollfor long-running non-dependent tasks.
What is Ansible idempotency and how do you ensure custom shell scripts remain idempotent?
file, package, and service are inherently idempotent. When invoking custom bash commands via command or shell, you must provide idempotency safeguards using the creates argument (skip task if path exists) or removes argument (run only if path exists), or register task output with conditional when clauses.
How do you manage secrets securely in CI/CD pipelines using Ansible Vault?
ansible-vault encrypt. Inside CI/CD runners (GitHub Actions, GitLab CI, Jenkins), inject the vault decryption password as a protected environment variable or secret file. Execute playbooks using --vault-password-file pointing to the injected secret or use ANSIBLE_VAULT_PASSWORD_FILE, ensuring unencrypted keys never touch disk or console logs.
What is the difference between --check mode and --syntax-check?
--syntax-check is a local parser check that validates YAML syntax, playbook structure, and task indentation without opening any network connections or reaching remote hosts. In contrast, --check (dry-run mode) connects over SSH to every host in the inventory, evaluates facts and module states, and reports whether tasks would result in ok or changed without applying actual system modifications.