如何使用Azure Python SDK获取VM、数据库等单个资源的成本
借助Azure Python SDK获取单个资源成本与价格信息
前提准备
- 安装必要的Python包:
azure-mgmt-costmanagement、azure-identity,执行命令:pip install azure-mgmt-costmanagement azure-identity - 确保你的Azure账号拥有Cost Management Reader或更高权限,且已通过
az login完成本地Azure身份认证
获取单个资源的实际产生成本
使用Cost Management SDK的query方法,通过指定资源ID过滤目标资源的成本数据:
from azure.identity import DefaultAzureCredential from azure.mgmt.costmanagement import CostManagementClient # 初始化客户端 credential = DefaultAzureCredential() cost_client = CostManagementClient(credential) # 替换为你的订阅ID和目标资源ID subscription_id = "你的订阅ID" resource_id = "/subscriptions/订阅ID/resourceGroups/资源组名称/providers/Microsoft.Compute/virtualMachines/VM名称" # 构建成本查询参数 cost_query = { "type": "ActualCost", "timeframe": "MonthToDate", "dataset": { "granularity": "Daily", "filter": { "and": [ {"dimensions": {"name": "ResourceId", "operator": "In", "values": [resource_id]}} ] }, "aggregation": { "totalCost": {"name": "Cost", "function": "Sum"} } } } # 执行查询并解析结果 query_result = cost_client.query.execute(subscription_id, cost_query) if query_result and query_result.properties and query_result.properties.rows: print(f"资源 {resource_id} 的累计成本: {query_result.properties.rows[0][0]} {query_result.properties.columns[0].name}") else: print("未获取到有效成本数据")
获取单个资源的预估定价信息
要获取资源的定价标准(比如VM小时单价、数据库计费规则),可通过以下方式实现(兼容已弃用的azure-mgmt-commerce包,也可直接调用Azure Retail Prices API):
from azure.identity import DefaultAzureCredential from azure.mgmt.commerce import UsageManagementClient # 初始化客户端 credential = DefaultAzureCredential() commerce_client = UsageManagementClient(credential, subscription_id) # 筛选目标资源的定价,示例为华东区域D2s v3 VM的定价 rate_card = commerce_client.rate_card.list( filter="OfferDurableId eq 'MS-AZR-0003p' and Currency eq 'CNY' and Region eq 'chinaeast' and ProductName eq 'Virtual Machines Dv3 Series'" ) # 解析并输出定价 for meter in rate_card.meters: if meter.meter_name == "D2s v3": print(f"VM规格 {meter.meter_name} 的单价: {meter.meter_rates['0']} 元/小时")
关键注意事项
- 实际成本查询的时间范围可灵活调整,比如
WeekToDate或Custom(需额外指定timePeriod的起止日期) - 资源ID可直接从Azure门户的资源详情页复制获取
- 定价查询时,需确保区域、产品名称等筛选条件与目标资源完全匹配,否则会返回空结果
内容的提问来源于stack exchange,提问作者Amoghavarsh P
相关产品推荐
相关产品推荐

