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

如何使用Azure Python SDK获取Azure资源成本?已创建BillingManagementClient但不知如何查询成本信息

使用Azure Python SDK查询Azure资源成本的实操指南

嘿,我来帮你搞定这个问题!既然你已经创建了BillingManagementClient,那我们先从这个客户端的用法说起,再补充更适合资源级别成本查询的方案——毕竟后者才是获取具体资源成本的常用方式。

首先,确认必要权限

不管用哪个客户端,你的身份(服务主体或用户账号)都需要对应的权限才能查询成本数据,比如Cost Management Reader、Billing Reader或者更高权限(比如Contributor)。如果后续遇到403错误,先去Azure Portal检查角色分配是否正确。

方式一:用已创建的BillingManagementClient查询成本

这个客户端更多偏向账单账户、剖面级别的成本汇总,如果你需要的是账单整体或剖面的成本,可以这么用:

from azure.identity import DefaultAzureCredential
from azure.mgmt.billing import BillingManagementClient

# 假设你已经完成了这部分初始化
credential = DefaultAzureCredential()
subscription_id = "你的订阅ID"
billing_client = BillingManagementClient(credential, subscription_id)

# 替换成你的账单账户ID和账单剖面ID
billing_account_id = "xxxx-xxxx-xxxx-xxxx"
billing_profile_id = "xxxx-xxxx-xxxx"

# 获取账单剖面的成本摘要
cost_summary = billing_client.billing_profiles.get_cost_summary(
    billing_account_id=billing_account_id,
    billing_profile_name=billing_profile_id
)

# 打印核心成本信息
print(f"当前周期总成本: {cost_summary.total_cost.amount} {cost_summary.total_cost.currency}")
print("各时间段成本明细:")
for period in cost_summary.by_period:
    print(f"- {period.usage_start_date} 至 {period.usage_end_date}: {period.total_cost.amount} {period.total_cost.currency}")

不过要注意,这种方式没法直接拿到单个资源的成本,如果你需要资源级别的数据,推荐用下面的方案。

方式二:用CostManagementClient查询资源级成本

这是获取具体资源成本的更灵活方案,专门用于成本管理的查询。

步骤1:安装依赖包

如果还没装,先执行:

pip install azure-mgmt-costmanagement

步骤2:编写查询代码

下面的例子会查询过去30天内,订阅下所有资源的每日成本,并按资源ID和名称分组:

from azure.identity import DefaultAzureCredential
from azure.mgmt.costmanagement import CostManagementClient
from azure.mgmt.costmanagement.models import QueryDefinition, TimePeriod
import datetime

# 初始化客户端
credential = DefaultAzureCredential()
subscription_id = "你的订阅ID"
cost_client = CostManagementClient(credential)

# 构建查询规则:查询过去30天的实际成本,按资源分组
query_def = QueryDefinition(
    type="ActualCost",
    time_period=TimePeriod(
        start_date=(datetime.datetime.now() - datetime.timedelta(days=30)).strftime("%Y-%m-%d"),
        end_date=datetime.datetime.now().strftime("%Y-%m-%d")
    ),
    dataset={
        "granularity": "Daily",  # 可选Monthly/Daily
        "aggregation": {
            "totalCost": {"name": "Cost", "function": "Sum"}
        },
        "grouping": [
            {"type": "Dimension", "name": "ResourceId"},
            {"type": "Dimension", "name": "ResourceName"}
        ]
        # 如果只想查特定资源,添加过滤条件:
        # "filter": {
        #     "and": [
        #         {"dimension": {"name": "ResourceId", "operator": "In", "values": ["/subscriptions/xxx/resourceGroups/xxx/providers/Microsoft.Compute/virtualMachines/xxx"]}}
        #     ]
        # }
    }
)

# 执行查询,范围可以是订阅、资源组、管理组等
scope = f"/subscriptions/{subscription_id}"
result = cost_client.query.execute(scope, query_def)

# 解析并打印结果
print("资源成本明细:")
for row in result.rows:
    resource_id = row[0]
    resource_name = row[1]
    daily_cost = row[2]
    currency = result.columns[2].unit
    print(f"资源名称: {resource_name}\n资源ID: {resource_id}\n当日成本: {daily_cost} {currency}\n---")

几个关键注意点

  • 时间范围的格式必须是YYYY-MM-DD,不能包含时分秒
  • 范围参数scope可以灵活调整:比如资源组的范围是/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}
  • 如果查询结果为空,先检查时间范围是否正确,或者是否有资源产生成本
  • 权限问题:如果返回403,去Azure Portal给对应的身份分配Cost Management Reader角色

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 02:58:11