Set two different Target Groups on AWS Load Balancer with Terraform

Last week, I wrote an infrastructure as a code via Terraform. In my case, I need to forward the traffic from AWS Application Load Balancer public interface to two different target groups. The hashicorp language (HCL) not a hard language but the document is missing a lot of subjects and also there are some points in terraform are undocumented.

I’ve Google it before the make sure but I’ve seen there is a lot of questions and issues about the “Use more than one target group on AWS with terraform” subject.

I read the suggested solutions but they do not help me. After that, I decided to use “aws_lb_listener” as a resource. Finally, I found a solution to my case for my own. You can see details below:

resource "aws_lb" "awsalb" {
  name                       = "my-aws-loadbalancer"
  internal                   = false
  load_balancer_type         = "application"
  security_groups            = [aws_security_group.lb.id]
  subnets                    = data.aws_subnet_ids.subnets.ids
  enable_deletion_protection = false

  tags = {
    Name     = "My AWS ALB Load Balancer"
  }
}

resource "aws_lb_target_group" "origin" {
  name     = "Origin-Group"
  port     = 5080
  protocol = "HTTP"
  vpc_id   = data.aws_vpc.default.id

  stickiness {
      type = "lb_cookie"
  }
}

resource "aws_lb_target_group" "edge" {
  name     = "Edge-Group"
  port     = 5080
  protocol = "HTTP"
  vpc_id   = data.aws_vpc.default.id

  stickiness {
      type = "lb_cookie"
  }
}

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

  default_action {
    type = "forward"
    forward {
      target_group {
        arn = aws_lb_target_group.origin.arn
      }

      target_group {
        arn = aws_lb_target_group.edge.arn
      }

      stickiness {
        enabled  = true
        duration = 28800
      }
    }
  }
}


I hope, this trick is helpful to you.

Edit on June 28, 2022: I used this code block on https://github.com/flightlesstux/antmedia/tree/master/aws-cluster You can check and understand how’s working…