如何获取Azure存储账户容量详情?API返回空JSON的解决及替代方案
调用Azure Monitoring API获取存储账户的UsedCapacity指标时,返回状态码200但结果为空JSON:{"value":[]},使用的Python代码如下:
import requests from datetime import datetime, timedelta from azure.identity import ClientSecretCredential #start_time = (datetime.utcnow() - timedelta(hours=1)).replace(microsecond=0).isoformat() + "Z" #end_time = datetime.utcnow().replace(microsecond=0).isoformat() + "Z" start_time = (datetime.utcnow() - timedelta(hours=23)).replace(microsecond=0).isoformat() + "Z" end_time = (datetime.utcnow() - timedelta(hours=22)).replace(microsecond=0).isoformat() + "Z" #print("Start_Time:",start_time) #print("End_Time:",end_time) subscription_id = "" resource_group = "" storage_account_name = "" metric_name = "UsedCapacity" time_range = f"{start_time}/{end_time}" api_version = "2021-05-01" tenant_id = dbutils.secrets.get(scope="scope",key="tenant-id") client_id = dbutils.secrets.get(scope="scope", key="clientid") client_secret = dbutils.secrets.get(scope="sn_scope", key="secret") token_endpoint = f"https://login.microsoftonline.com/{tenant_id}/oauth2/token" data = { "grant_type": "client_credentials", "client_id": f"{client_id}", "client_secret": f"{client_secret}", "resource": "https://management.azure.com/" } response = requests.post(token_endpoint, data=data) if response.status_code == 200: post_response = response.text print("POST_Response:",post_response) access_token = response.json()["access_token"] #print("Access Token:", access_token) else: print("Error generating access token:", response.status_code) headers = { "Authorization": f"Bearer {access_token}", "Content-Type" : "application/json" } api_url = f"https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.Storage/storageAccounts/{storage_account_name}/providers/microsoft.insights/metrics?timespan={time_range}&metricnames={metric_name}&api-version={api_version}" print("API:",api_url) response = requests.get(api_url,headers=headers) if response.status_code == 200: data = response.text print("GET_Response:",data) else: print("Error retrieving metrics data:", response.status_code) print("Error Message:",response.text)
补充聚合与时间粒度参数:Azure Metrics API必须指定聚合方式才能返回有效数据,原请求URL缺少
aggregation参数。修改后的API URL示例:https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.Storage/storageAccounts/{storage_account_name}/providers/microsoft.insights/metrics?timespan={time_range}&metricnames={metric_name}&aggregation=Average&interval=PT1H&api-version={api_version}针对
UsedCapacity,常用聚合方式为Average(时段内平均容量)或Total(时段内总容量),interval=PT1H对应指标默认的1小时聚合粒度。确认时间范围有效性:如果指定的
timespan内存储账户无数据写入(如刚创建的空存储账户),会返回空数组。可尝试扩大时间范围,比如查询过去24小时的数据。验证服务主体权限:确保获取token的服务主体已被分配Monitoring Reader或Reader角色(作用范围为目标存储账户、资源组或订阅),RBAC角色分配可能存在15-30分钟的生效延迟。
检查存储账户类型:确认目标存储账户为支持
UsedCapacity指标的类型(如General Purpose v2、Blob Storage等),部分特殊存储类型(如Premium File Storage)可能不提供该指标。
Azure Resource Graph API:通过Kusto查询语言获取存储账户使用量,支持批量查询,示例查询语句:
Resources | where type == 'microsoft.storage/storageaccounts' | where name == '{storage_account_name}' | project name, usedCapacity = toreal(properties.usage.usedCapacity), location调用时使用Azure Resource Graph的API端点,需确保服务主体拥有
Reader权限。存储账户详情API:若仅需获取存储账户的配额配置(非实时使用量),可调用以下接口:
GET https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}?api-version=2023-01-01
内容的提问来源于stack exchange,提问作者Saksham Agarwal

