Skip to main content

playbooks-and-roles

๐Ÿ“˜ Playbooks & Roles (Based on Your Project Structure)โ€‹

Your Ansible project is well-organized using roles and playbooks. Below is a tailored explanation of how Playbooks and Roles work with examples taken directly from your directory structure.


๐Ÿ“‚ Project Structure Overviewโ€‹

D:\aops
โ”œโ”€โ”€ playbooks/ # Main playbook files
โ”‚ โ””โ”€โ”€ report/
โ”‚ โ””โ”€โ”€ go-access/
โ”œโ”€โ”€ roles/ # All role logic here
โ”‚ โ”œโ”€โ”€ apache/
โ”‚ โ”œโ”€โ”€ goaccess-install/
โ”‚ โ”œโ”€โ”€ goaccess-report/
โ”‚ โ”œโ”€โ”€ nginx/
โ”‚ โ”œโ”€โ”€ node_exporter/
โ”‚ โ”œโ”€โ”€ promtail/
โ”‚ โ”œโ”€โ”€ report/
โ”‚ โ”œโ”€โ”€ ssh-key-reset/
โ”‚ โ”œโ”€โ”€ tailscale/
โ”‚ โ””โ”€โ”€ utilities/

๐Ÿง  What is a Playbook?โ€‹

A playbook is a YAML file that tells Ansible what tasks to run and on which hosts. Think of it as the automation blueprint.

๐Ÿงพ Example: playbooks/report/go-access/main.ymlโ€‹

---
- name: Generate GoAccess Report
hosts: webservers
become: true

roles:
- goaccess-install
- goaccess-report

This playbook runs two roles on the webservers group: one to install GoAccess, and another to generate a report.


โš™๏ธ What is a Role?โ€‹

A role is a pre-defined structure for organizing related Ansible content like tasks, templates, handlers, etc.

๐Ÿ“ Role Example: roles/goaccess-reportโ€‹

roles/goaccess-report/
โ”œโ”€โ”€ tasks/
โ”‚ โ””โ”€โ”€ main.yml
โ””โ”€โ”€ templates/
โ””โ”€โ”€ goaccess.html.j2

๐Ÿงพ tasks/main.ymlโ€‹

---
- name: Generate GoAccess HTML report
command: >
goaccess /var/log/nginx/access.log \
-o /var/www/html/report.html \
--log-format=COMBINED

๐Ÿ“ Role Example: roles/apacheโ€‹

roles/apache/
โ”œโ”€โ”€ tasks/
โ”‚ โ””โ”€โ”€ main.yml
โ”œโ”€โ”€ handlers/
โ”‚ โ””โ”€โ”€ main.yml

๐Ÿงพ tasks/main.ymlโ€‹

---
- name: Install Apache
apt:
name: apache2
state: present
notify: Restart Apache

๐Ÿ” handlers/main.ymlโ€‹

---
- name: Restart Apache
service:
name: apache2
state: restarted

๐Ÿš€ Using Roles in a Playbookโ€‹

- name: Install and configure Apache
hosts: webservers
become: true

roles:
- apache

This makes your automation clean, modular, and maintainable.


โš ๏ธ Note on Nested Role Pathโ€‹

๐Ÿ“ roles/playbooks/roles/nginx/ โ€” This looks like a nested role and may not work unless explicitly included. It's better to keep roles directly under roles/.


โœ… Summaryโ€‹

ComponentPurpose
PlaybooksDefine orchestration and logic per host/group
RolesModular units (Apache, GoAccess, etc.)
InventoryDefines target systems
VarsCentralized variable management

๐Ÿ“Œ With this setup, you can easily scale automation by plugging roles into playbooks as needed. Clean, simple, and powerful!