Top Tags

Ansible CLI Handbook

Quick reference for essential Ansible commands — ad-hoc tasks, playbooks, inventory, vault, galaxy, configuration, debugging, and more.

Installation & Setup

Install Ansible

bash
1# macOS (Homebrew)
2brew install ansible
3
4# Ubuntu / Debian (apt)
5sudo apt update && sudo apt install -y ansible
6
7# Fedora / RHEL (dnf)
8sudo dnf install -y ansible
9
10# Python (pip — universal)
11pip install ansible
12
13# Verify installation
14ansible --version

Shell Autocomplete

bash
1# Bash — install argcomplete
2pip install argcomplete
3
4# Activate globally (requires root)
5activate-global-python-argcomplete
6
7# Or activate per session
8eval "$(register-python-argcomplete ansible)"
9eval "$(register-python-argcomplete ansible-playbook)"
10eval "$(register-python-argcomplete ansible-galaxy)"

Useful Aliases

bash
1alias ap='ansible-playbook'
2alias av='ansible-vault'
3alias ag='ansible-galaxy'
4alias ai='ansible-inventory'
5alias ad='ansible-doc'

Important Paths & Config Files

Configuration File Lookup Order

Ansible searches for its configuration file in the following order (first found wins):

bash
1$ANSIBLE_CONFIG # 1. Environment variable (highest priority)
2./ansible.cfg # 2. Current directory
3~/.ansible.cfg # 3. Home directory (hidden file)
4/etc/ansible/ansible.cfg # 4. System-wide default (lowest priority)

Key Directories & Files

bash
1/etc/ansible/ # Default Ansible config directory
2/etc/ansible/ansible.cfg # System-wide config file
3/etc/ansible/hosts # Default inventory file
4/etc/ansible/roles/ # System-wide roles directory
5
6~/.ansible/ # User Ansible data directory
7~/.ansible.cfg # User config file
8~/.ansible/galaxy_token # Galaxy API token
9~/.ansible/tmp/ # Temporary files
10~/.ansible/cp/ # SSH connection persistence (ControlPath)
11~/.ansible/collections/ # User-installed collections
12~/.ansible/roles/ # User-installed roles

Log Files

bash
1# Logging is disabled by default. Enable in ansible.cfg:
2# [defaults]
3# log_path = /var/log/ansible.log
4
5/var/log/ansible.log # Common log location (if configured)
6~/.ansible/ansible.log # Alternative user-level log location

Environment Variables

bash
1ANSIBLE_CONFIG=/path/to/ansible.cfg # Override config file location
2ANSIBLE_INVENTORY=/path/to/hosts # Override default inventory
3ANSIBLE_ROLES_PATH=/path/to/roles # Override roles search path
4ANSIBLE_COLLECTIONS_PATH=/path/to/colls # Override collections search path
5ANSIBLE_LOG_PATH=/var/log/ansible.log # Enable and set log file path
6ANSIBLE_VAULT_PASSWORD_FILE=~/.vault_pass # Auto-use vault password file
7ANSIBLE_HOST_KEY_CHECKING=False # Disable SSH host key checking
8ANSIBLE_REMOTE_USER=deploy # Default remote user
9ANSIBLE_BECOME=True # Always use privilege escalation
10ANSIBLE_BECOME_METHOD=sudo # Default become method
11ANSIBLE_FORKS=20 # Number of parallel processes
12ANSIBLE_TIMEOUT=30 # SSH connection timeout

Inventory Management

Inventory Basics

bash
1ansible-inventory --list # Show full inventory as JSON
2ansible-inventory --list -y # Show full inventory as YAML
3ansible-inventory --graph # Show inventory tree/graph
4ansible-inventory --graph --vars # Graph with variables
5ansible-inventory --host myserver # Show variables for a specific host
6ansible-inventory -i custom_hosts --list # Use custom inventory file

Inventory File Formats

ini
1# INI format — /etc/ansible/hosts or inventory.ini
2[webservers]
3web1.example.com
4web2.example.com ansible_port=2222
5
6[dbservers]
7db1.example.com ansible_user=admin
8db2.example.com
9
10[all:vars]
11ansible_user=deploy
12ansible_python_interpreter=/usr/bin/python3
13
14[webservers:vars]
15http_port=80
yaml
1# YAML format — inventory.yml
2all:
3 hosts:
4 mail.example.com:
5 children:
6 webservers:
7 hosts:
8 web1.example.com:
9 web2.example.com:
10 ansible_port: 2222
11 dbservers:
12 hosts:
13 db1.example.com:
14 ansible_user: admin

Host Patterns

