Kubernetes, Infrastructure and Ops Book Bundle
Learn more
Apr 23, 2021 11 min read

RHCE Ansible Series #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:

  1. defaults: Contains default variables for the role that are meant to be easily overwritten.
  2. vars: Contains standard variables for the role that are not meant to be overwritten in your playbook.
  3. tasks: Contains a set of tasks to be performed by the role.
  4. handlers: Contains a set of handlers to be used in the role.
  5. templates: Contains the Jinja2 templates to be used in the role.
  6. files: Contains static files are needed from the role tasks.
  7. tests: May contain an optional inventory file, as well as test.yml playbook that can be used to test the role.
  8. 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!

Great! You’ve successfully signed up.
Welcome back! You've successfully signed in.
You've successfully subscribed to Linux Handbook.
Your link has expired.
Success! Check your email for magic link to sign-in.
Success! Your billing info has been updated.
Your billing was not updated.