๐ญ Ansible Roles & Project Structure
๐ฏ What is an Ansible Role?
An Ansible Role is a predefined structure used to organize your automation.
๐ Simple meaning:
Instead of writing everything in one big playbook, we split into reusable parts
๐ฆ Real-Life Example
Think like this:
๐ฝ๏ธ Hotel Kitchen
- Chef (Playbook)
- Different sections:
* ๐ Cooking team
* ๐งน Cleaning team
* ๐งพ Billing team
Each section = Role
๐ก Easy Definition
- Role = Reusable automation module
- Helps to:
* Organize code
* Reuse tasks
* Maintain easily
๐ Role Structure (Important)
When you create a role, it follows a standard folder structure:
my-role/ โ โโโ tasks/ โ โโโ main.yml โ โโโ handlers/ โ โโโ main.yml โ โโโ templates/ โ โโโ files/ โ โโโ vars/ โ โโโ main.yml โ โโโ defaults/ โ โโโ main.yml โ โโโ meta/ โ โโโ main.yml
๐ Folder Explanation (Very Important ๐ฅ)
๐ tasks/
๐ Main เฎตเฏเฎฒเฏ เฎเฎเฏเฎ เฎคเฎพเฎฉเฏ เฎจเฎเฎเฏเฎเฏเฎฎเฏ
- Contains actual tasks
- Entry file:
main.yml
Example:
- name: Install nginx
apt:
name: nginx
state: present
๐ handlers/
๐ Used for restart/reload services
Example:
- name: restart nginx
service:
name: nginx
state: restarted
Called only when needed (notify)
๐ templates/
๐ Dynamic files (Jinja2 templates)
Example:
- nginx.conf.j2
๐ files/
๐ Static files
- No variables
- Direct copy
๐ vars/
๐ Variables (high priority)
port: 80
โ๏ธ defaults/
๐ Default variables (low priority)
port: 8080
๐ If user doesnโt override โ this value used
๐ meta/
๐ Role dependencies
Example:
dependencies: - role: common
๐งฑ Project Structure (Full Project)
Now letโs see how a real Ansible project looks
my-ansible-project/ โ โโโ inventory โ โโโ playbook.yml โ โโโ roles/ โ โโโ webserver/ โ โโโ database/ โ โโโ common/ โ โโโ group_vars/ โโโ host_vars/
๐ Explanation
๐ inventory
๐ Target servers list
[web] 192.168.1.10
โถ๏ธ playbook.yml
๐ Main entry point
Example:
- hosts: web
roles:
- webserver
๐ญ roles/
๐ Contains all roles
- webserver
- database
- common
๐งพ group_vars/
๐ Variables for group
๐ฅ๏ธ host_vars/
๐ Variables per server
๐ How Everything Works Together
1. You run playbook
2. Playbook calls role
3. Role runs tasks
4. Tasks use variables
5. Handlers trigger when needed
๐ฐ Real-Life Example (Like your Docker one)
Think of building a website server
- Role = Setup kit
- tasks = steps (install nginx, copy config)
- templates = config file with variables
- handlers = restart nginx
- playbook = instruction manual
๐ฅ Key Difference (Like Image vs Container style)
| Concept | Meaning |
| -------- | ----------------- |
| Playbook | Main controller |
| Role | Reusable module |
| Tasks | Actual work |
| Handlers | Triggered actions |
๐ง Short Summary
- Role = structured, reusable automation
- Helps large projects
- Makes DevOps life easy ๐