如何修改Azure Policy实现仅为特定资源组内新建资源添加标签?
问题分析
原策略之所以给资源组加标签,核心原因有两个:
- DeployIfNotExists默认在资源组范围执行部署,模板里的
Microsoft.Resources/tags资源会作用于资源组 - 没有排除资源组本身作为目标对象,也未限定要处理的资源范围
调整后的策略方案
以下是修改后的策略,实现仅为指定资源组内的新建资源添加标签,且不会影响资源组本身:
{ "mode": "Indexed", "parameters": { "targetResourceGroupName": { "type": "String", "metadata": { "displayName": "目标资源组名称", "description": "仅为该资源组内的资源添加标签" } }, "requiredTagKey": { "type": "String", "defaultValue": "Environment", "metadata": { "displayName": "必填标签键", "description": "检查是否存在的标签键" } }, "enforcedTagKey": { "type": "String", "defaultValue": "department", "metadata": { "displayName": "要添加的标签键", "description": "自动添加的标签键" } }, "enforcedTagValue": { "type": "String", "defaultValue": "dev", "metadata": { "displayName": "要添加的标签值", "description": "自动添加的标签值" } } }, "policyRule": { "if": { "allOf": [ { "field": "tags[parameters('requiredTagKey')]", "exists": "false" }, { "field": "resourceGroup", "equals": "[parameters('targetResourceGroupName')]" }, { "not": { "field": "type", "equals": "Microsoft.Resources/subscriptions/resourceGroups" } } ] }, "then": { "effect": "DeployIfNotExists", "details": { "type": "[field('type')]", "deploymentScope": "resource", "roleDefinitionIds": [ "/providers/Microsoft.Authorization/roleDefinitions/4a9ae827-6dc8-4573-8ac7-8239d42aa03f" ], "deployment": { "properties": { "mode": "Incremental", "parameters": { "resourceId": { "value": "[field('id')]" }, "enforcedTagKey": { "value": "[parameters('enforcedTagKey')]" }, "enforcedTagValue": { "value": "[parameters('enforcedTagValue')]" } }, "template": { "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "resourceId": { "type": "String" }, "enforcedTagKey": { "type": "String" }, "enforcedTagValue": { "type": "String" } }, "resources": [ { "type": "Microsoft.Resources/tags", "apiVersion": "2021-04-01", "name": "default", "scope": "[parameters('resourceId')]", "properties": { "tags": { "[parameters('enforcedTagKey')]": "[parameters('enforcedTagValue')]" }, "operation": "Merge" } } ] } } } } } } }
关键调整说明
- 限定目标资源与排除资源组:通过
allOf组合条件,指定仅处理targetResourceGroupName下的资源,同时排除资源组类型本身 - 部署范围改为资源级别:添加
"deploymentScope": "resource",让部署在单个资源的范围内执行,而非资源组 - 模板针对具体资源操作:使用
scope属性指定标签操作的目标资源ID(来自当前匹配的资源),并通过Merge操作保留资源原有标签,仅添加新标签 - 权限角色调整:使用
4a9ae827-6dc8-4573-8ac7-8239d42aa03f(资源策略参与者角色),该角色具备修改资源标签的权限,比原资源组参与者更精准
内容的提问来源于stack exchange,提问作者Quies
相关产品推荐
相关产品推荐

