terraformterraform-provider-azureazure-app-configuration

Getting error when creating app configuration key with dynamic block in for_each


I need to create Azure App Configurations with using Terraform. In Terraform documentation, it gives the structure to create is:

Azure app config key creating

In my problem, I have configurations in this schema as a sample data:

locals {
  configurations = {
    label1 = {
      key1 = "value1",
      key2 = "value2",
    },
    label2 = {
      key1 = "value2",
      key3 = "value3",
      key4 = "value4",
    }
  }
}

Generating "label", "key", and "value" fields need to use these configurations value. So, I have created a code to implement it as you see in below:

resource "azurerm_app_configuration_key" "example" {
  for_each                = local.configurations
  configuration_store_id = example.id
  label                  = each.key
  dynamic "key" {
    for_each = each.value
    content {
      name  = key
      value = value
    }
  }
}

But it gives 'Required attribute "key" not specified: An attribute named "key" is required here' error.

How to solve this problem?


Solution

  • The documentation indicates that the resource indeed does not allow a key to be configured with a dynamic block.

    Instead, you must iterate over each key-label pair, as that uniquely defines a configuration key. You can achieve that by some Terraform list and map comprehension magic as follows:

    locals {
      resource_group_name = "..."
      location            = "..."
      configurations = {
        label1 = {
          key1 = "value1",
          key2 = "value2",
        },
        label2 = {
          key1 = "value2",
          key3 = "value3",
          key4 = "value4",
        }
      }
      key_labels = merge(
        [for label, config in local.configurations :
          { for key, value in config :
            "${label}-${key}" =>
            {
              "key"   = key,
              "value" = value,
              "label" = label
            }
          }
        ]...
      )
    }
    resource "azurerm_app_configuration" "test" {
      name                = "testconfig12345678"
      resource_group_name = local.resource_group_name
      location            = local.location
    }
    
    resource "azurerm_app_configuration_key" "test" {
      for_each               = local.key_labels
      configuration_store_id = azurerm_app_configuration.test.id
      key                    = each.value.key
      label                  = each.value.label
      value                  = each.value.value
    }