resource "aws_lb_target_group_attachment" "alb-tg-attachment" {
for_each = {
for item in local.alb_list : "${item.key}-${item.instances}" => item
}
target_group_arn = aws_lb_target_group.alb-tg[each.value.key].arn
target_id = each.value.instances
port = each.value.port
}
locals {
environment = terraform.workspace
alb = {
xxx = {
port = 9106
instances = [aws_instance.web.id, aws_instance.web-1.id]
health = "/health"
}
yyy = {
port = 9106
instances = [aws_instance.web.id, aws_instance.web-1.id]
health = "/health"
}
}
alb_list = flatten([
for key, config in local.alb : [
for instance in config.instances : {
key = key
port = config.port
instances = instance
health = config.health
}
]
])
}
Error:
│ Error: Invalid for_each argument
│
│ on alb.tf line 76, in resource "aws_lb_target_group_attachment" "alb-tg-attachment":
│ 76: for_each = {
│ 77: for item in local.alb_list : "${item.key}-${item.instances}" => item
│ 78: }
│ ├────────────────
│ │ local.alb_list is tuple with 2 elements
│
│ The "for_each" map includes keys derived from resource attributes that cannot be determined until apply, and so Terraform cannot determine the full set of keys
│ that will identify the instances of this resource.
│
│ When working with unknown values in for_each, it's better to define the map keys statically in your configuration and place apply-time results only in the map
│ values.
│
│ Alternatively, you could use the -target planning option to first apply only the resources that the for_each value depends on, and then apply a second time to
│ fully converge.