ZUREPYTHON SDK以获取个人资源成本

问题描述 投票:0回答:2
我想使用Python脚本来获得个人资源成本,以获取VM,数据库等价格的任何方法

python azure azure-python-sdk
2个回答
0
投票

https://learn.microsoft.com/en-us/python/api/overview/azure/cost-management-management-billing?view = azure-python

Microsoft并不容易获得单个资源的成本。 您可以潜在地使用计费API,但需要特殊的许可。 我这样做的方式是:


0
投票

确定资源组的成本

ResourceId

  • 代码我看起来像这样:

    def get_resource_group_cost(credential, subscription_id: str, resource_group_name: str, days: int = 7) -> Dict: try: cost_client = CostManagementClient(credential) end_time = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0) start_time = end_time - timedelta(days=days) scope = f"/subscriptions/{subscription_id}/resourceGroups/{resource_group_name}" parameters = { "type": "ActualCost", "timeframe": "Custom", "timePeriod": { "from": start_time.isoformat(), "to": end_time.isoformat() }, "dataset": { "granularity": "None", "aggregation": { "totalCost": { "name": "Cost", "function": "Sum" } }, "grouping": [ { "type": "Dimension", "name": "ResourceId" } ] } } cost_data = cost_client.query.usage(scope=scope, parameters=parameters) # Process the results into a dictionary of resource costs resource_costs = {} if cost_data.rows: for row in cost_data.rows: resource_id = row[1] # ResourceId is in the second column cost = row[0] # Cost is in the first column currency = row[2] # Currency is in the third column resource_costs[resource_id] = { 'total_cost': cost, 'avg_daily_cost': cost / days, 'currency': currency } return resource_costs except Exception as e: print(f"Error getting cost data for resource group {resource_group_name}: {str(e)}") return None
© www.soinside.com 2019 - 2025. All rights reserved.