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

如何使用Python获取Azure特定资源组的成本明细?

获取Azure资源组成本明细的实现方案

一、适用模块

推荐使用Azure官方的azure-mgmt-costmanagement模块,这是专门针对成本管理场景封装的SDK,比直接调用REST API更简洁易维护。如果偏好原生HTTP请求,也可以直接调用Cost Management的REST API,但SDK能省去很多参数拼接和响应解析的工作。

安装SDK命令:

pip install azure-mgmt-costmanagement

二、所需权限

服务主体(即你的Client ID对应应用)需要以下任一权限,权限需分配在订阅级别或目标资源组级别:

  • Cost Management Reader:只读权限,仅用于查询成本数据,适合仅查看需求
  • Cost Management Contributor:可读写成本数据,支持配置预算、警报等操作
  • Reader:订阅级只读权限,可查看包括成本在内的所有资源数据
  • Contributor:订阅级读写权限,拥有资源管理和成本查询的完整权限

三、代码示例(基于SDK)

结合你现有认证逻辑,修改代码实现资源组成本明细查询:

from azure.identity import ClientSecretCredential
from azure.mgmt.costmanagement import CostManagementClient
from datetime import datetime, timedelta
import requests

subscription_id = 'MYSUBID'
client_id = 'MYCLIENTID'
client_secret = 'MYSECRETVALUE'
tenant_id = 'MYTENANTID'

# 初始化认证和成本管理客户端
credential = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
cost_client = CostManagementClient(credential, subscription_id)

# 获取资源组列表(复用原有逻辑)
rg_url = f"https://management.azure.com/subscriptions/{subscription_id}/resourcegroups?api-version=2021-04-01"
access_token = credential.get_token("https://management.azure.com/.default")
headers = {"Authorization": f"Bearer {access_token.token}"}
response = requests.get(rg_url, headers=headers)

if response.status_code == 200:
    resource_groups = response.json()
    # 设置查询时间范围(过去30天)
    start_date = (datetime.today() - timedelta(days=30)).strftime("%Y-%m-%d")
    end_date = datetime.today().strftime("%Y-%m-%d")
    
    for rg in resource_groups['value']:
        rg_name = rg['name']
        print(f"=== 资源组 {rg_name} 成本明细 ===")
        
        # 构建成本查询参数
        cost_query = {
            "type": "ActualCost",
            "timePeriod": {"start": start_date, "end": end_date},
            "dataset": {
                "granularity": "Daily",
                "aggregation": {"totalCost": {"name": "Cost", "function": "Sum"}},
                "grouping": [
                    {"type": "Dimension", "name": "ResourceGroupName"},
                    {"type": "Dimension", "name": "ResourceType"}
                ]
            },
            "filter": {
                "and": [
                    {"dimension": {"name": "ResourceGroupName", "operator": "In", "values": [rg_name]}}
                ]
            }
        }
        
        # 执行查询并输出结果
        query_result = cost_client.query.usage(f"/subscriptions/{subscription_id}", cost_query)
        if query_result.rows:
            print("日期\t\t资源类型\t\t总成本")
            for row in query_result.rows:
                print(f"{row[0]}\t{row[1]}\t{row[2]}")
        else:
            print("无成本数据")
        print("\n")
else:
    print(response.status_code, "-", response.text)

四、REST API调用方式(可选)

若不使用SDK,可直接调用Cost Management的查询API,请求端点:

POST https://management.azure.com/subscriptions/{subscriptionId}/providers/Microsoft.CostManagement/query?api-version=2023-11-01

请求体结构与上述SDK中的cost_query参数一致,认证方式与你获取资源组的逻辑相同,使用https://management.azure.com/.default的访问令牌。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 04:46:13