Configuring Reverse Proxy using Ansible Playbook

In this blog, I am going to tell you how to configure the ha-proxy server using ansible-playbook in simple steps:
Pre-requisites:
- Ansible should be configured in your base os.
- yum should be configured in it to download the packages.
- You should have a basic knowledge of AWS cloud and have an account over it.
Step1: Writing ansible-playbook
Here we are not using Ansible ad-hoc commands to configure haproxy we are writing a playbook to automate the whole process.
- hosts: haproxy
vars:
- packages:
- httpd
- haproxy
tasks:
- name: "Installing webserver"
package:
name: "{{ item }}"
state: present
loop:
- httpd
- haproxy- name: "Configuring the config file for haproxy"
template:
src: "/root/Ansible/Practice/haproxy.cfg"
dest: "/etc/haproxy/haproxy.cfg"- name: "Starting websever"
service:
name: "{{ item }}"
state: started
loop:
- httpd
- haproxy- name: "Copying web pages"
copy:
dest: "/var/www/html/index.html"
content: "This is test page"
Here, we are running the playbook for all the os that is listed within the haproxy group. There we are installing the httpd and haproxy packages by using the loop and then starting their services.
Now, we also need to make our proxy server dynamic for this we are going to add some lines in the configuration file. We can find the configuration file either from the internet or we can first download the proxy package then go to the location /etc/haproxy/haproxy.cfg
There change the backend port bind from 5000 to 8080 and append the following code in the end:
{% for i in groups['haproxy'] %}
server app{{ loop.index }} {{ i }}:80 check
{% endfor %}
This code will automatically append all the IP addresses that are in the haproxy group to the configuration file.
Now all we need to do is run the ansible-playbook
ansible-playbook haproxy.yml
That’s all, our local haproxy server has been set.
Now if we want to launch the same setup over AWS we first need to launch EC2 instances over it. To launch the instance we can run this ansible script:
- name: Provision os in AWS for loadBalancer
ec2:
key_name: "key"
instance_type: "t2.micro"
image: "ami-0ebc1ac48dfd14136"
count: 3
wait: yes
vpc_subnet_id: "subnet-id"
region: "ap-south-1"
state: restarted
assign_public_ip: yes
instance_tags:
Name: "loadBalancer"
group_id: "sg-08ebf6fbae80de33a"
aws_access_key: "{{ myuser }}"
aws_secret_key: "{{ mypass }}"
This script will create 3 instances over the AWS and then we can run the ansible script for haproxy to create a load balancer over ec2 instance.
Git URL: https://raw.githubusercontent.com/gaurav2203/Practice/master/haproxy.yml
Here, I have provided my git url for your reference. Hope you find this blog useful.