# ansible / architecture / roles
Organize Automation with Ansible Roles
Writing everything in one massive playbook becomes impossible to maintain. An Ansible Role is a predefined directory structure that splits your code into reusable, modular parts.
Why Use Roles?
Roles allow you to organize code, reuse tasks across multiple different projects, and keep your repositories clean. Instead of one 5,000-line playbook, you have focused, independent modules.
Imagine a massive Hotel Kitchen. You don't have one chef trying to do everything. You have different sections: a Cooking team, a Cleaning team, and a Billing team. In Ansible, each of these sections is a Role.
The Advantages
• Organize code: Everything has a specific place.
• Reuse tasks: Build an "nginx" role once, use it everywhere.
• Maintain easily: Fix a bug in a role, and all playbooks using it are instantly fixed.
The Role Structure
When you create a role, Ansible expects a very specific directory layout. Each folder serves a distinct, isolated purpose.
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 வேலை இங்க தான் நடக்கும் (The main work happens here)
Contains the actual tasks to execute. The entry file must bemain.yml. - handlers/
Used specifically for restarting or reloading services. They are only executed when explicitly called via
notify. - templates/
Stores dynamic files (Jinja2 templates, typically
.j2extension). - files/
Stores static files that require a direct copy with no variable substitution.
- vars/
Contains high-priority variables specific to this role.
- defaults/
Contains low-priority default variables. If a user doesn’t override the variable in their playbook, this value is used safely.
- meta/
Defines role dependencies (e.g., if this role requires a `common` role to run first).
The Full Project Layout
my-ansible-project/ ├── inventory ├── playbook.yml ├── roles/ │ ├── webserver/ │ ├── database/ │ └── common/ ├── group_vars/ └── host_vars/
How Everything Works Together
- 1
You execute the playbook.yml (The instruction manual).
- 2
The playbook maps the inventory (target servers) to the specified roles.
- 3
The role executes its tasks/main.yml (The setup kit).
- 4
Tasks pull data from group_vars, host_vars, or the role's own vars.
- 5
If configuration files change, tasks notify the handlers to restart services.
Key Concepts Reference
| Concept | Meaning | Analogy |
|---|---|---|
| Playbook | The Main Controller | The Instruction Manual / The Manager |
| Role | Reusable Automation Module | The Setup Kit / A Kitchen Department |
| Tasks | The Actual Work | The individual cooking steps |
| Handlers | Triggered Actions | Cleaning the station only when told to |
Role = Structured, reusable automation. It helps structure massive configurations, organizes large projects safely, and makes DevOps life easy 😄.