Reverse Proxy(Haproxy) with Ansible

Pawan Trivedi
2 min readDec 9, 2020

--

Setting up Reverse Proxy and Load Balance with Haproxy using Ansible.

Photo by Cookie the Pom on Unsplash

A reverse proxy is a server that sits in front of web servers and forwards client (e.g. web browser) requests to web servers.

A reverse proxy operates by:

  • Receiving a user connection request
  • Completing a TCP three-way handshake, terminating the initial connection
  • Connecting with the origin server and forwarding the original request

Some of the benefits of a reverse proxy :

  • Load Balancing : A popular website that gets millions of users every day may not be able to handle all of its incoming site traffic with a single origin server. Instead, the site can be distributed among a pool of different servers, all handling requests for the same site. In this case, a reverse proxy can provide a load balancing solution which will distribute the incoming traffic evenly among the different servers to prevent any single server from becoming overloaded.
  • Protection from attacks : With a reverse proxy in place, a web site or service never needs to reveal the IP address of their origin server(s). This makes it much harder for attackers to leverage a targeted attack against them.

In this blog I am using HAPROXY(tool) to perform this, haproxy is an open source Load Balancer and proxying solution and to automate this I am using Ansible an automation tool, and using ansible we can achieve this at large scale without repeating the same task again and again. So whenever a new node/server comes up you just need to update the inventory fill and everything will be managed by ansible automatically.

Update inventory file in below format using groups and group variables are a convenient way to apply variables to multiple hosts at once.

vim /etc/ansible/hosts.txt

[proxyserver]

192.168.1.140 ansible_user=user_name ansible_ssh_pass=password

[webserver]

192.168.1.140 ansible_user=user_name ansible_ssh_pass=password 192.168.1.248 ansible_user=user_name ansible_ssh_pass=password

Here is playbook for setting up the haproxy server.

you can run this using command -> ansible-playbook reverseproxy.yml

reverseproxy.yml

Haproxy configuration file, this file should be in same directory where playbook is located.

→ haproxy.cfg.j2

This is a dynamic playbook i.e. you don’t have to worry about the anything when new server comes up for loop and groups variable in cfg file pickups new node and update it to the proxy node,so you just update inventory file with ip and credentials of that node rest will be managed by Ansible.

--

--