Set two different Target Groups on AWS Load Balancer with Terraform

Hello,

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 is 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 does 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 help to you.

Leave a Reply

Your email address will not be published. Required fields are marked *