Configure HAProxy load balancer for Apache webserver with Ansible Roles

Girija Varma
3 min readMay 4, 2021

In this article, we are going to create 2 ansible roles one to configure the httpd web server and the other to configure the HAProxy load balancer, and We need to combine both of these roles controlling web server versions
and solving challenge for the host IPs addition dynamically over each Managed Node in HAProxy.cfg file.

Refer to this article to know about Ansible and HAProxy.

https://vgirija.medium.com/configure-haproxy-server-on-ec2-instance-with-help-of-dynamic-inventory-in-ansible-88abf849e3b9

Let's do the practical

  1. Configure the ansible configuration file:

I hope you have installed ansible software, if not use the command → pip3 install ansible, to install Ansible.

# vim /etc/ansible/ansible.cfg 
ansible.cfg

Ansible Roles

Roles let you automatically load related vars_files, tasks, handlers, and other Ansible artifacts based on a known file structure. Once you group your content into roles, you can easily reuse them and share them with other users.

To create a role:

# ansible-galaxy init <your_rolename>

To check all the roles:

# ansible-galaxy list

Here I have created 2 roles to manage this task:

  1. myapache: It will configure the httpd webserver

In the task folder,

# vim /etc/ansible/roles/myapache/tasks/main.yml

main.yml

In the vars folder,

# vim /etc/ansible/roles/myapache/vars/main.yml

main.yml

In the files folder,

# vim /etc/ansible/roles/myapache/files/indexpage.php

indexpage.php

In the handlers folder,

# vim /etc/ansible/roles/myapache/handlers/main.yml

main.yml

2. myloadbalancer: It will configure the HAProxy load balancer

In the task folder,

# vim /etc/ansible/roles/myloadbalancer/tasks/main.yml

main.yml

In the vars folder,

# vim /etc/ansible/roles/myloadbalancer/vars/main.yml

main.yml

In the handlers folder,

# vim /etc/ansible/roles/myloadbalancer/handlers/main.yml

main.yml

In the templates folder,

# vim /etc/ansible/roles/myloadbalancer/templates/haproxy.cfg.j2

haproxy.cfg.j2

To play these roles I have created another playbook → main_file.yml

main_file.yml

The output of playbook file:

the output of main_file.yml
the output of main_file.yml

The Loadbalancer and web servers are running on AWS cloud but you can do it in local VM also.

running instances

In the below pictures you will see the backend web servers coming in every time we hit this load balancer i.e the frontend server i.e. ‘13.232.98.116'

⚜️GitHub:

If you have any doubts ask me in the responses, and if you like it please do a clap 👏

Thank you 😇

--

--