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:

Get hands-on with 1400+ tech skills courses.