Home > front end >  How to use Terraform for_each resource block and count resource block
How to use Terraform for_each resource block and count resource block

Time:06-02

I am having a azurerm_postgresql_flexible_server resource using count and azurerm_postgresql_flexible_server_configuration using fore each. Please find the below code.

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

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
          }
      }
    ]...)
}

Below is my for_each resource

 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
}

currently I am having two azurerm_postgresql_flexible_server resources. azurerm_postgresql_flexible_server.example[0] and azurerm_postgresql_flexible_server.example[1]. Could you please let me know if there is a possibility to include some alternative options like count?

Splat Expressions did not work.

CodePudding user response:

If you want to apply your two azurerm_postgresql_flexible_server for each instance of azurerm_postgresql_flexible_server_configuration, you need one more extra level of flattening:

locals {
  flat_config = merge(flatten([
      for single_config in var.config: [        
        for value in single_config.values: {
          for idx, server in azurerm_postgresql_flexible_server.example:
          "${single_config.name}-${value}-${idx}" => {
              "name" = single_config.name
              "value" = value
              "flexible_server" = server
          }
        }  
      ]
    ])...)
}

then

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