Deploy a Load Balancer and multiple Web Servers on AWS instance through Ansible

Aditya Raj
4 min readOct 9, 2020

Task Description :-

  1. Provision EC2 instances through ansible.
  2. Retrieve the IP Address of instances using the dynamic inventory concept.
  3. Configure the web servers through the ansible role.
  4. Configure the load balancer through the ansible role.
  5. The target nodes of the load balancer should auto-update as per the status of web servers.

Step 1: Let us create an Ansible configuration file for AWS.

In my case I have create ansible configuration file is in/etc/ansible/ansible.cfg folder location.

Step 2: Create Dynamic Inventory.

To create the dynamic inventory by fetching ec2 instance IP we will have to use and ec2.ini file.

So first we have to download these files from GitHub.

Inside file we will have to change the python version to 3

Also we have to file executable.

#chmod +x

Step 3: Install boto library and export environment variable.

To make an API request to AWS EC2 we have to install bolo library and also export the environmental variable needed for boto.

#pip3 install bolo

#export AWS_DEFAULT_REGION=’Enter the region name’

#export AWS_ACCESS_KEY_ID=’Enter AWS Access key’

#export AWS_SECRET_ACCESS_KEY=’Enter AWS Secret key’

Step 4: Create Ansible Roles for launching the instances, configuring webserver and configuring load balancer.

Launch instances for webserver and load balancer:

#ansible-galaxy init instance

Configure webserver:

#ansible-galaxy init webserver

Configure Load Balancer:

#ansible-galaxy init lbserver

Step 4: Lets write Ansible code of launching instance, configuring webserver and load balancer.

First let see instance role:

  1. tasks/main.yml

2. /vars/main.yml

Here we have encrypted the vars file.

Let see webserver role:

  1. tasks/main.yml

Let see lbserver role:

  1. tasks/main.yml

2. handlers/main.yml

3. templates/haproxy.cfg

Here the frontend is bind at port number 5000 and backend(webserver) is at port number 80. Here roundrobin algorithm for load balancing.

Step 5: Provision EC2 instances through ansible.

For this I am using task3.yml file.

Step 6: Configure the web servers and load balancer through the ansible role.

For this I am using setup.yml file.

Successfully our load balancer is configured. Let see the output.

Thank You !!



Aditya Raj

I'm passionate learner diving into the concepts of computing 💻