Search code examples
terraformterraform-provider-awsterraform-provider-azureterraform-provider-gcp

Populate Array of Objects While Iterating in Terraform


I want to create an object called my_obj which will have an array inside called "values". This "values" should have 'another_obj' which is of type 'array of objects' with multiple objects & it's attribute which is having only 'description'.

locals{
another_obj = [{
description = "my_description_1"
},
{
description = "my_description_2"
}]
}

// this part needs to be corrected

my_obj = {
for_each = { for entry in local.another_obj : entry.name => entry }
//Array named as value which I want to create  
"values" = [
{
description = each.value.description,
type = "STRING",
}]
}` `

I am expecting 'my_obj' to look something like

my_obj = {
"values" = [
{
description = "my_description_1",
type = "STRING"
},
{
description = "my_description_2",
type = "STRING",
}
]
}

Solution

  • You can achieve what you want as follows:

    locals {
      my_obj = {
        values = [for value in local.another_obj:
          {
            description = value.description,
            type = "STRING"
          }
        ]
      }
    }
    

    p.s. each is only used in resource or module blocks, not in regular loops.