Ansible roles for load balancer and apache webserver

Aakash Bhardwaj
3 min readJul 10, 2021

What are Ansible 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. -Roles in Ansible are a way of managing playbooks. If we need the same tasks in multiple playbooks, then instead of writing in every playbook we create separate roles for each task and apply them to playbooks.

command is used for creating a role:

ansible-galaxy role init <role_name>

To set the path of the role we set the ansible configuration file as,

role_path=</path>

Ansible Galaxy is a repository for Ansible Roles that are available to drop directly into your Playbooks to streamline your automation projects.

To see an available role in our system:-

ansible-galaxy role list

🔅Create an ansible role myapache to configure Httpd WebServer.
🔅Create another ansible role myloadbalancer to configure HAProxy LB.
🔅We need to combine both roles controlling webserver versions
and solving challenge for host ip’s addition dynamically over each Managed
Node in HAProxy.cfg file.

creating a directory called myroles and 2 roles named “myapache” and “myloadbalancer” in that directory,

tree structure of myapache role

tree structure of myloadbalancer role

ansible-galaxy init myapache

ansible-galaxy init myloadbalancer

Now, let’s update the role path in ansible.cfg file:

Now lets work on ”myapache” role to configure apache webserver:

The variables used here are fetched from vars directory’s main.yml file:

The webpage is from files directory’s index.html file:

Now, let’s work on ”myloadbalancer” role to configure haproxy:

The variables used here are fetched from vars directory’s main.yml file:

Haproxy is from files directory:

Everything is done, now just update the inventory for webservers group and lb and run the playbook:

Output of the webpage:

--

--