Ansible Roles

Many tools are in use in the IT industry, among which automation tools are getting more popular. These tools play an essential role in developing multiple apps and software. Ansible is a famous tool for configuration management and automates complex IT tasks. You may know the working of the Ansible suite of tools, creating and running Ansible Playbook, etc. Further, to simplify the Ansible Playbooks, Ansible roles are used. These roles include many playbooks where they divide the complex playbooks into different separate reusable parts. In this blog, you will learn about Ansible roles, how they are useful for Ansible, role structure, the creation of roles, and many other aspects.

What is an Ansible Role?

Ansible roles are the primary process of dividing the Ansible Playbook into multiple reusable roles. However, roles are the small functions used inside the playbooks and don't need any specific setting. These roles play a great role in simplifying the creation of complex Ansible playbooks. Also, they make them available to reuse for different purposes. Further, roles allow us to combine various tasks into a single container that helps automate tasks effectively. It also helps reuse the codes if they are useful for anyone. Roles also allow us to share configuration templates.

Ansible is a popular open-source IT automation tool for configuration management, and it is written in Python. However, Ansible is known for its simplicity and ease of use features.

Further, let us know the Ansible roles function with a simple example. For instance, you can perform 5 different tasks on 5 multiple devices. For this, it is possible through a single system. But using a system machine for these tasks might be difficult, and you may need clarification. Here, you can create five different roles for each task where each Role will execute a single task. Further, you can define a name for each position in the playbook to call the roles for these tasks.

Why Are Roles Useful in Ansible?

To start using Ansible, you need contrate on writing and creating playbooks that help automate repetitive tasks much more quickly. By automating more tasks using playbooks, users get more insights into Ansible and become experts. In this regard, at some point, Ansible Playbook may stop working. Here comes the Ansible Roles to safeguard the tasks and their execution.

Ansible Roles allow you to reuse the Ansible code for repetitive tasks and share it efficiently. These roles help you with the best structure to set up multiple jobs, handlers, variables, templates, etc. Further, you can reuse the same roles in multiple tasks without altering the code.

On the other hand, Ansible roles are independent and don’t depend on others to execute. Also, they are highly reusable in different tasks. However, arranging the Ansible code into Ansible roles offers a more easily manageable structure than simply using Ansible playbooks. However, the increasing number of playbooks creates complexity in tasks.

Further, putting the Ansible code within the roles allows you to arrange the automation tasks in a group of series. Typically, using Ansible roles enables you to reuse tasks and share them easily without creating duplicate functions for your design.

Get ahead in your career by learning Ansible Course through hkrtrainings Ansible Online Training!

Ansible Training

  • Master Your Craft
  • Lifetime LMS & Faculty Access
  • 24/7 online expert support
  • Real-world & Project Based Learning

Ansible Role Structure

Now, let us know the typical Ansible role structure. Ansible roles play a key role in writing complex Ansible playbooks by dividing playbooks into different small files. It makes them easy to execute and allows us to reuse them for routine tasks. However, each Ansible role has limited functionality, and no role is called a Playbook. These are the functions used independently within the Ansible Playbooks.

Further, the Ansible role structure uses a normalized directory design to manage consistency and easy usage. They can also delete where these are inactive. Here, the following example command is used to define the skeleton of the role directory structure;

ansible-galaxy init 

Here, the command “ansible-galaxy” includes an Ansible package that doesn’t require additional installation. The following is a skeleton of a typical Ansible role structure:

IMAGE

Ansible verifies the main.yml files, possible changes, and applicable data in each subdirectory. Further, you can add extra YAML files within some directories. Let us discuss the below files used in the Ansible role structure.

  • Defaults: This file includes the default variable values for the Role. These variables are generally used when no values are given. Here, main.yml is the file that defines the variables within this directory.
  • Files: This directory includes multiple types of files, like static and custom, that a role uses to execute tasks. Further, this directory contains all the files to transmit to the remote nodes or hosts.
  • Handlers: This directory is useful to store handler tasks activated by a role's functions.
  • Meta: This directory contains the metadata of each Role which includes author, dependencies, license, supported platforms, etc.
  • Tasks: The number of jobs or projects a role performs. They represent the Role's core functionality.
  • Templates: This directory includes the Jinja2 template files displayed on the remote host.
  • Tests: The directory “tests” include files related to testing. Also, these are configuration files helpful in testing.
  • Vars: This directory includes variables useful for a role. 

