Playbooks & Roles

💤0
Lv 10 XP
← 📜 Infrastructure as Code · Ansible

Playbooks & Roles

Intermediate ⭐ 80 XP ⏱ 18 min #ansible#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
  1. Write a play that installs a package and deploys a templated config file.
  2. Add a handler that restarts a service only when its config changes.
  3. Explain the standard directory structure of a role.
  4. Describe how Ansible Galaxy helps reuse community roles.
🧾Cheat Sheet
ElementRole
PlayMaps hosts → tasks
TaskA single module call
VariablesParameterize plays
TemplateJinja2-rendered file
HandlerRuns on notify (e.g. restart)
RoleReusable structured automation
GalaxyShare/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