CREATING LOABALANCER ON AWS USING ANSIBLE

Ritik Bobade
4 min readMar 24, 2021

Today we will be looking how to create a load balancer over AWS using Ansible.

What is Load balancer?

Load balancing is defined as the methodical and efficient distribution of network or application traffic across multiple servers in a server farm. Each load balancer sits between client devices and backend servers, receiving and then distributing incoming requests to any available server capable of fulfilling them.

So, for this we will launch 3 ec2-instances over AWS which will be combination of t3.micro and t2.micro .

Ansible Controller Node — t3.micro

Load balancer — t2.micro

Webserver — t2.micro

So, we can launch instances manually also and through ansible playbook also we are launching through manual mode.

After launching the instances or node will will need to create different roles for load balancer and webserver .

Before that we will need to add hosts for the ansible

After adding the hosts now, we will create roles , for this we will create a role folder all roles will be inside it.

ansible-galaxy init webserver — -> role created for webserver

ansible-galaxy init lbalancer — -> role created for Load Balancer

We will need a host playbook/directory the run/manage the roles

We will name the main playbook as “setup.yml”, so the whole roles setup looks like this.

Also, you need to set roles path in the ansible configuration file.

Now we are good to go for writing the playbook we first write the main playbook i.e., setup.yml

After that we have configure webserver of each instance by writing the playbook in the task folder and the handlers folder.

So now we have written the playbooks of webserver now we have to configure the role of the load balancer before that we have to install haproxy in our system we can install by running the command-

yum install haproxy -y — → it will install haproxy

Then you need to change the port number binding. You can use any port e.g., 1234. Here we have used 8080. also, you need to provide the public ip of all the instances with 80 port. To give Ip randomly here we can use Jinja Template to extract the hostname of each ec2 instance.

Now we have to go to /etc/haproxy/haproxy.cgf and copy the configuration file and paste it to the template directory of the load balancer role and we have to ad the file path in the playbook as well.

So now we have to write the playbook of the tasks inside the load balancer role

As both the roles are completed by writing the playbooks, we are ready to run the main playbook inside the role directory named as “setup.yml” we can run it by command

ansible-playbook -vv setup.yml

As we can see above both roles ran successfully let’s see the load balancer is working successfully or not, we can do it by running the public IP of the load balancer with port number 8080.

--

--