So far you have been creating Ansible playbooks to automate a certain task on your managed nodes. There is a huge chance that someone else has already designed an Ansible solution to the problem/task you are trying to solve and that’s exactly what Ansible roles is all about.
In this tutorial, you will understand how roles are structured in Ansible. You will also learn to use ready-made roles from Ansible Galaxy.
Furthermore, you will learn to create your own custom Ansible roles.
Before you proceed with this tutorial, please refer to other chapters in the Ansible tutorial series for better understanding of various topics mentioned here.
Understanding Ansible Roles
An Ansible role is a collection of files, tasks, templates, variables, and handlers that together serve a certain purpose like configuring a service. Roles allows you to easily re-use code and share Ansible solutions with other users which makes working with large environments more manageable.
Role Directory Structure
A typical Ansible role follows a defined directory structure that is usually composed of the following directories:
- defaults: Contains default variables for the role that are meant to be easily overwritten.
- vars: Contains standard variables for the role that are not meant to be overwritten in your playbook.
- tasks: Contains a set of tasks to be performed by the role.
- handlers: Contains a set of handlers to be used in the role.
- templates: Contains the Jinja2 templates to be used in the role.
- files: Contains static files are needed from the role tasks.
- tests: May contain an optional inventory file, as well as test.yml playbook that can be used to test the role.
- meta: Contains role metadata such as author information, license, dependencies, etc.
Keep in mind that a role may have all the aforementioned directories or just a subset of them. In fact, you can define an empty role that has zero directories, although won’t be useful!