AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

Ansible Cheat Sheet: Quick Reference Commands & Syntax (2026)

By Luca Berton · Published 2024-01-01 · Category: installation

Ansible cheat sheet with essential commands, playbook syntax, module examples, and configuration reference. Quick reference for daily Ansible use.

Ansible Cheat Sheet: Quick Reference Commands & Syntax (2026)

Ansible Cheat Sheet

A quick reference for the most commonly used Ansible commands, modules, and playbook patterns. Bookmark this page for daily use.

See also: Ansible Modules List: 50 Most Used Modules Quick Reference

Essential Commands

Ad-Hoc Commands

# Ping all hosts
ansible all -m ping

# Run a command ansible webservers -m shell -a "uptime"

# Copy a file ansible all -m copy -a "src=file.txt dest=/tmp/file.txt"

# Install a package ansible all -m apt -a "name=nginx state=present" --become

# Gather facts ansible hostname -m setup

# List hosts in a group ansible webservers --list-hosts

Playbook Commands

# Run a playbook
ansible-playbook playbook.yml

# Dry run ansible-playbook playbook.yml --check --diff

# Limit to hosts ansible-playbook playbook.yml --limit webserver1

# Extra variables ansible-playbook playbook.yml -e "env=production"

# Tags ansible-playbook playbook.yml --tags "deploy,config" ansible-playbook playbook.yml --skip-tags "debug"

# Start at a specific task ansible-playbook playbook.yml --start-at-task "Install nginx"

# Step through tasks ansible-playbook playbook.yml --step

# Verbose output ansible-playbook playbook.yml -v # basic ansible-playbook playbook.yml -vvv # detailed ansible-playbook playbook.yml -vvvv # connection debug

Inventory Commands

# Use custom inventory
ansible-playbook -i inventory.ini playbook.yml

# Graph inventory ansible-inventory --graph

# List inventory as JSON ansible-inventory --list

Vault Commands

# Create encrypted file
ansible-vault create secrets.yml

# Encrypt existing file ansible-vault encrypt vars.yml

# Decrypt file ansible-vault decrypt vars.yml

# Edit encrypted file ansible-vault edit secrets.yml

# Encrypt a string ansible-vault encrypt_string 'secret_value' --name 'db_password'

# Run playbook with vault ansible-playbook playbook.yml --ask-vault-pass ansible-playbook playbook.yml --vault-password-file ~/.vault_pass

Galaxy Commands

# Install a role
ansible-galaxy role install geerlingguy.docker

# Install a collection ansible-galaxy collection install community.general

# Install from requirements ansible-galaxy install -r requirements.yml

# List installed roles ansible-galaxy role list

# Create role skeleton ansible-galaxy role init my_role

Playbook Syntax

Basic Structure

---
- name: Play name
  hosts: target_group
  become: true
  vars:
    variable_name: value
  tasks:
    - name: Task name
      module_name:
        param1: value1
        param2: value2

Variables

# In playbook
vars:
  app_port: 8080

# From file vars_files: - vars/main.yml

# Registered - command: whoami register: result - debug: var=result.stdout

# Facts "{{ ansible_hostname }}" "{{ ansible_default_ipv4.address }}" "{{ ansible_distribution }}"

Conditionals

when: ansible_os_family == "Debian"
when: result.rc == 0
when: my_var is defined
when: my_var | bool
when: inventory_hostname in groups['webservers']
when:
  - condition1
  - condition2  # AND logic

Loops

# Simple loop
loop:
  - item1
  - item2

# Dict loop loop: - { name: 'user1', groups: 'wheel' } - { name: 'user2', groups: 'users' }

# With index loop: "{{ items }}" loop_control: index_var: idx label: "{{ item.name }}"

Handlers

tasks:
  - name: Update config
    template: src=app.conf.j2 dest=/etc/app.conf
    notify: Restart app

handlers: - name: Restart app service: name=myapp state=restarted

Error Handling

# Ignore errors
- command: /opt/app/check
  ignore_errors: true

# Block/rescue/always - block: - name: Try this command: /opt/risky-command rescue: - name: Handle failure debug: msg="It failed" always: - name: Always do this debug: msg="Cleanup"

