Configure HAProxy and dynamically update the Configuration file using Ansible

Inshiya Nalawala
CodeX
Published in
3 min readMar 30, 2021

HAProxy is a Load Balancer, that balances load on a server by distributing it across the replicated servers, in a round robin fashion.

This article demonstrates how you can set up haproxy and dynamically add the IPs of the replicated server as they join the inventory of the webserver list.

What this Demonstration include?

1. Installing software like httpd and PHP on a list of hosts to configure web server

2. Copying a simple PHP script in the document root of the servers

3. Initiating the web service

4. Installing the haproxy software

5. Updating the Configuration file to add back end servers(the ones we configured as web servers)

6. Re-starting the service if required

The hosts file initially looks like this:

This means we are configuring the webserver on two hosts whose IP address is 192.168.0.107 and 192.168.0.108.

The Haproxy load balancer is configured on localhost on port number 5000.

Step 1: Installing the httpd and PHP software

For this, we will use the package module as shown below,

Step 2: Copying the PHP script to the document root

Step 3: Starting the web service and configuring firewall

Using the copy module, a simple PHP script that runs the ifconfig command and displays the output, is copied in the Document root of the Web Server.

Following that, the services are started and firewall is configured to allow requests on port 80.

Step 4: Installing the haproxy software

Since, we want to configure the Load Balancer on localhost, which is different from the hosts on which we configured the web servers; this configuration of Haproxy is done in a different play, but in the same playbook. HAProxy listens on port 5000 and forwards the request to the back end web servers in round robin fashion. That means, it is the Load balancer that is exposed.

Step 5: Editing the Haproxy configuration file and updating/copying the file to the host configured to be the Load balancer

Step 6: Restarting the haproxy service

Now, in course of time, we may need to add more replicas of the webserver. Thus, to dynamically update the configuration of the HAProxy to load balance among the new set of servers, we use the template module to copy the updated configuration file.

This is how we update the configuration file — by looping over the webservers host group and adding the servers in the configuration file.

Thus, the playbook is run every time a new server shows up in the inventory and the Load Balancer configuration is updated dynamically.

I hope this article helped you learn something new.

--

--