Error while creating resources on terraform 1.7.0

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.

Hi @Shubham1406220,

The value for ${item.instances} is derived from the computed id attribute of each aws_instance, which won’t be known until after they are created. The error is attempting to explain that you can’t use unknown values to identify other instances. You will need to choose a static value for each of the aws_lb_target_group_attachment instances, even if it’s something simple like xxx-1, xxx-2, etc.

Hello @jbardin , How can i escape the issue by assigning a static value since i don’t want to run the tf in steps.

To directly use the suggestion from my last comment, record the index of each of instances and use that as part of the for_each key,

  alb_list = flatten([
    for key, config in local.alb : [
      for idx, instance in config.instances : {
        key       = key
        index     = idx
        port      = config.port
        instances = instance
        health    = config.health
      }
    ]
  ])

and the for expression would look like

 for item in local.alb_list : "${item.key}-${item.index}" => item

Thank @jbardin . This resolved my issue