bash
1ansible all -m ping # All hosts
2ansible webservers -m ping # Specific group
3ansible web1.example.com -m ping # Single host
4ansible 'webservers:dbservers' -m ping # Multiple groups (union)
5ansible 'webservers:&staging' -m ping # Intersection
6ansible 'webservers:!db1' -m ping # Exclusion
7ansible '*.example.com' -m ping # Wildcard
8ansible 'webservers[0]' -m ping # First host in group
9ansible 'webservers[0:2]' -m ping # Range of hosts

Ad-Hoc Commands

Syntax

bash
1ansible <host-pattern> -m <module> -a "<arguments>" [options]

Connectivity & Info

bash
1ansible all -m ping # Test connectivity to all hosts
2ansible all -m setup # Gather all facts from hosts
3ansible all -m setup -a "filter=ansible_os_family" # Filter specific facts
4ansible all --list-hosts # List matched hosts
5ansible all -m debug -a "msg={{ inventory_hostname }}" # Show hostname

Command Execution

bash
1ansible all -m command -a "uptime" # Run command (default module)
2ansible all -a "uptime" # Same — command is default
3ansible all -m shell -a "echo $HOME" # Shell module (supports pipes, env vars)
4ansible all -m raw -a "uptime" # Raw command (no Python required)
5ansible all -m script -a "/tmp/myscript.sh" # Run local script on remote hosts

File Operations

bash
1# Copy file to remote hosts
2ansible all -m copy -a "src=/local/file.txt dest=/remote/file.txt mode=0644"
3
4# Fetch file from remote hosts to local
5ansible all -m fetch -a "src=/remote/file.txt dest=/local/ flat=yes"
6
7# Create a directory
8ansible all -m file -a "path=/tmp/mydir state=directory mode=0755"
9
10# Create a symlink
11ansible all -m file -a "src=/file.conf dest=/etc/file.conf state=link"
12
13# Delete a file
14ansible all -m file -a "path=/tmp/oldfile state=absent"
15
16# Change file ownership
17ansible all -m file -a "path=/tmp/file owner=www-data group=www-data mode=0644"

Package Management

bash
1# APT (Debian/Ubuntu)
2ansible all -m apt -a "name=nginx state=present" -b
3ansible all -m apt -a "name=nginx state=latest" -b
4ansible all -m apt -a "name=nginx state=absent" -b
5ansible all -m apt -a "update_cache=yes" -b
6
7# YUM / DNF (RHEL/Fedora)
8ansible all -m yum -a "name=httpd state=present" -b
9ansible all -m dnf -a "name=httpd state=latest" -b

Service Management

bash
1ansible all -m service -a "name=nginx state=started" -b
2ansible all -m service -a "name=nginx state=stopped" -b
3ansible all -m service -a "name=nginx state=restarted" -b
4ansible all -m service -a "name=nginx enabled=yes" -b
5
6# Systemd-specific
7ansible all -m systemd -a "name=nginx state=reloaded daemon_reload=yes" -b

User & Group Management

bash
1# Create a user
2ansible all -m user -a "name=deploy shell=/bin/bash create_home=yes" -b
3
4# Add user to groups
5ansible all -m user -a "name=deploy groups=sudo append=yes" -b
6
7# Remove a user
8ansible all -m user -a "name=olduser state=absent remove=yes" -b
9
10# Create a group
11ansible all -m group -a "name=developers state=present" -b

Cron Jobs

bash
1# Create a cron job
2ansible all -m cron -a "name='daily backup' hour=2 minute=0 job='/opt/backup.sh'" -b
3
4# Remove a cron job
5ansible all -m cron -a "name='daily backup' state=absent" -b

Common Ad-Hoc Flags

bash
1-i INVENTORY # Specify inventory file or path
2-m MODULE # Module to run (default: command)
3-a "ARGS" # Module arguments
4-b, --become # Run with privilege escalation (sudo)
5-K, --ask-become-pass # Prompt for sudo password
6-k, --ask-pass # Prompt for SSH password
7-u USER # Remote user
8-f FORKS # Number of parallel processes (default: 5)
9-v, -vv, -vvv, -vvvv # Increasing verbosity levels
10--limit HOST # Restrict to specific host(s)
11-e "key=value" # Extra variables
12-C, --check # Dry run (no changes)
13-D, --diff # Show file diffs
14--private-key FILE # SSH private key file
15-t TAGS # Run only tagged tasks
16--skip-tags TAGS # Skip tagged tasks

Playbook Execution

Running Playbooks

bash
1ansible-playbook playbook.yml # Run a playbook
2ansible-playbook playbook.yml -i inventory.yml # With custom inventory
3ansible-playbook playbook.yml -i staging -i production # Multiple inventories
4ansible-playbook playbook.yml -l webservers # Limit to group/host
5ansible-playbook playbook.yml -b # With sudo
6ansible-playbook playbook.yml -b -K # With sudo, prompt password
7ansible-playbook playbook.yml -u deploy # As specific user
8ansible-playbook playbook.yml -e "env=staging version=2.1" # Extra variables
9ansible-playbook playbook.yml -e @vars.yml # Extra variables from file

