Configuring HAproxy in AWS Instances using Ansible

Configuring HAproxy in AWS Instances using Ansible

In the last article, we have configured the HAproxy in localhost, in this article we're gonna configure HAproxy in AWS instance.

To configure HAproxy in AWS instance we have to give the location of the AWS instance private key in the Ansible Inventory.

Ansible Inventory file:-

[webservers]
52.66.251.239 ansible_user=ec2-user ansible_ssh_private_key_file=/root/Aws/master.pem ansible_connection=ssh

[load_balancer]
52.66.236.128  ansible_user=ec2-user ansible_ssh_private_key_file=/root/Aws/balancer.pem ansible_connection=ssh

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

To escalate the privileges we have to edit ansible.cfg

ansible.cfg file :-

[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

Changes in haproxy.cfg file

which we upload from controller node:- cfg file.jpg Now, we write a code in Ansible to configure HAproxy and Webservers.

haproxy.yml file:-

---
- 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

Now run the program:-

program successfully.jpg

As you can see the program ran successfully, now its time to check the changes by entering the IP address of the reverse proxy server in the webserver.

browser.jpg

As we can see the index.html in the web browser which means our task is successfully completed.

All thanks to the Mr Vimal Daga sir for providing such information to us.

Thanks you !!