jsonazureterraformazure-app-configuration

Terraform iterating a json file for key value pairs


I have an appconfig.json file which contains the key value details for the azure app config. sample appConfig.json :

[
    {
        "contentType": "",
        "key": "FuncApp:Ihub:Common:D365Api:JobStatusRelativePath",
        "tags": {
        },
        "value": "/api/connector/jobstatus"
    },
    {
        "contentType": "application/vnd.microsoft.appconfig.keyvaultref+json;charset=utf-8",
        "key": "secretName",
        "label": null,
        "tags": {
        },
        "value": "{\"uri\":\"https://iac-key-vault-sandbox2.net/secrets/secretName\"}"
    }
]

Now inside a appconfig.tf file I want to read the contents of the json and iteratively assign the values to the azurerm_app_configuration_key. sample code

locals {
appConfigData = jsondecode(file("appConfig.json"))
}

resource "azurerm_app_configuration_key" "appConfigKey" {
configuration_store_id = azurerm_app_configuration.appConfiguration.id
for_each = [for element in local.appConfigData: local.appConfigData]
key                    = each.value.key
label                  = each.value.label
value                  = each.value.value
content_type           = each.value.contentType
}

I want to understand how to do this task as I have been failing to do so. I keep getting errors like:


╷
│ Error: Invalid for_each argument
│ 
│   on terraform_AppConfig.tf line 17, in resource "azurerm_app_configuration_key" "appConfigKey":
│   17:   for_each = [for element in local.appConfigData: local.appConfigData]
│     ├────────────────
│     │ local.appConfigData is tuple with 4 elements
│ 
│ The given "for_each" argument value is unsuitable: the "for_each" argument must be a map, or set of strings, and you have provided a value of type tuple.

Solution

  • This should work for you:

    locals {
      appConfigData = jsondecode(file("appConfig.json"))
    }
    
    resource "azurerm_app_configuration_key" "appConfigKey" {
      configuration_store_id = azurerm_app_configuration.appConfiguration.id
      for_each               = { for element in local.appConfigData : element.key => element }
      key                    = each.value.key
      label                  = each.value.label
      value                  = each.value.value
      content_type           = each.value.contentType
    }