Installation & Setup
Install Ansible
bash
1# macOS (Homebrew)2brew install ansible3
4# Ubuntu / Debian (apt)5sudo apt update && sudo apt install -y ansible6
7# Fedora / RHEL (dnf)8sudo dnf install -y ansible9
10# Python (pip — universal)11pip install ansible12
13# Verify installation14ansible --versionShell Autocomplete
bash
1# Bash — install argcomplete2pip install argcomplete3
4# Activate globally (requires root)5activate-global-python-argcomplete6
7# Or activate per session8eval "$(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 directory3~/.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 directory2/etc/ansible/ansible.cfg # System-wide config file3/etc/ansible/hosts # Default inventory file4/etc/ansible/roles/ # System-wide roles directory5
6~/.ansible/ # User Ansible data directory7~/.ansible.cfg # User config file8~/.ansible/galaxy_token # Galaxy API token9~/.ansible/tmp/ # Temporary files10~/.ansible/cp/ # SSH connection persistence (ControlPath)11~/.ansible/collections/ # User-installed collections12~/.ansible/roles/ # User-installed rolesLog Files
bash
1# Logging is disabled by default. Enable in ansible.cfg:2# [defaults]3# log_path = /var/log/ansible.log4
5/var/log/ansible.log # Common log location (if configured)6~/.ansible/ansible.log # Alternative user-level log locationEnvironment Variables
bash
1ANSIBLE_CONFIG=/path/to/ansible.cfg # Override config file location2ANSIBLE_INVENTORY=/path/to/hosts # Override default inventory3ANSIBLE_ROLES_PATH=/path/to/roles # Override roles search path4ANSIBLE_COLLECTIONS_PATH=/path/to/colls # Override collections search path5ANSIBLE_LOG_PATH=/var/log/ansible.log # Enable and set log file path6ANSIBLE_VAULT_PASSWORD_FILE=~/.vault_pass # Auto-use vault password file7ANSIBLE_HOST_KEY_CHECKING=False # Disable SSH host key checking8ANSIBLE_REMOTE_USER=deploy # Default remote user9ANSIBLE_BECOME=True # Always use privilege escalation10ANSIBLE_BECOME_METHOD=sudo # Default become method11ANSIBLE_FORKS=20 # Number of parallel processes12ANSIBLE_TIMEOUT=30 # SSH connection timeoutInventory Management
Inventory Basics
bash
1ansible-inventory --list # Show full inventory as JSON2ansible-inventory --list -y # Show full inventory as YAML3ansible-inventory --graph # Show inventory tree/graph4ansible-inventory --graph --vars # Graph with variables5ansible-inventory --host myserver # Show variables for a specific host6ansible-inventory -i custom_hosts --list # Use custom inventory fileInventory File Formats
ini
1# INI format — /etc/ansible/hosts or inventory.ini2[webservers]3web1.example.com4web2.example.com ansible_port=22225
6[dbservers]7db1.example.com ansible_user=admin8db2.example.com9
10[all:vars]11ansible_user=deploy12ansible_python_interpreter=/usr/bin/python313
14[webservers:vars]15http_port=80yaml
1# YAML format — inventory.yml2all:3 hosts:4 mail.example.com:5 children:6 webservers:7 hosts:8 web1.example.com:9 web2.example.com:10 ansible_port: 222211 dbservers:12 hosts:13 db1.example.com:14 ansible_user: adminHost Patterns
bash
1ansible all -m ping # All hosts2ansible webservers -m ping # Specific group3ansible web1.example.com -m ping # Single host4ansible 'webservers:dbservers' -m ping # Multiple groups (union)5ansible 'webservers:&staging' -m ping # Intersection6ansible 'webservers:!db1' -m ping # Exclusion7ansible '*.example.com' -m ping # Wildcard8ansible 'webservers[0]' -m ping # First host in group9ansible 'webservers[0:2]' -m ping # Range of hostsAd-Hoc Commands
Syntax
bash
1ansible <host-pattern> -m <module> -a "<arguments>" [options]Connectivity & Info
bash
1ansible all -m ping # Test connectivity to all hosts2ansible all -m setup # Gather all facts from hosts3ansible all -m setup -a "filter=ansible_os_family" # Filter specific facts4ansible all --list-hosts # List matched hosts5ansible all -m debug -a "msg={{ inventory_hostname }}" # Show hostnameCommand Execution
bash
1ansible all -m command -a "uptime" # Run command (default module)2ansible all -a "uptime" # Same — command is default3ansible 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 hostsFile Operations
bash
1# Copy file to remote hosts2ansible all -m copy -a "src=/local/file.txt dest=/remote/file.txt mode=0644"3
4# Fetch file from remote hosts to local5ansible all -m fetch -a "src=/remote/file.txt dest=/local/ flat=yes"6
7# Create a directory8ansible all -m file -a "path=/tmp/mydir state=directory mode=0755"9
10# Create a symlink11ansible all -m file -a "src=/file.conf dest=/etc/file.conf state=link"12
13# Delete a file14ansible all -m file -a "path=/tmp/oldfile state=absent"15
16# Change file ownership17ansible 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" -b3ansible all -m apt -a "name=nginx state=latest" -b4ansible all -m apt -a "name=nginx state=absent" -b5ansible all -m apt -a "update_cache=yes" -b6
7# YUM / DNF (RHEL/Fedora)8ansible all -m yum -a "name=httpd state=present" -b9ansible all -m dnf -a "name=httpd state=latest" -bService Management
bash
1ansible all -m service -a "name=nginx state=started" -b2ansible all -m service -a "name=nginx state=stopped" -b3ansible all -m service -a "name=nginx state=restarted" -b4ansible all -m service -a "name=nginx enabled=yes" -b5
6# Systemd-specific7ansible all -m systemd -a "name=nginx state=reloaded daemon_reload=yes" -bUser & Group Management
bash
1# Create a user2ansible all -m user -a "name=deploy shell=/bin/bash create_home=yes" -b3
4# Add user to groups5ansible all -m user -a "name=deploy groups=sudo append=yes" -b6
7# Remove a user8ansible all -m user -a "name=olduser state=absent remove=yes" -b9
10# Create a group11ansible all -m group -a "name=developers state=present" -bCron Jobs
bash
1# Create a cron job2ansible all -m cron -a "name='daily backup' hour=2 minute=0 job='/opt/backup.sh'" -b3
4# Remove a cron job5ansible all -m cron -a "name='daily backup' state=absent" -bCommon Ad-Hoc Flags
bash
1-i INVENTORY # Specify inventory file or path2-m MODULE # Module to run (default: command)3-a "ARGS" # Module arguments4-b, --become # Run with privilege escalation (sudo)5-K, --ask-become-pass # Prompt for sudo password6-k, --ask-pass # Prompt for SSH password7-u USER # Remote user8-f FORKS # Number of parallel processes (default: 5)9-v, -vv, -vvv, -vvvv # Increasing verbosity levels10--limit HOST # Restrict to specific host(s)11-e "key=value" # Extra variables12-C, --check # Dry run (no changes)13-D, --diff # Show file diffs14--private-key FILE # SSH private key file15-t TAGS # Run only tagged tasks16--skip-tags TAGS # Skip tagged tasksPlaybook Execution
Running Playbooks
bash
1ansible-playbook playbook.yml # Run a playbook2ansible-playbook playbook.yml -i inventory.yml # With custom inventory3ansible-playbook playbook.yml -i staging -i production # Multiple inventories4ansible-playbook playbook.yml -l webservers # Limit to group/host5ansible-playbook playbook.yml -b # With sudo6ansible-playbook playbook.yml -b -K # With sudo, prompt password7ansible-playbook playbook.yml -u deploy # As specific user8ansible-playbook playbook.yml -e "env=staging version=2.1" # Extra variables9ansible-playbook playbook.yml -e @vars.yml # Extra variables from fileExecution Control
bash
1ansible-playbook playbook.yml -C # Dry run (check mode)2ansible-playbook playbook.yml -D # Show diffs for file changes3ansible-playbook playbook.yml -C -D # Dry run with diffs4ansible-playbook playbook.yml --step # Step through tasks one by one5ansible-playbook playbook.yml --start-at-task="Install nginx" # Start at specific task6ansible-playbook playbook.yml -t deploy # Run only tagged tasks7ansible-playbook playbook.yml --skip-tags tests # Skip tagged tasks8ansible-playbook playbook.yml -f 20 # Run with 20 forksSyntax & Debugging
bash
1ansible-playbook playbook.yml --syntax-check # Validate playbook syntax2ansible-playbook playbook.yml --list-tasks # List all tasks3ansible-playbook playbook.yml --list-hosts # List targeted hosts4ansible-playbook playbook.yml --list-tags # List all tags5ansible-playbook playbook.yml -v # Verbose output6ansible-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 file2ansible-vault edit secrets.yml # Edit encrypted file in-place3ansible-vault view secrets.yml # View encrypted file contents4ansible-vault encrypt existing.yml # Encrypt an existing file5ansible-vault decrypt secrets.yml # Decrypt a file permanently6ansible-vault rekey secrets.yml # Change encryption passwordEncrypting Strings
bash
1# Encrypt a single variable value2ansible-vault encrypt_string 'SuperSecret123' --name 'db_password'3
4# Encrypt from stdin5echo -n 'SuperSecret123' | ansible-vault encrypt_string --stdin-name 'db_password'Using Vault with Playbooks
bash
1# Prompt for vault password2ansible-playbook playbook.yml --ask-vault-pass3
4# Use vault password file5ansible-playbook playbook.yml --vault-password-file ~/.vault_pass6
7# Use vault ID (multiple vaults)8ansible-playbook playbook.yml --vault-id dev@~/.vault_pass_dev9ansible-playbook playbook.yml --vault-id prod@promptAnsible Galaxy (Roles & Collections)
Roles
bash
1ansible-galaxy role init my_role # Create role skeleton2ansible-galaxy role install geerlingguy.nginx # Install role from Galaxy3ansible-galaxy role install -r requirements.yml # Install roles from file4ansible-galaxy role list # List installed roles5ansible-galaxy role search elasticsearch # Search for roles6ansible-galaxy role search elasticsearch --author geerlingguy # Search by author7ansible-galaxy role remove geerlingguy.nginx # Remove installed role8ansible-galaxy role info geerlingguy.nginx # Show role infoCollections
bash
1ansible-galaxy collection init mynamespace.mycollection # Create collection skeleton2ansible-galaxy collection build # Build a collection tarball3ansible-galaxy collection install community.general # Install a collection4ansible-galaxy collection install -r requirements.yml # Install from requirements5ansible-galaxy collection list # List installed collections6ansible-galaxy collection verify community.general # Verify collection integrity7ansible-galaxy collection download community.general -p ./downloads # Download for offline installRequirements File
yaml
1# requirements.yml — define roles and collections to install2roles:3 - name: geerlingguy.nginx4 version: "3.2.0"5 - name: geerlingguy.docker6 - src: https://github.com/user/custom-role.git7 name: custom-role8
9collections:10 - name: community.general11 version: ">=5.0.0"12 - name: ansible.posixbash
1# Install all from requirements file2ansible-galaxy install -r requirements.yml3ansible-galaxy collection install -r requirements.ymlModule Documentation
Browse Module Docs
bash
1ansible-doc -l # List all available modules2ansible-doc -l | grep aws # Search module names3ansible-doc copy # Show full docs for a module4ansible-doc -s copy # Show snippet/example for a module5ansible-doc -t connection -l # List connection plugins6ansible-doc -t callback -l # List callback plugins7ansible-doc -t inventory -l # List inventory plugins8ansible-doc -t lookup -l # List lookup pluginsConfiguration Management
View & Manage Config
bash
1ansible-config view # Show current ansible.cfg contents2ansible-config dump # Dump all resolved settings (with sources)3ansible-config dump --only-changed # Show only non-default settings4ansible-config list # List all configurable settings with descriptions5ansible-config init --disabled > ansible.cfg # Generate sample config with all options commented6ansible-config init --disabled -t all > ansible.cfg # Include plugin-level settingsCommon ansible.cfg Settings
ini
1[defaults]2inventory = ./inventory3remote_user = deploy4private_key_file = ~/.ssh/id_ed255195host_key_checking = False6retry_files_enabled = False7forks = 208timeout = 309log_path = /var/log/ansible.log10roles_path = ./roles:/etc/ansible/roles11collections_path = ./collections12stdout_callback = yaml13callbacks_enabled = timer, profile_tasks14interpreter_python = auto_silent15
16[privilege_escalation]17become = True18become_method = sudo19become_user = root20become_ask_pass = False21
22[ssh_connection]23ssh_args = -o ControlMaster=auto -o ControlPersist=60s24pipelining = True25control_path_dir = ~/.ansible/cp26
27[inventory]28enable_plugins = host_list, script, auto, yaml, ini, tomlDebugging & Troubleshooting
Connectivity Testing
bash
1ansible all -m ping # Basic SSH + Python check2ansible all -m ping -vvvv # Debug connection issues3ansible all -m raw -a "hostname" # Test without Python on remote4ansible all -m setup -a "filter=ansible_distribution" # Check remote OS infoCommon Debug Commands
bash
1# Check which hosts match a pattern2ansible webservers --list-hosts3
4# Test playbook without making changes5ansible-playbook playbook.yml -C -D6
7# Run with maximum verbosity8ansible-playbook playbook.yml -vvvv9
10# Check playbook syntax11ansible-playbook playbook.yml --syntax-check12
13# Show facts for a host14ansible myhost -m setup15ansible myhost -m setup -a "filter=ansible_memory_mb"16ansible myhost -m setup --tree /tmp/facts/ # Save facts to filesTroubleshooting Checklist
bash
1# SSH connection failing?2ansible all -m ping -vvvv # Check SSH error details3ssh -o StrictHostKeyChecking=no user@host # Test SSH manually4
5# Module not found?6ansible-doc -l | grep <module_name> # Verify module exists7ansible --version # Check Ansible version8
9# Privilege escalation issues?10ansible all -m command -a "whoami" -b # Test sudo access11ansible all -m command -a "sudo -l" -b # Check sudo permissions12
13# Slow execution?14# Enable pipelining in ansible.cfg:15# [ssh_connection]16# pipelining = True17
18# Python not found on remote?19ansible all -m raw -a "which python3" # Locate Python20# Set in inventory: ansible_python_interpreter=/usr/bin/python3Ansible Pull
bash
1# Pull and run playbook from a git repository2ansible-pull -U https://github.com/user/repo.git playbook.yml3
4# With checkout branch and inventory5ansible-pull -U https://github.com/user/repo.git -C main -i localhost, playbook.yml6
7# Run on a schedule via cron8ansible-pull -U https://github.com/user/repo.git -o -s 60 playbook.yml9# -o = only run if repo has changed, -s = random sleep before executionAnsible Console (Interactive REPL)
bash
1ansible-console all -i inventory.yml # Start interactive console2ansible-console webservers -b # Console with sudo3
4# Inside the console:5# cd webservers # Switch to a group6# ping # Run ping module7# command uptime # Run command8# copy src=/tmp/file dest=/tmp/file # Copy a file9# shell df -h # Run shell command10# exit # Quit consoleUseful One-Liners
bash
1# Check disk space on all servers2ansible all -a "df -h" -b3
4# Check uptime on all servers5ansible all -a "uptime"6
7# Check memory usage8ansible all -m shell -a "free -m"9
10# Reboot all webservers11ansible webservers -m reboot -b12
13# Kill a process on all hosts14ansible all -m shell -a "pkill -f my_process" -b15
16# Check if a service is running17ansible all -m shell -a "systemctl is-active nginx"18
19# Gather hostnames of all machines20ansible all -m command -a "hostname -f"21
22# Check which hosts are reachable23ansible all -m ping --one-line24
25# Deploy SSH key to all hosts26ansible all -m authorized_key -a "user=deploy key='{{ lookup('file','~/.ssh/id_ed25519.pub') }}'" -b27
28# Sync a directory29ansible all -m synchronize -a "src=/local/dir/ dest=/remote/dir/"