An Ansible role is a reusable, self-contained unit of automation that is used to organize and manage tasks, variables, files, templates, and handlers in a structured way.
Roles help to encapsulate and modularize the logic and configuration needed to manage a particular system or application component.
This modular approach promotes reusability, maintainability, and consistency across different playbooks and environments.
The main list of actions that the role performs.
Tasks that are triggered by changes in other tasks, typically used for actions like restarting services.
Static files that need to be transferred to managed hosts.
Jinja2 templates that can be rendered and transferred to managed hosts.
Variables that are used within the role.
Default variables for the role, which can be overridden.
Metadata about the role, including dependencies on other roles.
Custom modules or plugins used within the role.
Default module parameters for the role.
Custom lookup plugins for the role.
An Ansible role follows a specific directory structure:
<role_name>/
├── defaults/
│ └── main.yml
├── files/
├── handlers/
│ └── main.yml
├── meta/
│ └── main.yml
├── tasks/
│ └── main.yml
├── templates/
├── vars/
└── main.yml
Roles allow you to break down complex playbooks into smaller, reusable components. Each role handles a specific part of the configuration or setup.
Once created, roles can be reused across different playbooks and projects. This saves time and effort in writing redundant code.
By organizing related tasks into roles, it becomes easier to manage and maintain the code. Changes can be made in one place and applied consistently wherever the role is used.
Roles make playbooks cleaner and easier to read by abstracting away the details into logically named roles.
Roles facilitate collaboration among team members by allowing them to work on different parts of the infrastructure independently.
Using roles ensures that the same setup and configuration procedures are applied uniformly across multiple environments, reducing the risk of configuration drift.