6
votes

I am having a hard time figuring out how to make an output for each target group resource that this code creates. I'd like to be able to reference each one individually in other modules. It sounds like for_each stores it as a map, so my question is how would I get the arn for targetgroup1 and targetgroup2? Terraform normally refers to outputs by resource name, so I am struggling with that in this scenario and also how to refer to these individual arns. Would I also need to work the outputs into the for_each or could I drop it into the output.tf file?

locals {
  target_groups_beta = {
    targetgroup1 = {
      name = "example",
      path = "/",
      environment = "Beta"
    }
    targetgroup2 = {
      name = "example2",
      path = "/",
      environment = "Beta"
    }
    }
  }

resource "aws_lb_target_group" "target-group" {
  for_each = local.target_groups_beta
  name     = "example-${each.value.name}-"
  port     = 80
  protocol = "HTTP"
  vpc_id   = var.vpc-id
  deregistration_delay = 5

  tags = {
    Environment = "${each.value.environment}"
  }

  health_check{
  healthy_threshold = 2
  unhealthy_threshold = 2
  timeout = 10
  interval = 15
  path = each.value.path
  }
}

I receive the following error when trying to do it in the output.tf file without a key value, but when I input one such as value = "${aws_lb_target_group.target-group[0].arn}" it says it's invalid. Error without key value below:

Error: Missing resource instance key

on modules\targetgroups\output.tf line 2, in output "tg_example_beta": 2: value = "${aws_lb_target_group.target-group.arn}"

Because aws_lb_target_group.target-group has "for_each" set, its attributes must be accessed on specific instances.

For example, to correlate with indices of a referring resource, use: aws_lb_target_group.target-group[each.key]

1

1 Answers

10
votes

The aws_lb_target_group.target-group generated will be a map, with key values of targetgroup2 and targetgroup1.

Therefore, to get the individual target group details you can do:

output "target-group1-arn" {
  value = aws_lb_target_group.target-group["targetgroup1"].arn
}

To return both as a map:

output "target-groups-arn-alternatice" {
  value = {for k, v in aws_lb_target_group.target-group: k => v.arn}
}
target-groups-arn-alternatice = {
  "targetgroup1" = "arn:aws:elasticloadbalancing:us-east-1:xxxx:targetgroup/example-example/285b26e15221b113"
  "targetgroup2" = "arn:aws:elasticloadbalancing:us-east-1:xxxx:targetgroup/example-example2/075bd58359e4c4b2"
}

To return both as a list (order will be same as for keys function):

output "target-groups-arn" {
  value = values(aws_lb_target_group.target-group)[*].arn
}
target-groups-arn = [
  "arn:aws:elasticloadbalancing:us-east-1:xxxx:targetgroup/example-example/285b26e15221b113",
  "arn:aws:elasticloadbalancing:us-east-1:xxxx:targetgroup/example-example2/075bd58359e4c4b2",
]