Configuring Haproxy by Ansible

Aman Rathi
3 min readDec 14, 2020


Here in this task we gonna see how to configure the haproxy server with the help of ansible.


HAProxy is a free, open-source software that provides a high availability load balancer and proxy server for TCP and HTTP-based applications that spread requests across multiple servers. It is written in C and has a reputation for being fast and efficient.

Road map of Ansible role of Haproxy

  1. Make an inventory that contains the webserver’s ip
  2. Edit the config file by jinja template
  3. Now install the haproxy software
  4. Start the service
  5. Copy the config files
  6. Restart the service

Lets’s see step by step

Step1. Making inventory

We will create two different groups one contains the load balancer IP and the other one contains the webservers IP. So that the haproxy fetch the IP from the inventory and save them in the config file.

Step2: Editing the file by jinja template

Set the webservers ip in the haproxy.cfg file by jinja templates

Step3. Installing the haproxy software

The first task of this role is to install the haproxy server’s software

- name: installing haproxy
name: haproxy
state: present

Step3. Starting the service

- name: starting services
name: haproxy
state: started

Step3. Copying conf. files and restarting the service

Hereafter copying, we have to restart the services for this we will use handlers and this notify keyword notifies handler to restart the service.

- name: copying files
src: haproxy.cfg.j2
dest: /etc/haproxy/haproxy.cfg
notify: restart

Now let’s create a playbook to which will first create a webservers on thr provided ip’s and then attach with haproxy. For the webserver role use the below github link.

- hosts: webserver
gather_facts: no
- name: setting up webservers
name: http
- hosts: loadbalancer
gather_facts: no
- name: setting up load balancer


Here all the webservers are running on 8123 ports with diff ip’s but we only need on one ip i.e of loadbalancers ip and we will be redirected to the webservers.

github links

Thank You!!



Aman Rathi