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

如何通过Azure Policy为所有Azure订阅强制添加并维护指定标签

强制为Azure租户所有订阅添加并维护指定标签方案建议

核心需求回顾

  • ✅ 已实现:为所有现有订阅添加指定标签(通过修复任务)
  • 待实现:
    • 新创建的订阅自动应用标签
    • 标签被修改/删除时自动修正

现有策略的不足

当前策略中使用的add操作仅会在标签不存在时添加,无法处理标签值被篡改或标签被删除的场景;需补充配置确保新订阅创建时能触发策略逻辑。

针对性修改建议

1. 修改策略的Modify操作类型

将原策略中operations里的operation从add改为addOrReplace,这样无论标签是不存在、值被修改还是被删除,都会强制替换为正确的标签值,满足自动修正的需求。

修改后的完整策略:

{
  "mode": "All",
  "policyRule": {
    "if": {
      "allOf": [
        {
          "field": "type",
          "equals": "Microsoft.Resources/subscriptions"
        },
        {
          "not": {
            "field": "[concat('tags[', parameters('tagName'), ']')]",
            "equals": "[concat(parameters('tagValuePrefix'), subscription().subscriptionId, '/')]"
          }
        }
      ]
    },
    "then": {
      "effect": "modify",
      "details": {
        "roleDefinitionIds": [
          "/providers/Microsoft.Authorization/roleDefinitions/4a9ae827-6dc8-4573-8ac7-8239d42aa03f"
        ],
        "operations": [
          {
            "operation": "addOrReplace",
            "field": "[concat('tags[', parameters('tagName'), ']')]",
            "value": "[concat(parameters('tagValuePrefix'), subscription().subscriptionId, '/')]"
          }
        ]
      }
    }
  },
  "parameters": {
    "tagName": {
      "type": "String",
      "metadata": {
        "displayName": "Tag Name",
        "description": "The name of the tag to add."
      },
      "defaultValue": "policy_config_path"
    },
    "tagValuePrefix": {
      "type": "String",
      "metadata": {
        "displayName": "Tag Value Prefix",
        "description": "The prefix for the tag value, excluding the subscription ID."
      },
      "defaultValue": "config/azure/mytenantname.com/subscriptions/"
    }
  }
}

2. 确保新订阅自动触发策略

由于策略已在**租户根级别(/)**分配,且模式设置为All、目标资源类型为Microsoft.Resources/subscriptions,新订阅创建时会自动触发Azure Policy的评估流程,自动应用标签。需确认以下两点:

  • 策略分配时已启用**“强制实施在新资源上”**(默认启用,可在分配设置中确认)
  • 策略分配的系统托管身份已获取租户根级别的标签参与者权限(对应策略中指定的角色ID,分配时Azure会自动为身份授予该权限,若未自动授予可手动添加)

3. 验证与补充配置

  • 手动触发策略评估:在Azure门户的策略分配页面,选择“评估资源”,可立即触发现有资源的重新评估,验证修正逻辑
  • 调整评估周期:默认策略评估周期为24小时,若需要更及时的修正,可在策略分配的“高级”设置中调整评估频率

内容的提问来源于stack exchange,提问作者DivZ

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 20:22:25