Execution Control

bash
1ansible-playbook playbook.yml -C # Dry run (check mode)
2ansible-playbook playbook.yml -D # Show diffs for file changes
3ansible-playbook playbook.yml -C -D # Dry run with diffs
4ansible-playbook playbook.yml --step # Step through tasks one by one
5ansible-playbook playbook.yml --start-at-task="Install nginx" # Start at specific task
6ansible-playbook playbook.yml -t deploy # Run only tagged tasks
7ansible-playbook playbook.yml --skip-tags tests # Skip tagged tasks
8ansible-playbook playbook.yml -f 20 # Run with 20 forks

Syntax & Debugging

bash
1ansible-playbook playbook.yml --syntax-check # Validate playbook syntax
2ansible-playbook playbook.yml --list-tasks # List all tasks
3ansible-playbook playbook.yml --list-hosts # List targeted hosts
4ansible-playbook playbook.yml --list-tags # List all tags
5ansible-playbook playbook.yml -v # Verbose output
6ansible-playbook playbook.yml -vvv # Very verbose (connection debug)
7ansible-playbook playbook.yml -vvvv # Max verbosity (includes SSH)

Ansible Vault (Secrets Management)

Managing Encrypted Files

bash
1ansible-vault create secrets.yml # Create new encrypted file
2ansible-vault edit secrets.yml # Edit encrypted file in-place
3ansible-vault view secrets.yml # View encrypted file contents
4ansible-vault encrypt existing.yml # Encrypt an existing file
5ansible-vault decrypt secrets.yml # Decrypt a file permanently
6ansible-vault rekey secrets.yml # Change encryption password

Encrypting Strings

bash
1# Encrypt a single variable value
2ansible-vault encrypt_string 'SuperSecret123' --name 'db_password'
3
4# Encrypt from stdin
5echo -n 'SuperSecret123' | ansible-vault encrypt_string --stdin-name 'db_password'

Using Vault with Playbooks

bash
1# Prompt for vault password
2ansible-playbook playbook.yml --ask-vault-pass
3
4# Use vault password file
5ansible-playbook playbook.yml --vault-password-file ~/.vault_pass
6
7# Use vault ID (multiple vaults)
8ansible-playbook playbook.yml --vault-id dev@~/.vault_pass_dev
9ansible-playbook playbook.yml --vault-id prod@prompt

Ansible Galaxy (Roles & Collections)

Roles

bash
1ansible-galaxy role init my_role # Create role skeleton
2ansible-galaxy role install geerlingguy.nginx # Install role from Galaxy
3ansible-galaxy role install -r requirements.yml # Install roles from file
4ansible-galaxy role list # List installed roles
5ansible-galaxy role search elasticsearch # Search for roles
6ansible-galaxy role search elasticsearch --author geerlingguy # Search by author
7ansible-galaxy role remove geerlingguy.nginx # Remove installed role
8ansible-galaxy role info geerlingguy.nginx # Show role info

Collections

bash
1ansible-galaxy collection init mynamespace.mycollection # Create collection skeleton
2ansible-galaxy collection build # Build a collection tarball
3ansible-galaxy collection install community.general # Install a collection
4ansible-galaxy collection install -r requirements.yml # Install from requirements
5ansible-galaxy collection list # List installed collections
6ansible-galaxy collection verify community.general # Verify collection integrity
7ansible-galaxy collection download community.general -p ./downloads # Download for offline install

Requirements File

yaml
1# requirements.yml — define roles and collections to install
2roles:
3 - name: geerlingguy.nginx
4 version: "3.2.0"
5 - name: geerlingguy.docker
6 - src: https://github.com/user/custom-role.git
7 name: custom-role
8
9collections:
10 - name: community.general
11 version: ">=5.0.0"
12 - name: ansible.posix
bash
1# Install all from requirements file
2ansible-galaxy install -r requirements.yml
3ansible-galaxy collection install -r requirements.yml

Module Documentation

Browse Module Docs

bash
1ansible-doc -l # List all available modules
2ansible-doc -l | grep aws # Search module names
3ansible-doc copy # Show full docs for a module
4ansible-doc -s copy # Show snippet/example for a module
5ansible-doc -t connection -l # List connection plugins
6ansible-doc -t callback -l # List callback plugins
7ansible-doc -t inventory -l # List inventory plugins
8ansible-doc -t lookup -l # List lookup plugins

Configuration Management

View & Manage Config

