Configuring LoadBalancer using haproxy on AWS Using Ansible
Nikhil Suryawanshi
MLOps Engineer | 7x GCP | Kubernetes | Terraform | AWS | DevOps | Java | Python
Task Description:
??Launch an AWS instances with the help of ansible.
??Retrieve the public IP which is allocated to the launched instance.
??With the help of the retrieved Public IP configure the load balancing setup using haproxy.
Let's start -
For launching Instance on AWS Cloud from localhost, we have to install library for ansible to contact with AWS EC2 instance.
For this install boto library using pip3 command …
pip3 install boto pip3 install boto3
Here I create two playbook -
for launching AWS intance (web.yml)
for configuring webserver & configuring LoadBalancer using Haproxy (set.yml) .
Here I created three different role for launching instance , configuring webserver & configuring LoadBalancer using Haproxy.
To retrieve the public IP of the instance Dynamically we have to create dynamic inventory .
For this we have to download two files from this two links .
Run the below command to download those two files . These are the scripts given redhat officially .
Make a diff. folder and then enter these URL's to download scripts. wget https://raw.githubusercontent.com/ansible/ansible/stable-2.9/contrib/inventory/ec2.ini wget https://raw.githubusercontent.com/ansible/ansible/stable-2.9/contrib/inventory/ec2.py Make both files executable by running this commands ... chmod +x ec2.py chmod +x ec2.ini
And then provide the AWS_REGION , AWS_ACCESS_KEY_ID andAWS_SECRET_ACCESS_KEY in the ec2.ini files
export AWS_REGION='ap-south-1' export AWS_ACCESS_KEY_ID='enter your access key' export AWS_SECRET_ACCESS_KEY='enter your secret key'
Now we have to edit inside ec2.py file. This file written in python 2 but we are using python 3 so we need to edit the header.
#!/usr/bin/python3
Setting up the Ansible configuration file as per requirement .
Now run the playbook to launch instance on AWS -
ansible-playbook web.yml
Here I launch 2 instances with tag name webserver for webserver and 1 instance with tag name loadbalancer for loadbalancer.
Our AWS instances launched -
Dynamic inventory Dynamically Retrieve the public IP of the instance .
Listing all the instance IP using ansible command ..
ansible all --list-hosts
To configure the HAProxy and webserver on the instance run another ansible playbook .
ansible-playbook set.yml
Now enter the public IP of the Loadbalancer Instance -
Our output -
Github url- https://github.com/NikhilSuryawanshi/Ansible_code/tree/main/task3
TASK COMPLETED!!!!
ThankYou For Reading .