Home > other >  Terraform iterate through values
Terraform iterate through values

Time:06-01

Newbie question: Is there any way to loop the variable to storing in mentioned code?. below is my configurations variable.

config= [{  
"name" = shared_preload_libraries,
"values" = ["EXAMPLE1", "EXAMPLE2"]
},
{
"name" = "azure.extensions"
"values" = ["EXAMPLE1", "EXAMPLE2", "EXAMPLE3"]
}]

I need to iterate in such a way that, for each name in variable the corresponding values should inserterd one by one in below code.

 resource "azurerm_postgresql_flexible_server_configuration" "example" {
  name      = name
  server_id = azurerm_postgresql_flexible_server.example.id
  value     = values 
}

CodePudding user response:

You have to flatten your config as follows:

locals {
  flat_config = merge([
      for single_config in var.config: {
        for value in single_config.values: 
          "${single_config.name}-${value}" => {
              "name" = single_config.name
              "value" = value
          }
      }
    ]...) # do NOT remove the dots
}

then

 resource "azurerm_postgresql_flexible_server_configuration" "example" {
  for_each  = local.flat_config
  name      = each.value.name
  server_id = azurerm_postgresql_flexible_server.example.id
  value     = each.value.value
}
  • Related