Using Ansible to setup HaProxy and LoadBalancer servers
So, we will be Using HaProxy to do the following task :-
12.1 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.
Steps to be followed to achieve this task :
First of all, we need to update our inventory. Here, we can create group of host according to their functions. Example: We can group webserver ip and give its group name as web.
Inventory file :-
Basic Steps to followed
- Create folder
- Mount CDROM
- Configure yum
- Install php software
- Install httpd software
- copy content of webpage to Document Root
- Start web service
- Configure firewall to access port 80(by default port for webserver)
Configuring Haproxy server
8. Yum configuration as above. i.e step 1,2 and 3
9. Install haproxy
10. Configure /etc/haproxy/haproxy.cfg file
11. Start haproxy service
Lets jump to the fun part i.e writing ansible code.
Here is the code for configuring Webserver
- hosts: web
— name: “Creating a directory for mounting CDROM”
— name: “Mounting CDROM”
— name: “Configuring yum AppStream repo”
description: “yum dvd1”
— name: “Configuring yum BaseOS repo”
description: “yum dvd2”
— name: “Install httpd”
— name: “Install php”
— name: “Copying index.php file to document root”
— name: “Starting service”
— name: “Disabling firewall at port 8080”
The sample php code prints the IP address of the OS.
After running the playbook, we can confirm that our website is up and running.
Now, lets start writing code for configuring Haproxy server, which will have the above two created webserver as their backend servers.
So, here we will make use of Jinja Templating and ansible template module. We have take a copy of haproxy.cfg file and append the IP address of the backend server with the app number at the end of this file. So, we can get IP address using ansible groups variable.
- hosts: haproxy
— name: “Installing haproxy”
— name: “Configuring /etc/haproxy/haproxy.cfg file”
— name: “Starting haproxy service”
In haproxy.cfg file, run a for loop to get all the IP from inventory using groups variable. Group variable references a particular group host and list all the IP from that group.
groups[“web”] → Fetches all the IP address of the Web Group from inventory file. So, now whenever new IP/new server want to get appended we just have to write IP address in the Inventory file.
So, now we can access the Haproxy IP from browser using the 8080 port as configured and can see that it works as a load balancer.