bash
1ansible-config view # Show current ansible.cfg contents
2ansible-config dump # Dump all resolved settings (with sources)
3ansible-config dump --only-changed # Show only non-default settings
4ansible-config list # List all configurable settings with descriptions
5ansible-config init --disabled > ansible.cfg # Generate sample config with all options commented
6ansible-config init --disabled -t all > ansible.cfg # Include plugin-level settings

Common ansible.cfg Settings

ini
1[defaults]
2inventory = ./inventory
3remote_user = deploy
4private_key_file = ~/.ssh/id_ed25519
5host_key_checking = False
6retry_files_enabled = False
7forks = 20
8timeout = 30
9log_path = /var/log/ansible.log
10roles_path = ./roles:/etc/ansible/roles
11collections_path = ./collections
12stdout_callback = yaml
13callbacks_enabled = timer, profile_tasks
14interpreter_python = auto_silent
15
16[privilege_escalation]
17become = True
18become_method = sudo
19become_user = root
20become_ask_pass = False
21
22[ssh_connection]
23ssh_args = -o ControlMaster=auto -o ControlPersist=60s
24pipelining = True
25control_path_dir = ~/.ansible/cp
26
27[inventory]
28enable_plugins = host_list, script, auto, yaml, ini, toml

Debugging & Troubleshooting

Connectivity Testing

bash
1ansible all -m ping # Basic SSH + Python check
2ansible all -m ping -vvvv # Debug connection issues
3ansible all -m raw -a "hostname" # Test without Python on remote
4ansible all -m setup -a "filter=ansible_distribution" # Check remote OS info

Common Debug Commands

bash
1# Check which hosts match a pattern
2ansible webservers --list-hosts
3
4# Test playbook without making changes
5ansible-playbook playbook.yml -C -D
6
7# Run with maximum verbosity
8ansible-playbook playbook.yml -vvvv
9
10# Check playbook syntax
11ansible-playbook playbook.yml --syntax-check
12
13# Show facts for a host
14ansible myhost -m setup
15ansible myhost -m setup -a "filter=ansible_memory_mb"
16ansible myhost -m setup --tree /tmp/facts/ # Save facts to files

Troubleshooting Checklist

bash
1# SSH connection failing?
2ansible all -m ping -vvvv # Check SSH error details
3ssh -o StrictHostKeyChecking=no user@host # Test SSH manually
4
5# Module not found?
6ansible-doc -l | grep <module_name> # Verify module exists
7ansible --version # Check Ansible version
8
9# Privilege escalation issues?
10ansible all -m command -a "whoami" -b # Test sudo access
11ansible all -m command -a "sudo -l" -b # Check sudo permissions
12
13# Slow execution?
14# Enable pipelining in ansible.cfg:
15# [ssh_connection]
16# pipelining = True
17
18# Python not found on remote?
19ansible all -m raw -a "which python3" # Locate Python
20# Set in inventory: ansible_python_interpreter=/usr/bin/python3

Ansible Pull

bash
1# Pull and run playbook from a git repository
2ansible-pull -U https://github.com/user/repo.git playbook.yml
3
4# With checkout branch and inventory
5ansible-pull -U https://github.com/user/repo.git -C main -i localhost, playbook.yml
6
7# Run on a schedule via cron
8ansible-pull -U https://github.com/user/repo.git -o -s 60 playbook.yml
9# -o = only run if repo has changed, -s = random sleep before execution

Ansible Console (Interactive REPL)

bash
1ansible-console all -i inventory.yml # Start interactive console
2ansible-console webservers -b # Console with sudo
3
4# Inside the console:
5# cd webservers # Switch to a group
6# ping # Run ping module
7# command uptime # Run command
8# copy src=/tmp/file dest=/tmp/file # Copy a file
9# shell df -h # Run shell command
10# exit # Quit console

Useful One-Liners

bash
1# Check disk space on all servers
2ansible all -a "df -h" -b
3
4# Check uptime on all servers
5ansible all -a "uptime"
6
7# Check memory usage
8ansible all -m shell -a "free -m"
9
10# Reboot all webservers
11ansible webservers -m reboot -b
12
13# Kill a process on all hosts
14ansible all -m shell -a "pkill -f my_process" -b
15
16# Check if a service is running
17ansible all -m shell -a "systemctl is-active nginx"
18
19# Gather hostnames of all machines
20ansible all -m command -a "hostname -f"
21
22# Check which hosts are reachable
23ansible all -m ping --one-line
24
25# Deploy SSH key to all hosts
26ansible all -m authorized_key -a "user=deploy key='{{ lookup('file','~/.ssh/id_ed25519.pub') }}'" -b
27
28# Sync a directory
29ansible all -m synchronize -a "src=/local/dir/ dest=/remote/dir/"