Azure ARM模板如何自动将资源自身类型设为Context标签?
嘿,我正好处理过类似的需求,给你一个完美解决这个问题的方案:
首先,你之前用[resources('type')]报错是因为resources()函数的用法不对——它是用来引用模板中其他已定义资源的,语法是resources('resourceName'),没法直接获取当前资源的类型。而ARM模板里正好有个专门的函数type(),它会自动返回当前资源的完整类型(比如你要的"Microsoft.Web/serverfarms"),完全符合你的需求。
接下来给你具体怎么用:在资源的tags属性里,直接把Context标签的值设为[type()]就行,不用手动写任何资源类型,也不用为每种资源单独创建模板。举个实际的模板片段例子:
{ "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#", "contentVersion": "1.0.0.0", "variables": { "environmentTag": "Production", "ownerTag": "DevTeam" }, "resources": [ { "type": "Microsoft.Web/serverfarms", "apiVersion": "2022-09-01", "name": "myAppServicePlan", "location": "[resourceGroup().location]", "sku": { "name": "B1" }, "tags": { "Environment": "[variables('environmentTag')]", "Owner": "[variables('ownerTag')]", "Context": "[type()]" // 这里自动获取当前资源的类型 } }, { "type": "Microsoft.Web/sites", "apiVersion": "2022-09-01", "name": "myWebApp", "location": "[resourceGroup().location]", "dependsOn": [ "[resourceId('Microsoft.Web/serverfarms', 'myAppServicePlan')]" ], "properties": { "serverFarmId": "[resourceId('Microsoft.Web/serverfarms', 'myAppServicePlan')]" }, "tags": { "Environment": "[variables('environmentTag')]", "Owner": "[variables('ownerTag')]", "Context": "[type()]" // 这里会自动返回"Microsoft.Web/sites" } } ] }
这个方法的核心优势:
- 完全自动化,开发人员不需要手动填写任何资源类型信息
- 同一个模板可以复用在所有资源类型上,不用单独维护多套模板
type()函数在所有ARM资源类型上都能正常工作,返回的是标准的资源类型格式,完全满足计费标签的需求
另外补充一点:不管是根模板里的资源,还是嵌套模板里的资源,type()函数都能正确返回当前资源的类型,不用担心嵌套场景下失效。
内容的提问来源于stack exchange,提问作者Justin
相关产品推荐
相关产品推荐