# Changed when - shell: cat /etc/hostname changed_when: false

# Failed when - command: /opt/check register: result failed_when: "'ERROR' in result.stdout"

See also: Ansible Documentation: Complete Reference & Quick Start Guide (2026)

Most Used Modules

| Module | Purpose | Example | |--------|---------|---------| | apt/dnf/yum | Package mgmt | apt: name=nginx state=present | | copy | Copy files | copy: src=f.txt dest=/tmp/f.txt | | template | Jinja2 templates | template: src=app.j2 dest=/etc/app.conf | | file | File/dir mgmt | file: path=/tmp/dir state=directory | | service | Service mgmt | service: name=nginx state=started | | user | User mgmt | user: name=deploy shell=/bin/bash | | command | Run commands | command: ls /tmp | | shell | Run shell cmd | shell: echo $HOME \| tee /tmp/out | | debug | Print info | debug: msg="Hello" | | lineinfile | Edit lines | lineinfile: path=/etc/hosts line="..." | | get_url | Download file | get_url: url=... dest=/tmp/file | | git | Git operations | git: repo=... dest=/opt/app | | cron | Cron jobs | cron: name=backup job="/opt/backup.sh" | | stat | File info | stat: path=/etc/foo | | assert | Validate | assert: that: result.rc == 0 |

Jinja2 Filters

# String
"{{ name | upper }}"
"{{ name | lower }}"
"{{ name | replace('old','new') }}"
"{{ name | regex_replace('pattern','replace') }}"
"{{ name | default('fallback') }}"

# List "{{ list | length }}" "{{ list | first }}" "{{ list | last }}" "{{ list | join(',') }}" "{{ list | unique }}" "{{ list | sort }}" "{{ list | selectattr('key','equalto','val') }}"

# Math "{{ num | int }}" "{{ num | round }}"

# Path "{{ path | basename }}" "{{ path | dirname }}"

# Type conversion "{{ var | to_json }}" "{{ var | to_yaml }}" "{{ var | from_json }}" "{{ var | bool }}"

See also: Ansible Documentation: Complete Guide to Finding and Using Official Docs

Directory Structure (Best Practice)

project/
├── ansible.cfg
├── inventory/
│   ├── production
│   └── staging
├── group_vars/
│   ├── all.yml
│   └── webservers.yml
├── host_vars/
│   └── web1.yml
├── roles/
│   └── webserver/
│       ├── tasks/main.yml
│       ├── handlers/main.yml
│       ├── templates/
│       ├── files/
│       ├── vars/main.yml
│       └── defaults/main.yml
├── playbooks/
│   ├── site.yml
│   └── deploy.yml
└── requirements.yml

FAQ

What is the difference between command and shell modules?

The command module executes commands directly without a shell, so shell operators like |, >, & don't work. The shell module runs commands through /bin/sh, supporting all shell features.

How do I check if a file exists in Ansible?

Use the stat module: stat: path=/etc/myfile then check result.stat.exists in a when condition.

How do I run a task only once across all hosts?

Use run_once: true on the task.

Conclusion

Keep this cheat sheet handy for your daily Ansible work. For detailed tutorials on each topic, visit AnsiblePilot.

Ad-Hoc Commands

# Ping all hosts
ansible all -m ping

# Run command ansible webservers -m command -a "uptime"

# Copy file ansible all -m copy -a "src=file.txt dest=/tmp/file.txt"

# Install package ansible all -m apt -a "name=nginx state=present" -b

# Restart service ansible all -m service -a "name=nginx state=restarted" -b

# Gather facts ansible web1 -m setup

# Check disk space ansible all -a "df -h" --become

Playbook Structure

---
- name: My Playbook
  hosts: webservers
  become: true
  vars:
    app_port: 8080
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
    - name: Start nginx
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true
  handlers:
    - name: restart nginx
      service: { name: nginx, state: restarted }

Essential Commands

# Run playbook
ansible-playbook site.yml

# Check syntax ansible-playbook site.yml --syntax-check

# Dry run (check mode) ansible-playbook site.yml --check

# Diff mode (show changes) ansible-playbook site.yml --diff

