英文:
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和客户端密钥。
在订阅级别下为**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
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"}
英文:
> 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.
Assigned contributor
role to the appvenkat
under subscription level.
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() + "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)
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&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"}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论