📋 Cheat Sheets

Ansible Cheat Sheet — Playbooks, Modules, and Common Tasks


Click any item to expand the explanation and examples.

⚡ Ad-hoc Commands

ansible <hosts> -m <module> basics
# 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

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

# Specify inventory file
ansible all -i inventory.ini -m ping

📜 Playbooks

Basic playbook structure playbook
# deploy.yml
---
- name: Deploy web application
  hosts: webservers
  become: true
  vars:
    app_port: 3000

  tasks:
    - name: Install Node.js
      apt:
        name: nodejs
        state: present

    - name: Copy app files
      copy:
        src: ./app/
        dest: /opt/myapp/

    - name: Start application
      systemd:
        name: myapp
        state: started
        enabled: true
ansible-playbook deploy.yml
ansible-playbook deploy.yml --check    # Dry run
ansible-playbook deploy.yml --diff     # Show changes
ansible-playbook deploy.yml -l web01   # Limit to specific host
Variables and templates playbook
# Playbook vars
vars:
  db_host: localhost
  db_port: 5432

# Vars from file
vars_files:
  - vars/production.yml

# Use in tasks
tasks:
  - name: Configure app
    template:
      src: config.j2
      dest: /etc/myapp/config.yml

# config.j2 (Jinja2 template)
# database:
#   host: {{ db_host }}
#   port: {{ db_port }}
Handlers and conditionals playbook
tasks:
  - name: Update nginx config
    template:
      src: nginx.conf.j2
      dest: /etc/nginx/nginx.conf
    notify: restart nginx

  - name: Install package (Debian only)
    apt:
      name: nginx
    when: ansible_os_family == "Debian"

  - name: Install package (RedHat only)
    yum:
      name: nginx
    when: ansible_os_family == "RedHat"

handlers:
  - name: restart nginx
    service:
      name: nginx
      state: restarted
Loops playbook
tasks:
  - name: Install packages
    apt:
      name: "{{ item }}"
      state: present
    loop:
      - nginx
      - postgresql
      - redis

  - name: Create users
    user:
      name: "{{ item.name }}"
      groups: "{{ item.groups }}"
    loop:
      - { name: alice, groups: admin }
      - { name: bob, groups: developers }

📦 Inventory

Inventory file formats inventory
# inventory.ini
[webservers]
web01 ansible_host=192.168.1.10
web02 ansible_host=192.168.1.11

[databases]
db01 ansible_host=192.168.1.20

[all:vars]
ansible_user=deploy
ansible_ssh_private_key_file=~/.ssh/deploy_key
# inventory.yml
all:
  children:
    webservers:
      hosts:
        web01:
          ansible_host: 192.168.1.10
        web02:
          ansible_host: 192.168.1.11
    databases:
      hosts:
        db01:
          ansible_host: 192.168.1.20

See also: SSH cheat sheet | YAML cheat sheet | Terraform cheat sheet