# Limit to hosts ansible-playbook site.yml --limit web1

# Extra variables ansible-playbook site.yml -e "version=2.0"

# Tags ansible-playbook site.yml --tags deploy ansible-playbook site.yml --skip-tags test

# Verbose ansible-playbook site.yml -v # basic ansible-playbook site.yml -vvv # debug

# Step through tasks ansible-playbook site.yml --step

Inventory

# inventory.ini
[webservers]
web1 ansible_host=10.0.1.10
web2 ansible_host=10.0.1.11

[dbservers] db1 ansible_host=10.0.2.10

[all:vars] ansible_user=deploy ansible_become=true

Variables Priority (Low → High)

1. role defaults
2. inventory group_vars
3. inventory host_vars
4. playbook group_vars
5. playbook host_vars
6. play vars
7. play vars_prompt
8. play vars_files
9. registered vars
10. set_facts
11. role vars
12. block vars
13. task vars
14. extra vars (-e)  ← HIGHEST

Common Modules

# Files
- copy: { src: f.txt, dest: /tmp/f.txt }
- template: { src: t.j2, dest: /etc/config }
- file: { path: /opt/dir, state: directory }
- lineinfile: { path: /etc/conf, line: "key=val" }
- get_url: { url: "https://...", dest: /tmp/ }

# Packages - apt: { name: nginx, state: present } - yum: { name: httpd, state: latest } - pip: { name: flask, state: present }

# Services - service: { name: nginx, state: started, enabled: true } - systemd: { name: app, state: restarted, daemon_reload: true }

# Users - user: { name: deploy, shell: /bin/bash } - authorized_key: { user: deploy, key: "{{ ssh_key }}" }

# Commands - command: /opt/script.sh - shell: cat file | grep pattern - script: scripts/setup.sh

Conditionals & Loops

# When
- apt: { name: nginx }
  when: ansible_os_family == "Debian"

# Loop - user: { name: "{{ item }}" } loop: [alice, bob, charlie]

# Loop with dict - user: name: "{{ item.name }}" uid: "{{ item.uid }}" loop: - { name: alice, uid: 1001 } - { name: bob, uid: 1002 }

# Register + conditional - command: cat /etc/os-release register: os_info - debug: msg="Ubuntu!" when: "'Ubuntu' in os_info.stdout"

Jinja2 Filters

# String
"{{ name | upper }}"
"{{ name | lower }}"
"{{ name | replace('old', 'new') }}"
"{{ name | default('none') }}"

# List "{{ list | join(',') }}" "{{ list | unique }}" "{{ list | sort }}" "{{ list | length }}" "{{ list | first }}" "{{ list | last }}"

# Dict "{{ dict | dict2items }}" "{{ items | items2dict }}" "{{ dict1 | combine(dict2) }}"

# Type "{{ var | int }}" "{{ var | bool }}" "{{ var | to_json }}" "{{ var | to_yaml }}" "{{ var | from_json }}"

# Path "{{ path | basename }}" "{{ path | dirname }}" "{{ path | expanduser }}"

# Hash "{{ pass | password_hash('sha512') }}" "{{ data | hash('md5') }}"

Vault

# Encrypt file
ansible-vault encrypt secrets.yml

# Decrypt ansible-vault decrypt secrets.yml

# Edit encrypted file ansible-vault edit secrets.yml

# Run with vault ansible-playbook site.yml --ask-vault-pass ansible-playbook site.yml --vault-password-file .vault_pass

FAQ

What's the difference between import and include?

import_ is static (processed at parse time). include_ is dynamic (processed at runtime). Use import for fixed structure, include for conditional inclusion.

How do I debug variables?

- debug: var=my_variable
- debug: msg="{{ my_variable | type_debug }}"

How do I run a task on localhost?

- debug: msg="local task"
  delegate_to: localhost
  # or connection: local

Related Articles

Ansible Galaxy CLI cheatsheetwhitespace control in Jinja2 for AnsibleAnsible loop_control GuideAnsible JSON Conversion Guideidempotent restarts via Ansible handlers

Category: installation

Browse all Ansible tutorials · AnsiblePilot Home