使用JSON在Azure中创建多值标签并应用到新建资源组求助
需求实现JSON方案
我们可以通过两个JSON文件实现需求,可根据实际场景选择是否全局约束标签取值:
如果你不需要在整个订阅层面限制Department标签的可选值,仅需要在创建Test-RG时限定可选范围,仅使用第二部分的ARM模板即可完成需求。
1. 全局约束Department标签可选值的Azure Policy定义JSON
该Policy会在订阅范围内生效,强制所有资源(包括资源组)的Department标签值只能从预设的四个选项中选择,避免出现不符合规范的标签值:
{ "properties": { "displayName": "Allowed Department tag values", "policyType": "Custom", "mode": "Indexed", "description": "Restrict Department tag to predefined allowed values", "policyRule": { "if": { "allOf": [ { "field": "tags['Department']", "exists": true }, { "not": { "field": "tags['Department']", "in": [ "Technology", "Finance", "Manufacturing", "Sales and Marketing" ] } } ] }, "then": { "effect": "deny" } } } }
将上述内容保存为department-tag-policy.json,分配到对应订阅后即可生效。
2. 创建带指定Department标签的Test-RG资源组ARM模板JSON
模板内已预设Department标签的四个可选值,部署时可直接选择对应值,也可直接修改默认值为你需要的选项:
{ "$schema": "https://schema.management.azure.com/schemas/2018-05-01/subscriptionDeploymentTemplate.json#", "contentVersion": "1.0.0.0", "parameters": { "rgName": { "type": "string", "defaultValue": "Test-RG" }, "rgLocation": { "type": "string", "defaultValue": "chinaeast2" }, "departmentTagValue": { "type": "string", "allowedValues": [ "Technology", "Finance", "Manufacturing", "Sales and Marketing" ], "defaultValue": "Technology" } }, "resources": [ { "type": "Microsoft.Resources/resourceGroups", "apiVersion": "2022-09-01", "name": "[parameters('rgName')]", "location": "[parameters('rgLocation')]", "tags": { "Department": "[parameters('departmentTagValue')]" } } ] }
将上述内容保存为test-rg-deploy.json,在订阅级别部署该模板即可创建符合要求的Test-RG资源组。
内容的提问来源于stack exchange,提问作者Juber
相关产品推荐
相关产品推荐

