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
| Command | Action / Purpose |
|---|---|
ansible all -m ping -i hosts | Run ad-hoc ping module test on all inventory hosts |
ansible-playbook site.yml -i hosts | Execute playbook against target inventory |
ansible-playbook site.yml --check | Run dry-run simulation mode (check mode) |
ansible-playbook site.yml --limit webservers | Limit playbook execution to specific host group |
ansible-vault encrypt secrets.yml | Encrypt sensitive playbook variables file with password |
ansible-galaxy role init my_role | Scaffold 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
notifyactually triggers a state change (changed: true).
[!TIP] Use
ansible-playbook --check --diffto inspect exact line-by-line configuration changes before applying them on production servers.