Terraform: Application Load Balancer with Path Based Routing

Girish V P
ADIBI Technologies, Basavanagudi, Blore.
2 min readMar 8, 2024

Terraform code can be used to automate and create AWS resources. We will see how an Application Load Balancer can be created with Path Based routing enabled. This is a foundational level document for beginner. Let me use three target groups here, two are used for redirecting the requests based on criteria and other one used as a default target group.

Pre-requsite

1 - A VPC with two public subnet for launching the Application Load Balancer
2 - Security Group which has public access to port 80 for ALB

Step 1: Create Application Load Balancer

resource "aws_lb" "my-alb-1" {
name = "my-alb"
internal = false
load_balancer_type = "application"
security_groups = [ "sg-XXXXXXX" ]
subnets = ["subnet-XXXXXXXXX","subnet-YYYYYYY"]
enable_deletion_protection = false
enable_cross_zone_load_balancing = true
}

Step 2: Create three Target Groups

resource "aws_lb_target_group" "my-tg-1" {
name = "my-target-group-1"
port = 80
protocol = "HTTP"
target_type = "instance"
vpc_id = "vpc-XXXXXXXX"
health_check {
}
}

resource "aws_lb_target_group" "my-tg-2" {
name = "my-target-group-2"
port = 80
protocol = "HTTP"
target_type = "instance"
vpc_id = "vpc-XXXXXXXX"
health_check {
}
}

resource "aws_lb_target_group" "my-tg-3" {
name = "my-target-group-3"
port = 80
protocol = "HTTP"
target_type = "instance"
vpc_id = "vpc-XXXXXXXXX"
health_check {
}
}

Step3: Create a LB listener for port 80 with a default target group.

resource "aws_lb_listener" "my-alb-listener-1" {
load_balancer_arn = aws_lb.my-alb-1.arn
port = 80
protocol = "HTTP"
default_action {
type = "forward"
target_group_arn = aws_lb_target_group.my-tg-3.arn
}
}

Step 4: Create two LB Listener rules which can redirect the web requests based on the criteria. Link the LB Listener rules to LB Listener like below.

resource "aws_lb_listener_rule" "content-1" {
listener_arn = "${aws_lb_listener.my-alb-listener-1.arn}"
priority = 10
action {
type = "forward"
target_group_arn = "${aws_lb_target_group.my-tg-1.arn}"
}
condition {
path_pattern {
values = ["/content-1/*"]
}
}
}

resource "aws_lb_listener_rule" "content-2" {
listener_arn = "${aws_lb_listener.my-alb-listener-1.arn}"
priority = 20
action {
type = "forward"
target_group_arn = "${aws_lb_target_group.my-tg-2.arn}"
}
condition {
path_pattern {
values = ["/content-2/*"]
}
}
}

Step 5: Execute terraform apply command to create AWS resources.

Result:

Disclaimer: It is recommended to do a thorough test before applying in production environment.

Similar Topics

--

--