Configuring Load Balancer with Ansible

Configuring Load Balancer with Ansible

Hi there! Today we are going to set up basic load balancer using Ansible. For this, I am going to use Redhat as my VM and haproxy as my reverse proxy or load balancer.

What is Reverse Proxy/Load Balancer?

Diagram_2.png

A load balancer distributes incoming client requests among a group of servers, in each case returning the response from the selected server to the appropriate client. Load balancers are most commonly deployed when a site needs multiple servers because the volume of requests is too much for a single server to handle efficiently. Deploying multiple servers also eliminates a single point of failure, making the website more reliable. Most commonly, the servers all host the same content, and the load balancer’s job is to distribute the workload in a way that makes the best use of each server’s capacity, prevents overload on any server, and results in the fastest possible response to the client.

Let's Build

So I have three VMs for this tutorial :

  • 192.168.43.209: Load Balancer
  • 192.168.43.163: Webserver 1
  • 192.168.43.195: Webserver 2

Now we write a playbook which will configure the webservers and download webpages onto it. When the webservers are configured we will launch another play to install haproxy. The webpage will download is running ifconfig command so that we can see load balancing happening. It will show which system it is connected to. Here our webpage.

Screenshot (1042).png

But the problem is that how we are going to update the web server IPs dynamically into the haproxy.cfg file.

For this in ansible, we have template module which we can use with jinja. And we can use loop to loop through our web server IPs from inventory and update them to the load balancer. So here's our jinja template.

VirtualBox_Ansible Controller Redhat_06_01_2021_14_48_55.png

And our playbook looks like this

Screenshot (1041).png

You can see it here

Now let's run and see what we got. To run we use ansible-playbook <path_to_plabook>

VirtualBox_Ansible Controller Redhat_06_01_2021_14_16_13.png

VirtualBox_Ansible Controller Redhat_06_01_2021_14_16_57.png

Our playbook ran successfully now let's check if load balancing is happening.

Screenshot (1040).png

Screenshot (1039).png

You can see here I connected to IP 192.168.43.209 and we are going to backend servers. Also if we check the access_logs of our web server

VirtualBox_Absible Node CLI_06_01_2021_14_35_46.png

You can see that request it got was coming from IP 192.168.43.209 which is Load Balancer IP. Thus this is also working as a reverse proxy.

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

Did you find this article valuable?

Support Saurav Rana by becoming a sponsor. Any amount is appreciated!