Terraform Project Web Server with Load Balancer

A busy restaurant places a host at the door. The host greets each guest and sends them to a table with a free waiter. A load balancer plays that host for web servers. Visitors reach one address, and the balancer spreads them across several servers. If one server fails, the balancer stops sending guests to it. This project builds that setup on AWS with Terraform.

What You Will Build

Diagram: Traffic Flow

   Visitor browser
         |
         v
+------------------------+
|  Application Load      |   security group: allows port 80 from anywhere
|  Balancer              |
+-----------+------------+
            |
      Target Group (health checks every 30 seconds)
            |
     +------+------+
     |             |
     v             v
+---------+   +---------+
| Server 1|   | Server 2|   security group: allows port 80 from the balancer only
+---------+   +---------+

Before You Start

This project needs a VPC with two public subnets in different zones. Build the previous project first, or point the variables below to any existing VPC and subnet IDs.

Step 1: Variables

variable "vpc_id" {
  type = string
}

variable "subnet_ids" {
  type = list(string)
}

variable "server_count" {
  type    = number
  default = 2
}

Step 2: Find a Server Image

A data source finds the newest Amazon Linux image, so you never copy an ID by hand.

data "aws_ami" "linux" {
  most_recent = true
  owners      = ["amazon"]

  filter {
    name   = "name"
    values = ["al2023-ami-2023*-x86_64"]
  }
}

Step 3: Security Groups

Two groups protect the setup. The balancer accepts web traffic from everyone. The servers accept traffic from the balancer only.

resource "aws_security_group" "alb" {
  name   = "alb-sg"
  vpc_id = var.vpc_id

  ingress {
    from_port   = 80
    to_port     = 80
    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"]
  }
}

resource "aws_security_group" "web" {
  name   = "web-sg"
  vpc_id = var.vpc_id

  ingress {
    from_port       = 80
    to_port         = 80
    protocol        = "tcp"
    security_groups = [aws_security_group.alb.id]
  }

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

Step 4: Web Servers

The user_data script runs when each server starts. It installs a web server and writes a page that shows the server name. Refreshing the browser later reveals which server answered.

resource "aws_instance" "web" {
  count                  = var.server_count
  ami                    = data.aws_ami.linux.id
  instance_type          = "t3.micro"
  subnet_id              = var.subnet_ids[count.index % length(var.subnet_ids)]
  vpc_security_group_ids = [aws_security_group.web.id]

  user_data = <<-EOF
    #!/bin/bash
    dnf install -y httpd
    echo "Hello from server ${count.index + 1}" > /var/www/html/index.html
    systemctl enable --now httpd
  EOF

  tags = {
    Name = "web-${count.index + 1}"
  }
}

The expression count.index % length(...) spreads servers across the subnets in turn.

Step 5: Load Balancer Pieces

resource "aws_lb" "web" {
  name               = "web-alb"
  load_balancer_type = "application"
  security_groups    = [aws_security_group.alb.id]
  subnets            = var.subnet_ids
}

resource "aws_lb_target_group" "web" {
  name     = "web-targets"
  port     = 80
  protocol = "HTTP"
  vpc_id   = var.vpc_id

  health_check {
    path                = "/"
    healthy_threshold   = 2
    unhealthy_threshold = 2
    interval            = 30
  }
}

resource "aws_lb_target_group_attachment" "web" {
  count            = var.server_count
  target_group_arn = aws_lb_target_group.web.arn
  target_id        = aws_instance.web[count.index].id
  port             = 80
}

resource "aws_lb_listener" "http" {
  load_balancer_arn = aws_lb.web.arn
  port              = 80
  protocol          = "HTTP"

  default_action {
    type             = "forward"
    target_group_arn = aws_lb_target_group.web.arn
  }
}

Understanding Each Piece

ResourceJob
Load balancerThe public front door
ListenerWatches port 80 and forwards requests
Target groupThe list of servers that can receive traffic
AttachmentAdds one server to the target group
Health checkRemoves sick servers from rotation

Step 6: Output the Address

output "website_address" {
  value = aws_lb.web.dns_name
}

Step 7: Run and Test

terraform init
terraform plan -var="vpc_id=vpc-0abc123" -var='subnet_ids=["subnet-0aaa","subnet-0bbb"]'
terraform apply -var="vpc_id=vpc-0abc123" -var='subnet_ids=["subnet-0aaa","subnet-0bbb"]'

Wait two minutes for the health checks to pass. Open the website_address in a browser and refresh several times. The message switches between server 1 and server 2.

Clean Up

terraform destroy

Load balancers and servers charge by the hour, so destroy the project after practice.

Key Points

  • A load balancer spreads visitors across several servers behind one address.
  • Target groups hold the servers, and health checks remove failing ones.
  • Security groups let only the balancer talk to the servers.
  • A data source finds the newest server image automatically.
  • The count argument builds identical servers and their attachments.
  • The balancer address appears as an output after apply.