Creating a Role

You only need a special directory structure to start developing an Ansible Role. The roles in Ansible require this directory format, which Ansible can locate and use easily. You can assume you use the user's main directory as Ansible's current working directory. Suppose you have the Ansible configuration within another location; then, you must change to the specific directory.

So, let’s start creating a Role in Ansible. Here, you can see the below code that creates a directory called “roles”.

cd ~

mkdir roles

cd roles

In this directory, you can define the roles of Ansible that you can reuse throughout different playbooks and servers. Further, you can reference the below Ansible Playbook to turn the same into a reuseful Role in Ansible. It is the reference code for the same:

IMAGE

Then start building Apache DIR for the Role and open up the directories needed.

Later, start creating sub-directories as required, which will inform Ansible to use them as roles. However, these sub-directories will include the implementation code of your Role.

Now, let us discuss a few points that describe the creation of Ansible roles in detail.

  • Turn a Playbook to a Role

After familiarising yourself with roles in Ansible, it's time to turn a playbook into a role. For this, you should have the sub-directories of roles /Apache2. Then, here you need to build files related to YAML, which will help you define roles in a better way. 

  • Build the Tasks File main.yml

Here, it would help if you began with the subdirectory of tasks. So, let us proceed to this directory. The following is code for the same:

IMAGE

Then, it would help if you built the file main.yml within this directory. Further, you need to populate the same with the whole Apache Playbook contents by editing it to consist only of given tasks.

nano main.yml

The file you will see will look like this:

IMAGE

Here, you can keep the initial three lines along with some other lines of the tasks section from the above code. Also, you can delete the external space on the tasks’ left side. Then you can add a new part to it to allow a module of Apache “ModSecurity”. 

Now the file will be like the following:

IMAGE

Now, it will be easy to follow and know the tasks file clearly as it only includes the real steps to be executed while using Apache Roles.

You can check how the lines of “template” & copy use index & virtual host to the source files in the Role without any prior path. Further, the DIR form of the Role enables sourcing files, templates, etc. straight through their name. Hence, Ansible will automatically locate them for you.

Also, you ensure that you save the file and close it after completing the editing work.

We have the perfect professional Ansible Tutorial for you. Enroll now!

Subscribe to our YouTube channel to get new updates..!

  • Building the Handlers File

You have the playbook inside the above file you created, so you have to shift the section “handlers” to the file at the handler's main yml file.

Then, cd inside the sub-directory “handlers” to the Roles:

IMAGE

Then, open your file within the text editor, then copy the actual playbook “playbook. yml.”

IMAGE

Here, in the following code, you must keep only the last three lines.

Now, delete the whitespace also from prior to the handlers. At the end, you can see this:

IMAGE

Then must ensure to save it and close it once you complete it.

  • Add Templates & Files

After having relevant jobs and handlers, you need to ensure that there should be an index file and virtual host template. It will help Ansible find and put the same on the remote server. As you referenced the files inside the task's main file, they should exist there, otherwise Ansible will not properly execute the Role.

Here, you need to build the index file within the roles DIR:

cd ~/roles/ apache/ files

nano index. html

Then, copy-paste the below code to the editor, and save & end up the same.



Manage Configuration Hands-On

The existing server was provisioned through Ansible



After this, you need to edit the virtual host template. Now, you need to change it to the directory of the template and edit the same:

cd ~/roles/ apache/ templates

nano vhost. tpl

Then, please copy the following code to the editor and end it by saving it.

IMAGE

  • Meta (DIR) Directory

Suppose the Role depends on another role; you could insert another file within this directory, i.e., main yml. It may mention that the Role will rely on an “apt” role.

---

dependencies:

  - apt
  • Vars (DIR) Directory

As we discussed previously, there exists a directory called “vars'', which is useful for setting variables for the Role. There is a possibility that you can set up default variables for the Role using a vars file. However, it is not generally suggested to use it for tiny roles. These variables are similar to configuration data for the roles. 

