Azure资源组预算超限时如何限制资源创建及自定义策略
实现预算耗尽时限制Azure资源创建的自定义策略
以下是修改后的自定义策略,新增了预算限额与当前成本消耗的校验逻辑,仅当目标资源组的成本消耗达到或超过预算额度时,才会拒绝资源创建操作:
{ "properties": { "displayName": "Deny resource creation when budget is exhausted", "policyType": "Custom", "mode": "All", "description": "Restricts creation of Azure resources in the target resource group when current spend meets or exceeds the budget limit.", "metadata": { "createdBy": "62eddff1-******", "createdOn": "2023-05-26T05:08:07.5646255Z", "updatedBy": null, "updatedOn": null }, "parameters": { "resourceGroupName": { "type": "String", "metadata": { "displayName": "Target Resource Group", "description": "The name of the resource group where the budget is applied." } }, "budgetName": { "type": "String", "metadata": { "displayName": "Budget Name", "description": "The name of the budget configured for the resource group." } } }, "policyRule": { "if": { "allOf": [ { "field": "resourceGroup", "equals": "[parameters('resourceGroupName')]" }, { "anyOf": [ { "field": "type", "like": "Microsoft.*" } ] }, { "value": "[reference(resourceId('Microsoft.CostManagement/budgets', parameters('budgetName')), '2021-10-01').currentSpend.amount]", "greaterOrEquals": "[reference(resourceId('Microsoft.CostManagement/budgets', parameters('budgetName')), '2021-10-01').amount]" } ] }, "then": { "effect": "deny" } } } }
关键逻辑说明
- 参数配置:新增
resourceGroupName和budgetName两个参数,让策略可以灵活适配不同的资源组和预算,无需硬编码。 - 资源组匹配:通过
resourceGroup字段校验,确保策略仅作用于目标资源组内的资源创建操作。 - 预算与消耗校验:使用
reference函数读取指定预算的当前消耗金额(currentSpend.amount)和预算限额(amount),当消耗金额≥预算限额时,触发拒绝规则。 - 资源类型范围:保留原有的
Microsoft.*类型匹配,覆盖绝大多数Azure资源的创建操作。
注意事项
- 需确保目标资源组已提前创建好对应的100美元预算,且预算范围正确指向该资源组。
- Azure成本数据存在2-8小时的延迟,策略校验的消耗数据并非实时更新。
- 分配策略时,需确保执行主体拥有读取
Microsoft.CostManagement/budgets资源的权限。
内容的提问来源于stack exchange,提问作者Santosh Rao
相关产品推荐
相关产品推荐

