Chapter #24: How to Create and Use Ansible Roles with Ansible Galaxy
In this chapter, you will learn how to create roles in Ansible, download them from Ansible Galaxy, and use them in your playbooks to automate tasks efficiently.

In this chapter, you will learn how to create and download roles on Ansible Galaxy and use them. Ansible is a simple yet effective configuration management & automatic deployment tool that seamlessly automates complex tasks in an efficient manner.
You can manage hundreds or even thousands of servers from a single control node using a single playbook file.
However, writing playbooks for managing the same service in different environments can be quite cumbersome, and this usually leads to code redundancy. Additionally, more complexity can add to the difficulty in managing all the devices.
In comes roles. In Ansible, roles are used for breaking down playbooks into reusable files that can be used across several other instances where the need arises to perform a similar task. This eliminated the need for rewriting playbooks over and over again and saves a great deal of time and energy.
Roles are simply functionalities of playbooks. A role ships with pretty much what would constitute a playbook: Tasks, files, modules, variables, and templates. Also, note that each role is limited to a particular task or the desired output.
/etc/ansible/roles
directory is writable by the user executing Ansible commands.Creating an Ansible Role
To create a role in Ansible, simply use the syntax:
ansible-galaxy init role_name
Multiple directories and files will be created in your current working directory. In this case, I have decided to create a role in the /etc/ansible/roles
directory.
Letβs create a role called apache.
ansible-galaxy init apache

Use the tree
command to have a glance at the directory structure of the role.
tree apache

As you can see, several directories have been created; however, not all of them will be used in the playbook.
tasks/
, handlers/
, templates/
, vars/
, and defaults/
.Now, to use your newly created role in a playbook, define a task in the main.yml
file contained in the tasks
directory of your new role (/apache/tasks/main.yml
):
---
- hosts: database_servers
tasks:
- name: Install Apache2 on Ubuntu webserver
apt:
name: apache2
state: installed
apt
is specific to Debian-based systems.Afterward, create a playbook file and call the role as shown:
---
- hosts: webservers
roles:
- apache
Installing a Role from Ansible Galaxy
Roles play a crucial role in sharing code with other users in the Ansible community using the Ansible Galaxy platform.