This Task involves automating the deployment of HAProxy as a load balancer for a web application. It includes health checks, SSL termination, and high availability using Terraform, Ansible, and Docker. The implementation will be based on AWS infrastructure.
Components:
Terraform will be used to:
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "haproxy" {
ami = "ami-0abcdef1234567890" # Replace with actual AMI
instance_type = "t2.micro"
key_name = "my-key" # Replace with your key pair
security_groups = ["haproxy_sg"]
tags = {
Name = "HAProxy-LoadBalancer"
}
}
resource "aws_instance" "web_server" {
count = 2
ami = "ami-0abcdef1234567890"
instance_type = "t2.micro"
key_name = "my-key"
security_groups = ["web_sg"]
tags = {
Name = "Web-Server-${count.index + 1}"
}
}
resource "aws_security_group" "haproxy_sg" {
name = "haproxy_sg"
description = "Security group for HAProxy Load Balancer"
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
Ansible will:
- name: Setup Web Servers
hosts: web_servers
become: yes
tasks:
- name: Install Nginx
apt:
name: nginx
state: present
- name: Deploy Web App
copy:
content: "Welcome to the Load Balanced Web App
"
dest: /var/www/html/index.html
Ansible will:
- name: Setup HAProxy Load Balancer
hosts: haproxy
become: yes
tasks:
- name: Install HAProxy
apt:
name: haproxy
state: present
- name: Configure HAProxy
template:
src: haproxy.cfg.j2
dest: /etc/haproxy/haproxy.cfg
notify:
- Restart HAProxy
handlers:
- name: Restart HAProxy
service:
name: haproxy
state: restarted
frontend http_front
bind *:80
redirect scheme https if !{ ssl_fc }
frontend https_front
bind *:443 ssl crt /etc/haproxy/certs/fullchain.pem
default_backend web_servers
backend web_servers
balance roundrobin
server web1 192.168.1.10:80 check
server web2 192.168.1.11:80 check
To obtain an SSL certificate from Let's Encrypt, run:
sudo apt install certbot python3-certbot-haproxy
sudo certbot certonly --standalone -d example.com
Then, modify the HAProxy configuration:
bind *:443 ssl crt /etc/letsencrypt/live/example.com/fullchain.pem
terraform init
terraform apply -auto-approve
ansible-playbook -i inventory haproxy.yml
ansible-playbook -i inventory web_servers.yml
curl -I http://haproxy-loadbalancer-ip
curl -I https://haproxy-loadbalancer-ip
openssl s_client -connect example.com:443
Refresh the browser multiple times to ensure traffic is distributed across web servers.
This project provides an automated HAProxy Load Balancer setup for web applications using Terraform and Ansible. It ensures scalability, security, and high availability, making it ideal for production environments.