Search code examples
terraformhclhashicorp

Use attribute KEY and VALUE of a map inside a list element


I have defined a List called data, inside the list, i use a map with a key and a value. I now need to access the KEY and VALUE inside each element of the data list.

locals {
      data = [
        { "secret1" = 1 },
        { "secret2" = 1 },
        { "secret3" = 1 },
        { "secret4" = 1 },
        { "secret5" = 1 }
      ]
    }

The goal is to use the KEY and VALUE inside a google secret resource, the value should then be used inside secret and version attribute. Something like this:

data "google_secret_manager_secret_version" "secret_datas" {
  count   = length(local.data)
  secret  = local.data[count.index].key
  project = "myproject"
  version = local.data[count.index].value
}

My Current Error Message

│ Error: Unsupported attribute
│ 
│   on dependabot.tf line 38, in data "google_secret_manager_secret_version" "secret_data":
│   38:   version = local.data[count.index].value
│     ├────────────────
│     │ count.index is 1
│     │ local.data is tuple with 5 elements
│ 
│ This object does not have an attribute named "value".

Solution

  • This would be much easier with the modern for_each meta-argument. After optimizing the structure of the data in the locals:

    locals {
      data = {
        "secret1" = 1,
        "secret2" = 1,
        "secret3" = 1,
        "secret4" = 1,
        "secret5" = 1
      }
    }
    

    we can easily use it in the resource.

    data "google_secret_manager_secret_version" "secret_datas" {
      for_each = local.data
      
      secret  = each.key
      project = "myproject"
      version = each.value
    }