0

我需要用于标记的 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"
      }
    }
  }

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

4

1 回答 1

2

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

{
  "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
  4. 如果资源没有Billto标签,Billto则标签不会有值,因此"exists" : false将为 true 并且策略将拒绝。如果Billto标签的值为空,则为"equals": ""真,策略将拒绝。
于 2020-04-23T08:12:08.180 回答