我正在尝试创建一个审核虚拟机的 azure 策略。我想要满足的条件是虚拟机具有参数指定的所有标签,并且所有这些相应的标签都包含一个值。我在下面工作的第一个条件。然而,确定它们是否为空有点更具挑战性,因为看起来您不能在字段键中使用 current() 。
{
"parameters": {
"requiredTags": {
"type": "Array",
"metadata": {
"displayName": "Required Tags",
"description": "The list of tags that should exist on the virtual machine"
}
}
},
"policyRule": {
"if": {
"allof": [
{
"field": "type",
"equals": "Microsoft.Compute/VirtualMachines"
},
{
"count": {
"value": "[parameters('requiredTags')]",
"where": {
"field": "tags",
"containsKey": "[current()]"
}
},
"notEquals": "[length(parameters('requiredTags'))]"
},
{
"count": {
"value": "[parameters('requiredTags')]",
"where": {
"field": "[concat('tags[', current(), ']')]",
"notEquals": ""
}
},
"notEquals": "[length(parameters('requiredTags'))]"
}
]
},
"then": {
"effect": "audit"
}
}
}
最佳答案
这至少可以说是非常棘手的,而且似乎不存在这样的政策。尽管如此,我相信下面的 2 个选项可以解决问题 - 至少在我测试时是这样。
选项 1:
{
"not": {
"value": "[contains(string(field('tags')), '\"\"')]",
"equals": true
}
}
选项 2:
{
"value": "[indexOf(string(field('tags')), '\"\"')]",
"greaterOrEquals": 0
}
描述:
选项 1:
使用 contains
检查对象是否包含键或字符串是否包含子字符串。
容器
包含嵌套参数。
string
将指定值转换为字符串。在本例中,指定的值是 field = Tags
,它们是对象,而不是数组。在本例中,指定的值是 field=tags,它们是对象
,而不是数组
。
2 个标签的示例,“tagnumber1”的值为“value1”,“tagnumber2”的值为空:
"{\"tagnumber1\":\"value1\",\"tagnumber2\":\"\"}"
请注意,空值是 \"\"
- 这是我们的 itemToFind
。
选项 2:
使用 indexOf
返回字符串中值的第一个位置。
stringToSearch
包含嵌套参数。
stringToFind
为空。
string
将指定值转换为字符串。在本例中,指定的值是 field = Tags
,它们是对象
,而不是数组
。
2 个标签的示例,“tagnumber1”的值为“value1”,“tagnumber2”的值为空:
"{\"tagnumber1\":\"value1\",\"tagnumber2\":\"\"}"
请注意,空值为 \"\"
。
因此,我们必须搜索 \"\"
因为它代表对象中的空值。
该索引是从零开始的。如果未找到该项目,则返回 -1。整数表示项目的第一个索引,因此通过查看 "greaterOrEquals": 0
它只会返回找到的项目 - 意味着标签值为空。
链接:
- https://learn.microsoft.com/en-us/azure/governance/policy/concepts/definition-structure#fields
- https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-functions
- https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-expressions#escape-characters
- https://learn.microsoft.com/en-us/azure/templates/microsoft.compute/virtualmachines?pivots=deployment-language-arm-template#resource-format-1
关于json - 如何检查任何必需的标签是否为空 Azure Policy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75197850/