Creating and Configuring Haproxy and Webservers in AWS using Ansibles Roles.

B Manoj
4 min readJan 13, 2021

Problem Statement:

🔅Provision EC2 instances through ansible roles.

🔅 Retrieve the IP Address of instances using the dynamic inventory concept.

🔅Configure the web servers through the ansible role.

🔅Configure the load balancer through the ansible role.

🔅The target nodes of the load balancer should auto-update as per the status of web servers.

The entire problem statement requires three roles :

  1. Role-1 for creating ec2 instances and updating their public IP’s to inventory file using dynamic inventory concept.
  2. Role-2 for creating and configuring load balancer.
  3. Role-3 for creating and configuring web servers.

Now let’s initialize these roles using the command as follows:

ansible-galaxy init test1 // Similarly, test2 and test3. Role -1, 2, 3 are analogous to test -1, 2, 3

Let’s discuss the code for role -1

Attached screenshots for role-1 code part -1, 2, 3

As you can see that from the code, I am trying to create 3 OS in AWS as OS-1, 2, 3

OS2 is used as load balancer and OS1 and OS3 are used as webservers.

Excitingly, I am using 3 different OS flavors for doing this task, Amazon Linux, Redhat and Ubuntu.

The concerned file for variables is stored in another yaml file as shown below

Here p1 variable denotes region where we wanna create VMs in AWS

p2, p12 and p13 denotes amazon ami id for amazon linux, redhat and ubuntu.

p3 denotes type of vm that t2.micro

p4, p14, p15 and p5 denotes subnet and security group id’s

p7, p10 and p11 denotes the OS names such as OS1, 2 and 3

p8 and p9 denotes access and security keys for amazon

p6 denotes the public key for logging in the OS.

Also, after we create every OS, I am also trying to update the inventory file using register and lineinfile modules as below shown pic:

Let’s discuss the code for role -2

Here, we are trying to install LB software and then using template module to update the haproxy.cfg file in the destination side.

Let’s discuss the code for role -3

Here we need to be careful.

When we have ubuntu , then we need to use apache2 for installing webserver and for Amazon, we need to use httpd for installing webserver.

After, we installed we need to send some content to the destination file.

It is “FOR LB TESTING”

Let’s analyze main playbook where we had introduced the roles.

Let’s start executing the playbook.

Let’s see whether the VM’s in AWS were created or not

Let’s see whether the load balancer is working or not

Finally, the task is completed successfully !!!!

Thanks Guys !!!

Stay Tuned For More Interesting Updates !!!!

--

--