What are roles?

Ansible roles come in handy when we need to arrange a set of related tasks, variables, handlers, and even files into a structured format. Roles are also essential organizational and modular units for our automation tasks. Using roles makes our configuration maintainable, and it makes collaboration easier. We can isolate different functionalities, like the setup of databases, web servers, or load balancers, into different roles. This allows individual teams or team members to work on each component independently. Moreover, roles encourage reusability as we reference a single role in several playbooks without having to rewrite the specific tasks.

Defining roles allows us to separate concerns and run specific tasks or playbooks as per our needs instead of bundling the entire infrastructure configuration into a single file or component.

A role is usually a combination of the following components:

  • Tasks: The core automation steps that we want to execute.
  • Variables: The parameters that we can use to make the tasks in our role dynamic.
  • Templates: Jinja2A fast, expressive, extensible templating engine that is used in Ansible templates that we can use to generate configuration files.
  • Handlers: Actions that run when notified by specific tasks.
  • Files: Static files that we want to copy to the managed nodes.

While the aforementioned components are essential, it’s also important to always include appropriate documentation in our role directory, for example:

Get hands-on with 1200+ tech skills courses.