Although, the directory “vars” is worth specifying in this case, as it helps when roles are more complex.

  • Include other files

However, building roles, including many tasks, dependencies, etc., will be more vast and tough to know. In this condition, you can divide the functions into their files and add them to your file with the name; tasks / main.yml file. 

  • Create a Playbook Skeleton

Now, as the Role structure is configured, you can start using it with a small playbook instead of the earlier version. 

To build the small playbook file, you can use the below code.

cd ~

nano playbook.yml

Then open the above file and copy-paste the below code by saving and closing it.

IMAGE

However, there is only a little information needed for this file. 

Thus, this is the playbook you finally have. Also, it is very tiny and easy to understand, which helps you focus on other goals to configure servers instead of individual jobs.

  • Share Roles with Ansible Galaxy

Ansible Galaxy is a public repository of the content available in Ansible and is open-source with online availability. You can search, download, and utilize the allocated roles and community power. 

You can utilize Ansible Galaxy for browsing roles suitable for the use cases, saving you valuable time. But before you run a role, verify its code repository to check whether it is safe and provides output as you need.

Moreover, you can download the Role and install it from Galaxy using the command “ansible-galaxy install”. Then you can use the same inside the playbook while you override the variable of your default role.

Tips & Techniques for Ansible Roles

The following are some tips and techniques for your Ansible Roles:

  • It would help if you used detailed names for the roles, tasks, variables, etc., you created. Also, document the purpose of the roles in detail and specify the variables that the user needs to lay. Further, put some defaults and clarify the roles to enable users quickly onboard.
  • Always keep your roles flexible and eliminate inserting extreme dependencies. Further, to manage the execution sequence of various tasks and roles, you can use the command import_role tasks or include_role tasks rather than keywords related to typical roles.
  • A role manages multiple activities. For example, you can develop a role that installs several components. You can follow the partition of distress design principle as a whole and discrete the roles dependent on various functionalities.
  • Set your jobs/tasks in individual task files for better clarity and arrangement when it matches.
  • Don’t place any sensitive or crucial information into the roles of YAML files. These sensitive data should be moved while executing the Role by the playbook regarding variables. You shouldn’t save it inside the code repository.

Click here to get latest Ansible Interview Questions and Answers for 2022!

Ansible Training

Weekday / Weekend Batches

Conclusion

Thus, you have gone through the Ansible roles, their uses, and how to turn playbooks into the roles and the whole process. Now you can create roles as required using Ansible. Also, you have learned various tips and tricks regarding roles in Ansible. Ansible is a useful tool for automating complex IT jobs and managing configurations well. We hope you enjoyed learning Ansible roles in a detailed way. Stay tuned for more insights in this space. 

Related Articles:

Find our upcoming Ansible Training Online Classes

  • Batch starts on 28th Sep 2023, Weekday batch

  • Batch starts on 2nd Oct 2023, Weekday batch

  • Batch starts on 6th Oct 2023, Fast Track batch

Global Promotional Image
 

Categories

Request for more information

Gayathri
Gayathri
Research Analyst
As a senior Technical Content Writer for HKR Trainings, Gayathri has a good comprehension of the present technical innovations, which incorporates perspectives like Business Intelligence and Analytics. She conveys advanced technical ideas precisely and vividly, as conceivable to the target group, guaranteeing that the content is available to clients. She writes qualitative content in the field of Data Warehousing & ETL, Big Data Analytics, and ERP Tools. Connect me on LinkedIn.

Ansible roles are primarily responsible for dividing Ansible Playbooks into multiple reusable files. It helps to make writing a more complex playbook simple and reuse the same for various purposes.

Roles are just a small functionality that is used individually within the playbooks. Ansible Playbook is a unit of scripts arranged that describes the tasks that manage the device configuration with automation tools.

You can use the command ansible-galaxy to build Ansible roles, which offers several templates to create them.

Ansible generally looks for the roles within the subdirectory of roles related to the playbook file as a default. You can utilize the Ansible configuration roles_path to describe alternate role areas.