Load Balancing

Overview

ConnectPrivate

About Load Balancing, Application Load Balancer will route traffic to the Auto Scaling Group. We will define our listener and target group.

Set up files

In the LoadBalancing folder, create three files and name them respectively as main.tf, variables.tf, and outputs.tf.

ConnectPrivate

Define some variables we are going to use in the variables.tf file.

variable "one_tier_vpc_id" {
  
}
variable "port" {
  
}
variable "protocol" {
  
}
variable "alb_security_group_id" {
  
}
variable "public_subnet_1_id" {
  
}
variable "public_subnet_2_id" {
  
}

Target Group

Before we can create an Application Load Balancer, we need to define the Target Group. Here, we use resources aws_lb_target_group to create a Target Group in main.tf file.

resource "aws_lb_target_group" "instance_tg" {
  name      = "ASG-Web-Server-Target-Group"
  port      = var.port
  protocol  = var.protocol
  vpc_id    = var.one_tier_vpc_id
}

Application Load Balancer

Next, we will create an Application Load Balancer using resources aws_lb and aws_lb_listener

We define our load balancer type is Application Load Balancer. Attach the public subnet 1 and public subnet 2 to the ALB

resource "aws_lb" "application_load_balancer" {
  name                = "ALB-Web-Server"
  internal            = false
  load_balancer_type  = "application"
  security_groups     = [ var.alb_security_group_id ]
  subnets             = [ var.public_subnet_1_id, var.public_subnet_2_id ]
}

Listener

We use resource aws_lb_listener to confgure listener and routing.

resource "aws_lb_listener" "application_load_balancer_listener" {
  load_balancer_arn = aws_lb.application_load_balancer.arn
  port              = var.port
  protocol          = var.protocol

  default_action {
    type              = "forward"
    target_group_arn  = aws_lb.aws_lb_target_group.instance_tg.arn
  }
}

Output

We just output a value like alb_dns to get the DNS in the output.tf file for testing the Auto Scaling Group.

output "alb_dns" {
  value = aws_lb.application_load_balancer.dns_name
}
output "alb_endpoint" {
  value = aws_lb.application_load_balancer.dns_name
}
output "alb_tg_name" {
  value = aws_lb_target_group.instance_tg.name
}
output "alb_tg_arn" {
  value = aws_lb_target_group.instance_tg.arn
}

Finally, we have completely done buidling the three components of our infrastructure including Networking, Compute and Load Balancing. Next, we will configure our terraform folder so that we can start deploying Infrastructure.