Ansible Playbook Cheat Sheet

Quick reference guide for Ansible: Playbook syntax, inventory files, roles structure, and CLI modules.

CI/CD & DevOps
ansible
playbook
devops

Ansible is an open-source IT automation tool that automates provisioning, configuration management, application deployment, and intra-service orchestration.

Inventory File Formats (`hosts`)

ini
# INI Inventory format
[webservers]
web1.example.com ansible_user=ubuntu
web2.example.com ansible_user=ubuntu

[dbservers]
db1.example.com ansible_host=192.168.1.50

[production:children]
webservers
dbservers

Playbook Structure Example

yaml
---
- name: Configure Webservers
  hosts: webservers
  become: true # Execute tasks with sudo privileges

  vars:
    http_port: 80
    max_clients: 200

  tasks:
    - name: Ensure Nginx is installed
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true

    - name: Copy Nginx Config Template
      ansible.builtin.template:
        src: templates/nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        mode: "0644"
      notify: Restart Nginx

  handlers:
    - name: Restart Nginx
      ansible.builtin.service:
        name: nginx
        state: restarted

Essential `ansible` & `ansible-playbook` CLI Commands

Table
CommandAction / Purpose
ansible all -m ping -i hostsRun ad-hoc ping module test on all inventory hosts
ansible-playbook site.yml -i hostsExecute playbook against target inventory
ansible-playbook site.yml --checkRun dry-run simulation mode (check mode)
ansible-playbook site.yml --limit webserversLimit playbook execution to specific host group
ansible-vault encrypt secrets.ymlEncrypt sensitive playbook variables file with password
ansible-galaxy role init my_roleScaffold new Ansible role directory structure

Common Pitfalls & Tips

[!WARNING] Task handlers only execute once at the end of a play run, and only if a task using notify actually triggers a state change (changed: true).

[!TIP] Use ansible-playbook --check --diff to inspect exact line-by-line configuration changes before applying them on production servers.