terraform loop through ids list and generate data blocks from it (and access it again)

Viewed 698

Is it possible to have a terraform list of ids (as string), like so:

locals  {
  secrets = [
    "cloud.secret.id1",
    "cloud.secret.id2",
    "cloud.secret.id3",
  ]
}

and create dynamically data for all those ids,

data "google_secret_manager_secret_version" "basic" {
  for_each = toset(locals.secrets)
  secret = each.key
}

and then find a way to access a property inside each of those resources in the array again?

1 Answers

The use of for_each will result in data.google_secret_manager_secret_version.basic being a map with keys from your locals.secrets.

So you access it by referencing individuals elements in the map, e.g.:

data.google_secret_manager_secret_version.basic["cloud.secret.id2"].secret_data

or using for_each in some resource:

resourece "google_xxxx" "test" {
  for_each = toset(locals.secrets)
  secret   = data.google_secret_manager_secret_version.basic[each.key].secret_data
}
Related