使用Terraform动态块创建Azure App配置密钥时遇报错
问题解决:Terraform创建Azure App配置报错的修复
错误原因
你对azurerm_app_configuration_key资源的结构理解有误:该资源每个实例对应单个键值对,并不支持通过dynamic "key"块在一个资源里嵌套多个key。你之前的写法试图在单个资源中定义多个key,违反了资源的Schema要求,因此抛出"Required attribute 'key' not specified"错误。
解决方案
需要先将嵌套的配置数据扁平化,生成包含每个键值对完整信息(label、key、value)的集合,再通过for_each遍历创建对应的资源实例。
步骤1:扁平化配置数据
在locals块中添加逻辑,将嵌套结构转换成扁平的键值对集合:
locals { configurations = { label1 = { key1 = "value1", key2 = "value2", }, label2 = { key1 = "value2", key3 = "value3", key4 = "value4", } } # 扁平化处理:生成每个键值对的唯一标识和完整信息 app_config_keys = merge([ for label, keys in local.configurations : { for key_name, key_value in keys : "${label}.${key_name}" => { label = label key = key_name value = key_value } } ]...) }
步骤2:创建Azure App配置键值对资源
使用扁平化后的集合遍历创建资源,注意configuration_store_id要引用你实际创建的Azure App配置存储实例的ID:
# 先创建Azure App配置存储实例(示例) resource "azurerm_app_configuration" "example" { name = "example-app-config" resource_group_name = azurerm_resource_group.example.name location = azurerm_resource_group.example.location } # 遍历创建每个键值对资源 resource "azurerm_app_configuration_key" "example" { for_each = local.app_config_keys configuration_store_id = azurerm_app_configuration.example.id key = each.value.key label = each.value.label value = each.value.value }
关键说明
azurerm_app_configuration_key的必填字段为key、configuration_store_id和value,label是可选字段,需直接在资源块中定义,而非嵌套结构。- 扁平化后的集合用
${label}.${key}作为唯一键,确保for_each能正确识别每个独立的键值对实例。
内容的提问来源于stack exchange,提问作者bugracetin
相关产品推荐
相关产品推荐

