Using each to build expressions referring to non-for_each resources/data

I’ve come up with a hack to use each to refer to resources/data even when the target resources are not built with for_each. But it has an annoying extra step. Is there a better solution?

Here’s my ideal use-case:

locals {
root_folders = [
“internal”,
“secure”,
]
}

resource “google_folder” “root” {
for_each = toset(local.root_folders)
display_name = each.value
parent = data.google_organization.my-org.name
}

resource “google_folder_iam_policy” “root” {
for_each = google_folder.root
folder = each.value.name
policy_data = local.root_policies[each.key]
policy_data = data.google_iam_policy[each.key].policy_data # <- problem
}

data “google_iam_policy” “folder_internal” {

}

data “google_iam_policy” “folder_secure” {

}

I can’t get the line marked “problem” to work. Maybe there is some feature I missed?

My hack is to add another local map:

locals {
root_policies = {
internal = data.google_iam_policy.folder_internal.policy_data
secure = data.google_iam_policy.folder_secure.policy_data
}
}

And then update “problem” to:

policy_data = local.root_policies[each.key]

But this is not a great solution, since later engineers will need to know to update this intermediate map - which itself doesn’t accomplish anything.

Thanks for any bright ideas!

Hi @rvandegrift,

That is indeed the recommended answer, because it allows Terraform to properly understand what google_folder_iam_policy.root depends on: in this case, it depends indirectly on both data.google_iam_policy.folder_internal and data.google_iam_policy.folder_secure via local.root_policies. Understanding dependencies between resources is a critical part of how Terraform works, which is why only statically-defined references are allowed.