附加标签政策不适用于某些资源

时间:2019-05-10 09:41:16

标签: azure azure-policy

我正在创建一种将标签附加到新创建的资源上的天蓝色策略,该策略适用于大多数组件,但是我发现该策略不适用于某些组件,例如:逻辑应用程序。

{
  "mode": "All",
  "parameters": {
    "Environment": {
      "type": "String",
      "metadata": {
        "displayName": "Environment"
      },
      "defaultValue": "dev"
    },
    "Owner": {
      "type": "String",
      "metadata": {
        "displayName": "Owner"
      },
      "defaultValue": "Admin"
    },
    "CostCenter": {
      "type": "String",
      "metadata": {
        "displayName": "CostCenter"
      },
      "defaultValue": "NA"
    }
  },
  "policyRule": {
    "if": {
      "field": "tags",
      "exists": "false"
    },
    "then": {
      "effect": "append",
      "details": [
        {
          "field": "tags",
          "value": {
            "Environment": "[parameters('Environment')]",
            "Owner": "[parameters('Owner')]",
            "CostCenter": "[parameters('CostCenter')]"
          }
        }
      ]
    }
  }
}

我添加了一个类似的策略,将标签应用于资源组,根本不起作用,我不知道发生了什么。

{
  "mode": "All",
  "parameters": {
    "Environment": {
      "type": "String",
      "metadata": {
        "displayName": "Environment"
      },
      "defaultValue": "dev"
    },
    "Owner": {
      "type": "String",
      "metadata": {
        "displayName": "Owner"
      },
      "defaultValue": "admin"
    },
    "CostCenter": {
      "type": "String",
      "metadata": {
        "displayName": "CostCenter"
      },
      "defaultValue": "NA"
    }
  }
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "tags",
          "exists": "false"
        },
        {
          "field": "type",
          "equals": "Microsoft.Resources/subscriptions/resourceGroups"
        }
      ]
    },
    "then": {
      "effect": "append",
      "details": [
        {
          "field": "tags",
          "value": {
            "Environment": "[parameters('Environment')]",
            "Owner": "[parameters('Owner')]",
            "CostCenter": "[parameters('CostCenter')]"
          }
        }
      ]
    }
  }
}

1 个答案:

答案 0 :(得分:2)

自己弄清楚,我的策略中的"exists": "false"条件只会在“ tags”属性丢失或为null时触发,因此具有"tags": {}的资源组或资源甚至会绕过我的策略尽管它没有任何标签。

此外,对标签进行简单检查是不合理的,应按标签名称一一检查,如果不符合,请采取措施追加。

我还发现以下声明不适用于资源组,可能是因为这是不规范的做法。

{
  "then": {
    "effect": "append",
    "details": [
      {
        "field": "tags",
        "value": {
          "Environment": "[parameters('Environment')]",
          "Owner": "[parameters('Owner')]",
          "CostCenter": "[parameters('CostCenter')]"
        }
      }
    ]
  }
}

建议改用以下语句

{
  "then": {
    "effect": "append",
    "details": [
      {
        "field": "tags['Environment']",
        "value": "[parameters('Environment')]"
      },
      {
        "field": "tags['Owner']",
        "value": "[parameters('Owner')]"
      },
      {
        "field": "tags['CostCenter']",
        "value": "[parameters('CostCenter')]"
      }
    ]
  }
}