You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Azure Policy检查是否存在空白的必填标签

Azure Policy 审计VM标签:检查必填标签存在且非空

要创建审计Azure虚拟机的Policy,得满足两个要求:

  • VM必须包含参数指定的所有必填标签
  • 这些必填标签的值不能是空字符串

现在已经实现了第一个要求,但判断标签值是否为空时卡壳了——Azure Policy的field键里没法用current()函数。当前的Policy代码如下:

{
  "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"
    }
  }
}

解决方法

问题根源是field属性不支持在动态拼接的路径中使用current(),换用value表达式直接获取对应标签的值就能绕开这个限制。修正后的完整Policy代码如下:

{
  "parameters": {
    "requiredTags": {
      "type": "Array",
      "metadata": {
        "displayName": "必填标签",
        "description": "虚拟机上必须存在的标签列表"
      }
    }
  },
  "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": {
              "value": "[tags[current()]]",
              "notEquals": ""
            }
          },
          "notEquals": "[length(parameters('requiredTags'))]"
        }
      ]
    },
    "then": {
      "effect": "audit"
    }
  }
}

内容的提问来源于stack exchange,提问作者Jamie O'Connell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 00:35:27