Ansible Automation

Organize Automation with Ansible Roles

Lesson 9 of 12 · 9 min · Intermediate

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.

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.

Directory Tree
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 be main.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 .j2 extension).
  • 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/
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

ConceptMeaningAnalogy
PlaybookThe Main ControllerThe Instruction Manual / The Manager
RoleReusable Automation ModuleThe Setup Kit / A Kitchen Department
TasksThe Actual WorkThe individual cooking steps
HandlersTriggered ActionsCleaning the station only when told to