Azure Policy 检查空值

Azure Policy check for an empty value

我需要一个用于标记的 Azure Policy。我希望用户需要在创建资源组时定义标签。该政策还应检查 tagvaule 是否不为空。

我尝试了以下方法:

{
  "properties": {
    "displayName": "Require a tag Billto and a value that is not empty",
    "policyType": "Custom",
    "mode": "All",
    "description": "Enforces a required tag and its value on resource groups.",
    "metadata": {
      "category": "Tags",
    },
    "parameters": {
      "tagName": {
        "type": "String",
        "metadata": {
          "displayName": "Tag Name",
          "description": "Name of the tag, such as 'Billto'"
        }
      },
      "tagValue": {
        "type": "String",
        "metadata": {
          "displayName": "Tag Value",
          "description": "Value of the tag, such as 'Costcenter'"
        }
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.Resources/subscriptions/resourceGroups"
          },
          {
            "field": "[concat('tags[', parameters('tagName'), ']')]",
            "exists": "false"
          },
          {
            "value": "[concat('tags[', parameters('tagValue'), ']')]",
            "equals": ""
          }
        ]
      },
      "then": {
        "effect": "deny"
      }
    }
  }

有人可以帮助我并给我正确的代码吗? 谢谢托马斯

此策略定义将拒绝给定标签具有空值或完全缺少标签的资源组:

{
  "properties": {
    "mode": "All",
    "parameters": {
      "tagName": {
        "type": "String",
        "metadata": {
          "displayName": "Tag Name",
          "description": "Name of the tag, such as 'Billto'"
        }
      }
    },
    "policyRule": {
      "if": {
        "allOf": [
          {
            "field": "type",
            "equals": "Microsoft.Resources/subscriptions/resourceGroups"
          },
          {
            "anyOf": [
              {
                "field": "[concat('tags[', parameters('tagName'), ']')]",
                "exists": false
              },
              {
                "field": "[concat('tags[', parameters('tagName'), ']')]",
                "equals": ""
              }
            ]
          }
        ]
      },
      "then": {
        "effect": "deny"
      }
    }
  }
}

分解:

  1. parameters('tagName') 解析为参数 tagName 的值。对于此示例的其余部分,我们将使用 Billto 作为标签名称。
  2. "field": "[concat('tags[', parameters('tagName'), ']')]" 解析为 "field": "tags[Billto]"
  3. "field": "tags[Billto]" 将得到 Billto 标签的 value
  4. 如果资源没有 Billto 标签,Billto 标签将没有值,因此 "exists" : false 将为真,策略将拒绝。如果 Billto 标签的值为空,则 "equals": "" 为真,策略将拒绝。