如何从Azure存储帐户中获取大小详情?

huangapple go评论67阅读模式
英文:

How to fetch size details from storage account in Azure?

问题

我正在尝试使用Azure监视API获取大小详细信息或已使用容量,但它返回了一个空的JSON。

从这个API获取的响应状态码是200,但JSON文件只返回了{ "value" :[] }。

是否有其他API可以获取存储账户的大小?

英文:

I am trying to fetch the size details or Used Capacity using Azure Monitoring API but it's returning me blank 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="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)

Response I am getting from this API is 200 but the json file only returns { "value" :[] }
Is there any other API to fetch the size of storage account?

答案1

得分: 0

Sure, here's the translated content:

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

我在我的环境中尝试并获得了以下结果:

首先,我创建了一个应用程序来获取客户端ID、租户ID和客户端密钥。

如何从Azure存储帐户中获取大小详情?

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

如何从Azure存储帐户中获取大小详情?

我尝试使用几乎相同的代码,稍作修改,然后可以使用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
  access_token = response.json()["access_token"]
else:
  print("生成访问令牌时出错:", 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'}
已使用的存储帐户容量:
{"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"}

如何从Azure存储帐户中获取大小详情?

英文:

> How to fetch size details from storage account in Azure using Python.

I tried in my environment and got the below results:

Initially, I created App to get the Client-id,tenant-id and Client-secret.

如何从Azure存储帐户中获取大小详情?

Assigned contributor role to the appvenkat under subscription level.

如何从Azure存储帐户中获取大小详情?

I tried with the same code with minimal modification and I can able to fetch the used capacity of the storage account using Python.

Code:

    import requests
    from datetime import datetime, timedelta
    
    start_time = (datetime.utcnow() - timedelta(hours=23)).replace(microsecond=0).isoformat() + &quot;Z&quot;
    end_time = (datetime.utcnow() - timedelta(hours=22)).replace(microsecond=0).isoformat() + &quot;Z&quot;
    
    
    subscription_id = &quot;your subscription id&quot;
    resource_group = &quot;your resourcegroup name&quot;
    storage_account_name = &quot;your storage account name&quot;
    metric_name = &quot;UsedCapacity&quot; 
    time_range = f&quot;{start_time}/{end_time}&quot;  
    api_version = &quot;2021-05-01&quot;
    
    tenant_id = &quot;your tenant id&quot;
    client_id = &quot;your client id&quot;
    client_secret = &quot;your client secret
    
    token_endpoint = f&quot;https://login.microsoftonline.com/{tenant_id}/oauth2/token&quot; 
    
    data = {
      &quot;grant_type&quot;: &quot;client_credentials&quot;,
      &quot;client_id&quot;: f&quot;{client_id}&quot;,  
      &quot;client_secret&quot;: f&quot;{client_secret}&quot;,  
      &quot;resource&quot;: &quot;https://management.azure.com/&quot;
    }
    
    response = requests.post(token_endpoint, data=data)
    
    if response.status_code == 200:
      post_response = response.text
      #print(&quot;POST_Response:&quot;,post_response)
      access_token = response.json()[&quot;access_token&quot;]
    #   print(&quot;Access Token:&quot;, access_token)
    else:
      print(&quot;Error generating access token:&quot;, response.status_code)
    
    
    headers = {
      &quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;,
      &quot;Content-Type&quot; : &quot;application/json&quot;
    }
    
    
    api_url = f&quot;https://management.azure.com/subscriptions/{subscription_id}/resourceGroups/{resource_group}/providers/Microsoft.Storage/storageAccounts/{storage_account_name}/providers/microsoft.insights/metrics?timespan={time_range}&amp;metricnames={metric_name}&amp;api-version={api_version}&quot;
    
    
    print(&quot;API:&quot;,api_url)
    
    response = requests.get(api_url,headers=headers)
    print(response)
    print (response.headers)
    print(response.text)

Output:

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&amp;metricnames=UsedCapacity&amp;api-version=2021-05-01
&lt;Response [200]&gt;
{&#39;Cache-Control&#39;: &#39;no-cache&#39;, &#39;Pragma&#39;: &#39;no-cache&#39;, &#39;Transfer-Encoding&#39;: &#39;chunked&#39;, &#39;Content-Type&#39;: &#39;application/json; charset=utf-8&#39;, &#39;Content-Encoding&#39;: &#39;gzip&#39;, &#39;Expires&#39;: &#39;-1&#39;, &#39;Vary&#39;: &#39;Accept-Encoding&#39;, &#39;x-ms-correlation-request-id&#39;: &#39;ad9c6052-xxx2&#39;, &#39;x-ms-ratelimit-remaining-subscription-reads&#39;: &#39;11974&#39;, &#39;Request-Context&#39;: &#39;appId=cid-v1:b0xxxx&#39;, &#39;x-ms-request-id&#39;: &#39;{ad9c6xxxxx2}&#39;, &#39;Strict-Transport-Security&#39;: &#39;max-age=31536000; includeSubDomains&#39;, &#39;Access-Control-Allow-Origin&#39;: &#39;*&#39;, &#39;x-ms-routing-request-id&#39;: &#39;xxxxZ:ad9c605xxxxx2&#39;, &#39;X-Content-Type-Options&#39;: &#39;nosniff&#39;, &#39;Date&#39;: &#39;Fri, 16 Jun 2023 07:11:22 GMT&#39;}
Used capacity of Storage account:
{&quot;cost&quot;:59,&quot;timespan&quot;:&quot;2023-06-15T08:11:21Z/2023-06-15T09:11:21Z&quot;,&quot;interval&quot;:&quot;PT1H&quot;,&quot;value&quot;:[{&quot;id&quot;:&quot;/subscriptions/xxxxx/resourceGroups/xxx/providers/Microsoft.Storage/storageAccounts/venkat123/providers/Microsoft.Insights/metrics/UsedCapacity&quot;,&quot;type&quot;:&quot;Microsoft.Insights/metrics&quot;,&quot;name&quot;:{&quot;value&quot;:&quot;UsedCapacity&quot;,&quot;localizedValue&quot;:&quot;Used capacity&quot;},&quot;displayDescription&quot;:&quot;The amount of storage used by the storage account. For standard storage accounts, it&#39;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.&quot;,&quot;unit&quot;:&quot;Bytes&quot;,&quot;timeseries&quot;:[{&quot;metadatavalues&quot;:[],&quot;data&quot;:[{&quot;timeStamp&quot;:&quot;2023-06-15T08:11:00Z&quot;,&quot;average&quot;:2160775175}]}],&quot;errorCode&quot;:&quot;Success&quot;}],&quot;namespace&quot;:&quot;Microsoft.Storage/storageAccounts&quot;,&quot;resourceregion&quot;:&quot;eastus&quot;}

如何从Azure存储帐户中获取大小详情?

huangapple
  • 本文由 发表于 2023年6月15日 14:03:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76479533.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定