Role

Learn how to reuse our code using Ansible roles from the Ansible Galaxy online archive.

Code reusability

The Ansible role enables code reusability in Ansible. Ansible roles are like functions in the traditional programming world. We can use Ansible roles to develop playbooks more quickly and reuse Ansible code. All the files related to the roles must be under our project’s roles directory.

First, we are going to create an Ansible role and then use it in an Ansible playbook.

Role tree directories

The Ansible role has a standard directory tree. Some directories are mandatory, but most of them are not.

First of all, let’s create an Ansible role named role1.

ansible-galaxy role init role1

The ansible-galaxy command requires the following parameters:

  • role: This interacts with the Ansible role.
  • init: This initializes a new role.
  • role1: This is the name of the new role.

Successful execution of the previous command produces the creation of the role1 inside the roles directory and the following output:

- Role role1 was created successfully
Output of the ansible-galaxy role init command

The following directory tree will be created after executing the command:

Press + to interact
Directory tree of the roles/role1
Directory tree of the roles/role1

The description of the directory structure is as follows:

  • The defaults directory: The main.yml file in this directory contains the default values of role variables that can be overwritten when the role is used. These variables have low precedence and are intended to be
...