Terraform - for_each used with unknown values

Hi everyone,

Trying to create a load balancer for 2 instances and got stucked over an error when using
for_each :

resource "aws_lb_target_group_attachment" "wordpress" {

  for_each = toset([aws_instance.wordpress-app-eu-west-2b.id, aws_instance.wordpress-app-eu-west-2a.id])
  target_group_arn = aws_lb_target_group.wordpress.arn
  target_id = each.key
  port = 80

  depends_on = [

When doing a terraform plan I get the following error:

Error: Invalid for_each argument

on main.tf line 391, in resource "aws_lb_target_group_attachment" "wordpress":
391:   for_each = toset([aws_instance.wordpress-app-eu-west-2b.id, aws_instance.wordpress-app-eu-west-2a.id])

aws_instance.wordpress-app-eu-west-2a.id is a string, known only after apply
aws_instance.wordpress-app-eu-west-2b.id is a string, known only after apply

The "for_each" set includes values 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 use a map value where the keys are defined statically in your configuration and where only the values contain apply-time results.

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.

Thanks in advance!