Labs · DevOps
Lab: Create an Application Load Balancer, Target Group, Listener and Two nginx Servers with Terraform, and See Traffic Shared Between Them
Course: DevOps · Chapter 44: Terraform AWS Guides EC2 RDS S3 Security Groups IAM ALB and Auto Scaling · Lesson: 44.6 How to create an Application Load Balancer with Terraform
Lesson 44.6 explains the four ALB pieces and the security group chain; this lab runs and tests them.
Chala mitrano! Ek server padla tar site padli. Aaj don server, ek load balancer.
Suppose we are…
Suppose we are on an Instagram-style team and the single demo server falls over when traffic grows. An Application Load Balancer spreads requests across several servers and stops sending traffic to an unhealthy one. In Terraform an ALB is four pieces: the load balancer, a target group, a listener and the target attachments. This guide puts two nginx servers behind one ALB.
Goal of this lab
By the end you will have:
- An ALB that forwards to two healthy targets.
- Web servers that accept port 80 only from the ALB security group.
- Answers from
server 0andserver 1, then everything destroyed.
What you need
- Terraform 1.6 or newer (
terraform version). - AWS CLI v2 signed in to your own AWS account with an IAM user or SSO role that may create these resources (
aws sts get-caller-identityworks). Never use the root user, and never paste access keys into .tf files. - Region Mumbai (
ap-south-1) is used; changeregionif you prefer another. - 40 minutes.
Cost and cleanup
An ALB and two t3.micro instances are billed by the hour. Small charges are possible even on the free tier. Finish the lab in one sitting and always run the Clean up part at the end.
Part 1: Create the project files
Create the folder:
mkdir alb-guide && cd alb-guideWhat you should see: after the next steps, this layout:
alb-guide/ ├── versions.tf ├── variables.tf ├── main.tf └── outputs.tfCreate
versions.tf:versions.tf
terraform { required_version = ">= 1.6" required_providers { aws = { source = "hashicorp/aws" version = "~> 5.0" } } } provider "aws" { region = var.region }Create
variables.tf:variables.tf
variable "region" { type = string default = "ap-south-1" }Create
main.tf:main.tf
data "aws_ami" "al2023" { most_recent = true owners = ["amazon"] filter { name = "name" values = ["al2023-ami-2023.*-x86_64"] } } data "aws_vpc" "default" { default = true } data "aws_subnets" "default" { filter { name = "vpc-id" values = [data.aws_vpc.default.id] } } resource "aws_security_group" "alb" { name = "guide-lb-alb" vpc_id = data.aws_vpc.default.id } resource "aws_vpc_security_group_ingress_rule" "alb_http" { security_group_id = aws_security_group.alb.id cidr_ipv4 = "0.0.0.0/0" ip_protocol = "tcp" from_port = 80 to_port = 80 } resource "aws_vpc_security_group_egress_rule" "alb_all" { security_group_id = aws_security_group.alb.id cidr_ipv4 = "0.0.0.0/0" ip_protocol = "-1" } resource "aws_security_group" "web" { name = "guide-lb-web" vpc_id = data.aws_vpc.default.id } resource "aws_vpc_security_group_ingress_rule" "web_from_alb" { security_group_id = aws_security_group.web.id referenced_security_group_id = aws_security_group.alb.id ip_protocol = "tcp" from_port = 80 to_port = 80 } resource "aws_vpc_security_group_egress_rule" "web_all" { security_group_id = aws_security_group.web.id cidr_ipv4 = "0.0.0.0/0" ip_protocol = "-1" } resource "aws_instance" "web" { count = 2 ami = data.aws_ami.al2023.id instance_type = "t3.micro" subnet_id = data.aws_subnets.default.ids[count.index] vpc_security_group_ids = [aws_security_group.web.id] user_data = <<-EOT #!/bin/bash dnf install -y nginx echo "server ${count.index}" > /usr/share/nginx/html/index.html systemctl enable --now nginx EOT metadata_options { http_tokens = "required" } } resource "aws_lb" "web" { name = "guide-web-alb" load_balancer_type = "application" internal = false security_groups = [aws_security_group.alb.id] subnets = data.aws_subnets.default.ids } resource "aws_lb_target_group" "web" { name = "guide-web-tg" port = 80 protocol = "HTTP" vpc_id = data.aws_vpc.default.id health_check { path = "/" matcher = "200" } } resource "aws_lb_target_group_attachment" "web" { count = 2 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 } }Create
outputs.tf:outputs.tf
output "alb_url" { value = "http://${aws_lb.web.dns_name}" }
Part 2: Init, check and plan
Download the AWS provider:
terraform initWhat you should see:
Terraform has been successfully initialized!Format and validate:
terraform fmt terraform validateWhat you should see:
Success! The configuration is valid.Plan and read the counts:
terraform planWhat you should see:
Plan: 11 to add, 0 to change, 0 to destroy.
Part 3: Apply and test
Apply and type
yes:terraform applyWait 2–3 minutes for health checks, then curl four times:
for i in 1 2 3 4; do curl -s $(terraform output -raw alb_url); doneWhat you should see: answers from both servers:
Plan: 11 to add, 0 to change, 0 to destroy. Apply complete! Resources: 11 added, 0 changed, 0 destroyed. alb_url = "http://guide-web-alb-123456789.ap-south-1.elb.amazonaws.com" $ for i in 1 2 3 4; do curl -s $(terraform output -raw alb_url); done server 0 server 1 server 0 server 1In the console open EC2 → Target groups → guide-web-tg → Targets.
What you should see: two targets with health status healthy.
Clean up: destroy everything
Delete everything this lab created. Type
yeswhen asked:terraform destroyWhat you should see:
Destroy complete! Resources: 11 destroyed.
Ravindra Bagale's Tip
The web security group allows port 80 from the ALB security group, not from 0.0.0.0/0. Users can only reach the servers through the load balancer.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| 502 Bad Gateway from the ALB | No healthy targets | 502 or 503 means no healthy targets. Wait for user_data to finish, check that the web group allows port 80 from the ALB group, and look at the target group Health status in the console. |
| Default VPC with subnets in only one zone | ALB needs two zones; apply fails | Use a region whose default VPC has subnets in at least two zones |
Skipping terraform plan | Surprise changes or deletes | Always read the plan counts before apply |
Self-check checklist
0 of 4 done
Try-at-home challenge
Stop one instance in the console, curl again and see only one server answer. Start it again and watch it return to healthy.
Samajla ka? Two servers, one front door, health checks deciding. Aata pudhe jaauya Auto Scaling.