Terraform for aws_alb_listener how to add multiple target_group_arn in default action for type="forw

Publish date: 2024-05-25

My Approach: I have to create an "aws_lb_listener" resource , in the default action I have type = " forward" but I don't have one target_group_arn . I have more than one target_group_arn values.

Below snippet shows frontend-listener but the target_group_arn should include more than one arn values.

resource "aws_alb_listener" "frontend-listener" { load_balancer_arn = aws_alb.ss_alb.arn port = "443" #"80" protocol = "HTTPS" depends_on = [aws_alb_target_group.aws_alb_target_group] default_action { #target_group_arn = aws_alb_target_group.aws_alb_target_group.arn type = "forward" } } 

The aws_alb_target_group resource shows multiple target-group being created .

resource "aws_alb_target_group" "aws_alb_target_group" { for_each = local.ebapp_name name = "${each.value.name}-tg" port = 80 protocol = "HTTP" vpc_id = var.vpc_id } 

I have looked at the terraform documentation but couldn't get a solution. (https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/lb_listener)

resource "aws_alb_listener_rule" "aws_alb_listener_rule"{ for_each = local.ebapp_name listener_arn = aws_alb_listener.frontend-listener.arn action { type = "forward" target_group_arn = aws_alb_target_group.aws_alb_target_group[each.value.name].arn } condition { path_pattern { values = ["/${each.value.name}/*"] } } } 

I have also mentioned the Listener rules .

The error is shown with terraform apply command and it is as below:

for actions of type 'forward', you must specify a 'forward' block or 'target_group_arn'

What changes to make to solve this error?

2 Answers

I think you could achieve that using dynamic blocks. For example:

resource "aws_alb_listener" "frontend-listener" { load_balancer_arn = aws_alb.ss_alb.arn port = "443" #"80" protocol = "HTTPS" depends_on = [aws_alb_target_group.aws_alb_target_group] default_action { type = "forward" forward { dynamic "target_group" { for_each = aws_alb_target_group.aws_alb_target_group content { arn = target_group.value["arn"] } } } } } 

The above is example only, and some adjustment may still be required to make it work as expected.

8

This worked for me. It adds now all three target groups to the defualt action of the listener.

locals { target_groups = ["1", "2", "3"] } resource "aws_lb_listener" "https_to_target_group" { count = length(local.target_groups) certificate_arn = aws_acm_certificate.cd.arn load_balancer_arn = aws_lb.cd.arn port = var.alb.port protocol = var.alb.protocol ssl_policy = var.alb.ssl_policy default_action { type = "forward" forward { dynamic "target_group" { for_each = local.target_groups content { arn = aws_lb_target_group.cd[target_group.key].arn } } } } 

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobWxxYW2Ccn6OrZyrqpGbvLO5jJ%2Bmq2WRrMBurcubZKWho6myr7HRZp%2Bor12pvG6tw51kpq2cqbaxuMRmq5qql5rBbrPRqKypZZGnu261zWabnp6Rqrm1ecA%3D