Writing an Ansible-playbook to configure Haproxy and update the conf file dynamically

This article helps in how to configure the “proxy” server, update its conf file dynamically when a new “Apache” webserver is added into inventory.

Task Description:

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

What is HAproxy server?

HAProxy is free, open-source software that provides a high availability load balancer and proxy server for TCP and HTTP-based applications that spreads requests across multiple servers.

It helps us in balancing the load, managing the backend applications when added into it.

Every time we launch a new webserver, we have to tell to haproxy that a new webserver has come up and you need to add it to the inventory. This can be time-consuming and error-prone.

To tackle this problem we can use the ansible inventory file. Every time we add a webserver we can just update the inventory file. Using the template file ansible will go to config file and update its inventory dynamically.

Now we know what is haproxy server, let's set up the server in one instance.

Inventory file of ansible

We can see we have two instances in the backend group, and one instance in the load balancer group. We use this inventory to update the config file of proxy.

Run the following command and update the last line as follows

copy config file to working folder,

cp /etc/haproxy/haproxy.cfg /ansible-ws/task-10

This will copy the file to the working folder,

Now we can use jinja language to help ansible know that they have to update inventory there, normally when we add jinja to any file we use extension j2 at the end of the file.

vim haproy.cfg.j2

Add these lines starting from the backend. This helps ansible to update IP’s of the backend servers to it.

Now we configure the webservers,

Configuring webservers is simple,

  1. download the httpd software
  2. Copy the HTML file in /var/www/html folder
  3. start the httpd service

This is the whole code for this task,

Now run the playbook using

ansible-playbook task-12.yml
]

The playbook run successfully,

To check if the load balancer is working or not:

It is working completely fine. This completes our task.

connect me on Linkedin: https://www.linkedin.com/in/tejesh-itha-59083215a

DevOps and Machine Learning Enthusiast