Terraform模块为Azure FrontDoor配置嵌套循环的报错求解
错误原因
- 同一Terraform资源块中不能同时声明
count和for_each参数,二者只能二选一。 - 嵌套
for表达式构造对象时,外层必须为每个元素指定明确的键,不能直接返回列表类型的值。
实现思路
先将多台Front Door实例的所有前端端点展平为单层唯一键值对集合,再传入资源的for_each参数即可实现批量创建,无需把嵌套循环直接写在资源块内。
正确配置示例
1. 定义展平的前端端点局部变量
locals { # 合并所有Front Door的前端端点为单个Map,键为前端端点唯一ID all_frontend_endpoints = merge([ for fd in azurerm_frontdoor.front_door : { for fe_name, fe in fd.frontend_endpoint : fe.id => { frontend_id = fe.id frontend_name = fe_name } } ]...) }
2. 自定义HTTPS配置资源块
resource "azurerm_frontdoor_custom_https_configuration" "custom_https_configuration" { for_each = local.all_frontend_endpoints frontend_endpoint_id = each.value.frontend_id custom_https_provisioning_enabled = each.value.frontend_name != "front_door" ? local.frontend_https_configurations[each.value.frontend_name].custom_https_provisioning_enabled : false dynamic "custom_https_configuration" { for_each = (each.value.frontend_name != "front_door" && local.frontend_https_configurations[each.value.frontend_name].custom_https_provisioning_enabled) ? [1] : [] content { certificate_source = "AzureKeyVault" azure_key_vault_certificate_secret_name = "替换为你的证书密钥名称" azure_key_vault_certificate_secret_version = "替换为你的证书密钥版本" azure_key_vault_certificate_vault_id = "替换为你的Key Vault资源ID" } } }
关键说明
- 用
merge+列表展开运算符...将嵌套的前端端点集合合并为单层Map,键使用前端端点的唯一资源ID,避免资源索引变化导致的意外重建。 - 局部变量中存储的
frontend_name属性可直接关联你预先定义的local.frontend_https_configurations配置集合,无需额外查询。 - 若不需要复用展平后的端点集合,可直接将
local.all_frontend_endpoints的表达式写入资源的for_each参数中,单独提取为局部变量仅为提升配置可读性。
内容的提问来源于stack exchange,提问作者ossentoo
相关产品推荐
相关产品推荐

