Home > database >  Use terraform to create multiple listeners with same configurations for multiple load balancer ARN&#
Use terraform to create multiple listeners with same configurations for multiple load balancer ARN&#

Time:06-22

I have a resource "aws_lb_listener" with a default_action that needs to be added for multiple Load balancers. The way I see is creating individual resources with load_balancer_arn for all the load balancers.

Since the default action is common, Is there a way to create listener for each AWS LB

resource "aws_lb" "front_end" {
  # ...
}

resource "aws_lb" "front_end_2" {
  # ...
}


resource "aws_lb" "front_end_3" {
  # ...
}

resource "aws_lb_listener" "front_end" {
  load_balancer_arn = ["${aws_lb.front_end.arn}", "${aws_lb.front_end_2.arn}", "${aws_lb.front_end_3.arn}"] // I know this is incorrect but something like this (for each LB, create listener with following config)
  port              = "443"
  protocol          = "HTTPS"

  default_action {
    ....
    }
  }
}

In the above example, the listener configuration for all the three Load balancers is same. Hence wanting to create listener for each load balancer.

CodePudding user response:

Assuming that you want to keep your aws_lb as 3 independent resources, then you can use for_each to create 3 listeners for them.

resource "aws_lb_listener" "front_end" {

  for_each = toset([aws_lb.front_end.arn, aws_lb.front_end_2.arn, aws_lb.front_end_3.arn])

  load_balancer_arn = each.value
  port              = "443"
  protocol          = "HTTPS"

  default_action {
    ....
    }
  }
}
  • Related