Playbooks & Roles
Organize automation into playbooks, tasks, handlers, and reusable roles.
Theory
A playbook is a YAML file mapping plays (host groups) to tasks (module calls). Tasks run top to bottom. Supporting pieces:
- Variables — parameterize plays; templates (Jinja2) render config files
- Handlers — tasks that run only when notified by a change (e.g. restart a service after its config changes)
- Roles — a standard directory structure (
tasks/,templates/,vars/,handlers/) that packages reusable automation, shareable via Ansible Galaxy
Roles are the unit of reuse and organization for anything non-trivial.
Real-World Example
- name: Configure web servers
hosts: webservers
become: true
tasks:
- name: Install nginx
ansible.builtin.apt:
name: nginx
state: present
- name: Deploy site config
ansible.builtin.template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart nginx
handlers:
- name: Restart nginx
ansible.builtin.service:
name: nginx
state: restarted Hands-On Exercise
- Write a play that installs a package and deploys a templated config file.
- Add a handler that restarts a service only when its config changes.
- Explain the standard directory structure of a role.
- Describe how Ansible Galaxy helps reuse community roles.
Cheat Sheet▾
| Element | Role |
|---|---|
| Play | Maps hosts → tasks |
| Task | A single module call |
| Variables | Parameterize plays |
| Template | Jinja2-rendered file |
| Handler | Runs on notify (e.g. restart) |
| Role | Reusable structured automation |
| Galaxy | Share/install roles |
Common Interview Questions▾
What is an Ansible handler and when does it run?
A task that runs only when notified by another task that reported a change — used for actions like restarting a service after its configuration file changed.
What is a role?
A standardized, reusable bundle of tasks, templates, variables, and handlers in a defined directory structure, making automation modular and shareable via Galaxy.
Official Documentation
📝 My notes on this topic
Auto-saves as you type