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

如何使用Python获取Azure资源组的实际成本

解决Azure资源组实际成本汇总问题

你当前调用的usageDetails接口返回的是单条资源的使用明细,要获取资源组维度的实际成本总计,可通过以下两种方案实现:

方案1:使用Consumption Query API直接获取汇总数据

该API支持类SQL的查询语法,可直接按资源组分组并求和实际成本,效率更高。

修改后的Python代码示例:

import requests

# 替换为你的订阅ID和目标时间范围
subscription_id = "000000-0000-0000-0000-00000000000000"
start_date = "2024-01-01"
end_date = "2024-01-31"

url = f"https://management.azure.com/subscriptions/{subscription_id}/providers/Microsoft.Consumption/query?api-version=2023-11-01"

# 构建查询:按资源组分组,求和实际成本
query_payload = {
    "type": "ActualCost",
    "timePeriod": {
        "start": start_date,
        "end": end_date
    },
    "dataset": {
        "granularity": "None",  # 不按时间细分,直接返回总计
        "aggregation": {
            "totalCost": {
                "name": "PreTaxCost",
                "function": "Sum"
            }
        },
        "grouping": [
            {
                "type": "Dimension",
                "name": "ResourceGroup"
            }
        ]
    }
}

headers = {
    "Authorization": f"Bearer {access_token.token}",
    "Content-Type": "application/json"
}

response = requests.post(url, json=query_payload, headers=headers)

if response.status_code == 200:
    cost_summary = response.json()
    # 遍历结果,输出每个资源组的总成本
    for row in cost_summary['properties']['rows']:
        resource_group = row[0]
        total_cost = row[1]
        print(f"资源组 {resource_group} 的实际成本: {total_cost} USD")

方案2:对usageDetails返回的明细做本地聚合

如果坚持使用usageDetails接口,可在获取明细后按资源组分组求和:

修改后的代码示例:

import requests
from collections import defaultdict

url = "https://management.azure.com/subscriptions/000000-0000-0000-0000-00000000000000/providers/Microsoft.Consumption/usageDetails?api-version=2023-05-01&metric=actualcost"

headers = {
     "Authorization": f"Bearer {access_token.token}"
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
    cost_details = response.json()
    # 初始化字典存储每个资源组的成本总和
    rg_costs = defaultdict(float)
    
    # 遍历每条明细,累加资源组成本
    for item in cost_details.get('value', []):
        rg_name = item.get('properties', {}).get('resourceGroup', '未分组')
        actual_cost = item.get('properties', {}).get('actualCost', 0.0)
        rg_costs[rg_name] += actual_cost
    
    # 输出结果
    for rg, total in rg_costs.items():
        print(f"资源组 {rg} 的实际成本: {round(total, 2)} USD")

注意事项

  • 确保账号拥有Cost Management Reader或更高权限,否则会返回权限错误。
  • 时间范围:usageDetails默认返回最近30天数据,Query API需明确指定start和end日期。
  • 货币单位:返回成本默认是订阅结算货币,需转换可在查询中指定currency参数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 08:43:23