Configuring HAproxy using Ansible for webservers running on AWS

Configuring HAproxy using Ansible for webservers running on AWS

Now, in this article we're gonna configure HAproxy in AWS instance.

Since our load balancer and webservers are running in AWS instance we have to give the location of the AWS instance private key in the Ansible Inventory:

[webservers]
15.207.116.138  ansible_user=ec2-user ansible_ssh_private_key_file=/root/aws/server.pem ansible_connection=ssh

[load_balancer]
13.233.144.75  ansible_user=ec2-user ansible_ssh_private_key_file=/root/aws/loadbalancer.pem ansible_connection=ssh
[defaults]
inventory=/root/ansible/ip.txt
host_key_checking = false
ask_pass = false

[privilege_escalation]
become=yes
become_ask_pass=false
become_user=root
become_method=sudo

Here we have to escalate the privileges to root user as AWS instances by default login as ec2-user by which we cannot download HAproxy .

here before we upload the haproxy.cfg in the loadbalancer node and we use Jinja for loop in the file which will automatically add the IP of web servers into the file.

9GkXA_BD8 (1).jpeg

Now we write playbook for configuring HAproxy and Webservers:

---
- hosts: load_balancer

  tasks:
          - name: Downloading Haproxy
            package:
                    name: "haproxy"
                    state: present

          - name: Copying Haproxy configuration files
            template:
                    src: "haproxy.cfg"
                    dest: /etc/haproxy/
            notify:
                    - Restarting Load Balancer

          - name: Starting Haproxy
            service:
                    name: haproxy
                    state: started

  handlers:
          - name: Restarting Load Balancer
            service:
                    name: haproxy
                    state: restarted

- hosts: webservers

  tasks:
          - name: Installing httpd
            package:
                    name: "httpd"
                    state: present

          - name: Copying HTML files
            copy:
                    src: "/root/ansible/home.html"
                    dest: /var/www/html/
            notify:
                    - Restarting httpd

          - name: Starting httpd
            service:
                    name: httpd
                    state: started

  handlers:
          - name: Restarting httpd
            service:
                    name: "httpd"
                    state: restarted

After the program has ran successfully, then we can check the changes by entering the IP address of the reverse proxy server in the webserver.

Vddm0UmA6.jpeg