如何从Azure中的存储帐户获取大小详细信息?

szqfcxe2  于 2023-06-24  发布在  其他
关注(0)|答案(1)|浏览(150)

我试图使用Azure Monitoring API获取大小细节或已用容量,但它返回了空白的json。

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="sn_scope",key="tenant-id")
client_id = dbutils.secrets.get(scope="sn_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)

我从这个API得到的响应是200,但json文件只返回{“value”:[] }
是否有其他API可以获取存储账户的大小?

6ss1mwsb

6ss1mwsb1#

如何使用Python从Azure中的存储帐户获取大小详细信息。

我在我的环境中尝试了一下,得到了以下结果:

最初,我创建了应用程序来获取Client-id,tenant-id和Client-secret。

为订阅级下的**appvenkat分配了contributor**角色。

我试着用同样的代码进行最小的修改,我可以使用Python获取存储帐户的已使用容量。

代码:

import requests
    from datetime import datetime, timedelta
    
    start_time = (datetime.utcnow() - timedelta(hours=23)).replace(microsecond=0).isoformat() + "Z"
    end_time = (datetime.utcnow() - timedelta(hours=22)).replace(microsecond=0).isoformat() + "Z"
    
    
    subscription_id = "your subscription id"
    resource_group = "your resourcegroup name"
    storage_account_name = "your storage account name"
    metric_name = "UsedCapacity" 
    time_range = f"{start_time}/{end_time}"  
    api_version = "2021-05-01"
    
    tenant_id = "your tenant id"
    client_id = "your client id"
    client_secret = "your client 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)
    print(response)
    print (response.headers)
    print(response.text)

输出:

API: https://management.azure.com/subscriptions/xxxxx/resourceGroups/xxx/providers/Microsoft.Storage/storageAccounts/venkat123/providers/microsoft.insights/metrics?timespan=2023-06-15T08:11:21Z/2023-06-15T09:11:21Z&metricnames=UsedCapacity&api-version=2021-05-01
<Response [200]>
{'Cache-Control': 'no-cache', 'Pragma': 'no-cache', 'Transfer-Encoding': 'chunked', 'Content-Type': 'application/json; charset=utf-8', 'Content-Encoding': 'gzip', 'Expires': '-1', 'Vary': 'Accept-Encoding', 'x-ms-correlation-request-id': 'ad9c6052-xxx2', 'x-ms-ratelimit-remaining-subscription-reads': '11974', 'Request-Context': 'appId=cid-v1:b0xxxx', 'x-ms-request-id': '{ad9c6xxxxx2}', 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains', 'Access-Control-Allow-Origin': '*', 'x-ms-routing-request-id': 'xxxxZ:ad9c605xxxxx2', 'X-Content-Type-Options': 'nosniff', 'Date': 'Fri, 16 Jun 2023 07:11:22 GMT'}
Used capacity of Storage account:
{"cost":59,"timespan":"2023-06-15T08:11:21Z/2023-06-15T09:11:21Z","interval":"PT1H","value":[{"id":"/subscriptions/xxxxx/resourceGroups/xxx/providers/Microsoft.Storage/storageAccounts/venkat123/providers/Microsoft.Insights/metrics/UsedCapacity","type":"Microsoft.Insights/metrics","name":{"value":"UsedCapacity","localizedValue":"Used capacity"},"displayDescription":"The amount of storage used by the storage account. For standard storage accounts, it's the sum of capacity used by blob, table, file, and queue. For premium storage accounts and Blob storage accounts, it is the same as BlobCapacity or FileCapacity.","unit":"Bytes","timeseries":[{"metadatavalues":[],"data":[{"timeStamp":"2023-06-15T08:11:00Z","average":2160775175}]}],"errorCode":"Success"}],"namespace":"Microsoft.Storage/storageAccounts","resourceregion":"eastus"}

相关问题