为什么这个条件语句不能通过Terraform计划



我试图在terraform中运行一个循环,该循环根据条件语句从列表中分配效果。此条件语句旨在确保将所需效果分配给正确的策略列表保存在一个变量中,如下所示:

variable "builtin_policies" {
description = "List of objects consisting of: built in policy names and chosen effect"
type        = list(object({ displayName = string, effect = string }))
default = [
{
displayName : "API Management service should use a SKU that supports virtual networks",
effect : "Audit"
},
{
displayName : "Configure API Management services to disable public network access",
effect : "Disabled"
},
{
displayName : "API Management services should disable public network access",
effect : "AuditIfNotExists"
}
]

策略分配在填充了策略数据的JSON文件中循环。(内置策略的副本(策略分配:

resource "azurerm_management_group_policy_assignment" "this" {
for_each = { for f in local.raw_data : f.name => f }
name     = "${var.environment}-${random_integer.this.result}"

display_name         = each.value.displayName
description          = each.value.description
policy_definition_id = azurerm_policy_definition.this[each.key].id
management_group_id  = data.azurerm_management_group.this.id
parameters           = jsonencode({
effect = {
value = "${values( { for key, value in var.builtin_policies:
key => value.effect 
if value.displayName == each.value.displayName} )[0]}"
}
})

}

if语句返回以下错误:

Error: Invalid index
on main.tf line 135, in resource "azurerm_management_group_policy_assignment" "this":
135: if value.displayName each.value.displayName} ).0}"
each.value.displayName is "App Service apps should be injected into a virtual network"
var.builtin_policies is list of object with 112 elements
The given key does not identify an element in this collection value: the collection has no elements.

但如果我将以下内容打印到地形控制台中,我会得到预期值:

> values({for key, value in var.builtin_policies : key => value.effect if value.displayName == "Configure Azure Defender for Azure SQL database to be enabled"})[0]
"Disabled"
>

为什么条件语句失败?这两个条件词之间的唯一区别是硬编码字符串。但这应该不是问题,因为错误告诉我们each.value.displayName中的字符串是正确的。有什么想法吗?

我会尝试用try()方法替换"${..}

try(values( { for key, value in var.builtin_policies:          key => value.effect           if value.displayName == each.value.displayName} )[0], "None")

或者,

value = try(var.builtin_policies[index([for s in var.builtin_policies : s.displayName], each.value.displayName)].effect, "None")

最新更新