Chapter #9: Ansible Roles
This is the ninth chapter of RHCE Ansible EX 294 exam preparation series. You'll understand how roles are structured in Ansible. You'll also learn to use ready-made roles from Ansible Galaxy and create your own custom Ansible roles.
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!
A Linux sysadmin who likes to code for fun. I have authored Learn Linux Quickly book to help people learn Linux easily. I also like watching the NBA and going for a cruise with my skateboard.