How to fix Error: Invalid for_each argument when using nested for loops

I’m trying this:

data "aws_network_interfaces" "db_proxy_enis_list" {
  for_each = {
    for cluster in aws_rds_cluster.db_cluster: cluster.cluster_identifier => cluster
  }

  filter {
    name   = "vpc-id"
    values = [var.vpc_id]
  }
  filter {
    name   = "subnet-id"
    values = var.public_subnets
  }

  filter {
    name   = "description"
    values = ["Network interface for DBProxy ${each.key}"]
  }

  filter {
    name   = "security-group-ids"
    values = [aws_security_group.db_proxy_security.id]
  }
}

locals {
  enis_ids = flatten([
    for enis in data.aws_network_interfaces.db_proxy_enis_list : [
      for id in enis.ids : {
        id = id
      }
    ]
  ])
}

data "aws_network_interface" "aws_network_interface_enis" {
  for_each = { for enis in local.enis_ids : enis.id => enis }
  id       = each.value.id
}

But I keep getting this error:

Error: Invalid for_each argument
│
│ on rds.tf line 221, in data "aws_network_interface" "aws_network_interface_enis":
│ 221: for_each = { for enis in local.enis_ids : enis.id => enis }
│ ├────────────────
│ │ local.enis_ids will be known only after apply
│
│ 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.

The error is likely complaining about the keys being derived from the aws_network_interfaces data source, which is dynamically loaded on apply. Unfortunately it’s a limitation of for_each. This GitHub issue also provides more details. You might need to find an alterative way to get the ENI info you need.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.