简体   繁体   中英

How to use Terraform for_each resource block and count resource block

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM