Use Ansible playbook to Configure Reverse Proxy i.e. Haproxy and update it’s configuration file automatically on each time new Managed node (Configured With Apache Webserver) join the inventory.

Shobhit Singh Pal
3 min readDec 16, 2020

Reverse Proxy: Reverse does the work opposite to proxy that’s why it is called reverse proxy. Reverse proxy through the firewall takes the client request and make the similar request to server . After getting the response the reverse proxy sends the response to the client.

Prerequisites

  • HAproxy program
  • Host groups in inventory

For setting up the load balancer in any system we need to configure the HAproxy as reverse proxy. For configuring the HAproxy the file is haproxy.cfg. In the following section

we will make the entry of managed nodes.

This configuration file after the entry of managed nodes as per inventory need to upload on the system which will act as load balancer.

So now we have two types of host groups . First host group is the one who will act as the backend servers group and the second host group will be for the load balancer.

So inventory will look like:

and the haproxy.cfg file will be as follows as:

Here web is the host group. {% %} is the syntax for ‘for loop’ in jinja.

this for loop will iterate over the web host group and in each iteration will store the backend server ip in ‘i’. loop.index will evaulate as 1 for 1st iteration and so on.

{% endfor %} is the end of the scope of for loop.

After making the inventory and configuring the HAproxy we will code the ansible playbook.

This is simple ansible playbook which i coded. It has two host groups as per our inventory. The web host group is to configure the httpd server on systems which will act as backend servers and lb host group is for the load balancer set up.

Let’s understand the web hosts:

package: will install the httpd server.

file: will create the lw1.html.

copy: will copy the content “lb testing!!” in the lw1.html.

service: to restart the service if by chance httpd is already installed but for haproxy we need to again start the httpd service.

In lb hosts:

package: will install the haproxy program.

template: will update the haprxoy.cfg file dynamically means by interpreting the for loop and hosts.

service: to start the service of haproxy as reverse proxy.

finally running the ansible-playbook as:

ansible-playbook lb.yml

Now checking the output on ip 133:

Now as soon as more traffic will come load balancer will route the request to 194.

Sometimes the if webservers site does not reach then check the firewall and update it or run the command as follows:

systemctl stop firewalld

Conclusion: Setting the load balancer mainly involves the configuration of the HAproxy. With ansible now the load balancer can make entry of backend servers dynamically and fastly.

--

--