Ansible Code Management using Roles

Ansible Code Management using Roles

Hi there! Today we are going to see what are some of the best and most efficient practices to manage Ansible playbooks and code.

Why Roles?

Roles provide a framework for fully independent, or interdependent collections of variables, tasks, files, templates, and modules. In Ansible, the role is the primary mechanism for breaking a playbook into multiple files. This simplifies writing complex playbooks, and it makes them easier to reuse.

It's similar to splitting python code into different modules and then importing them to use in a file.

Let's Start

Here we will configure a simple webserver and Loadbalancer setup using roles. Our setup is like this:

  • IP 192.168.43.209 - acts as Loadbalancer
  • IP 192.168.43.195 - acts as Webserver

You can initialize a role using

ansible-galaxy init <rolename>

It will automatically create a directory structure and all that is left is for you to write code.

VirtualBox_Ansible Controller Redhat_14_03_2021_20_43_40.png

I have already written my roles for webserver and load balancer and they look like this.

VirtualBox_Ansible Controller Redhat_14_03_2021_20_37_22.png

You can check them out here

We make a simple playbook and we can include these roles like this.

Screenshot (1099).png

Now let's run our playbook.

VirtualBox_Ansible Controller Redhat_14_03_2021_20_10_28.png

VirtualBox_Ansible Controller Redhat_14_03_2021_20_11_01.png

Our playbook ran successfully now let's see if the setup is working.

Screenshot (1096).png

Also, you can see the logs of the webserver it has gotten a request from 192.168.43.209 which is our Load Balancer.

VirtualBox_Ansible CLI 2_14_03_2021_20_15_32.png

That's it for this one and see you next time ....!!

Did you find this article valuable?

Support Written Wisdom by becoming a sponsor. Any amount is appreciated!