Skip to content

ALB

ALB will expose our application to outer world and will handle all incoming traffic.

Application Load Balancer

  1. Create a resource block with type aws_alb and name this with parameters:
    1. name = "${var.service_name}-alb"
    2. subnets = data.aws_subnet_ids.public.ids
    3. security_groups = [aws_security_group.alb.id]

Application Load Balancer Target Group

  1. Create a resource block with type aws_alb_target_group and name frontend with parameters:
    1. name = "${var.service_name}-tg"
    2. port = 80
    3. protocol = "HTTP"
    4. vpc_id = var.vpc_id
    5. target_type = "ip"

Application Load Balancer Listener

  1. Create a resource block with type aws_alb_listener and name frontend with parameters:
    1. load_balancer_arn = aws_alb.this.id
    2. port = 80
    3. protocol = "HTTP"
    4. Default Action:
      default_action {
        target_group_arn = aws_alb_target_group.frontend.id
        type             = "forward"
      }
      

Check your configuration

To check your Terraform configuration run

terraform plan

It will show you the resources that Terraform will create,delete or change. It will not apply anything.


Answer

terraform/alb.tf

resource "aws_alb" "this" {
  name            = "${var.service_name}-alb"
  subnets         = data.aws_subnet_ids.public.ids
  security_groups = [aws_security_group.alb.id]
}

resource "aws_alb_target_group" "frontend" {
  name        = "${var.service_name}-tg"
  port        = 80
  protocol    = "HTTP"
  vpc_id      = var.vpc_id
  target_type = "ip"
}

resource "aws_alb_listener" "frontend" {
  load_balancer_arn = aws_alb.this.id
  port              = "80"
  protocol          = "HTTP"

  default_action {
    target_group_arn = aws_alb_target_group.frontend.id
    type             = "forward"
  }
}