我使用以下代码来获取资源组列表。但我需要检查每个资源组的成本详细信息。哪个模块将支持此功能以及实现此功能所需的权限是什么?
from azure.identity import ClientSecretCredential
import requests
subscription_id = 'MYSUBID'
client_id = 'MYCLIENTID'
client_secret = 'MYSECRETVALUE'
tenant_id = 'MYTENANTID'
# Create a ClientSecretCredential object
credential = ClientSecretCredential(tenant_id=tenant_id, client_id=client_id, client_secret=client_secret)
url = f"https://management.azure.com/subscriptions/{subscription_id}/resourcegroups?api-version=2021-04-01"
# Get an access token for the Azure Management API
access_token = credential.get_token("https://management.azure.com/.default")
# Make the GET request to retrieve a list of resource groups
headers = {
"Authorization": f"Bearer {access_token}"
}
response = requests.get(url, headers=headers)
if response.status_code == 200:
resource_groups = response.json()
for rg in resource_groups['value']:
print(rg['name'])
else:
print(response.status_code, "-" ,response.text)
最佳答案
要使用 python 以 美元
形式从 Azure 获取特定资源组的成本详细信息,请使用以下代码:
import os
from datetime import *
from azure.mgmt.costmanagement import CostManagementClient
from azure.mgmt.costmanagement.models import QueryDefinition, QueryDataset, QueryTimePeriod, QueryAggregation, QueryGrouping
from azure.identity import ClientSecretCredential
time_period_in_past=30
ResourceGroupName="ruk"
SubscriptionID="SubscriptionID"
maxDateInPast = ((datetime.now(timezone.utc))-timedelta(days=time_period_in_past))
credentials = ClientSecretCredential(
tenant_id="TenantID",
client_id="ClientID",
client_secret="ClientSecret"
)
time_period=QueryTimePeriod(from_property=maxDateInPast, to=datetime.now(timezone.utc))
client = CostManagementClient(credentials)
query_aggregation = dict()
query_aggregation["totalCost"] = QueryAggregation(name="Cost", function="Sum")
query_aggregation["totalCostUSD"] = QueryAggregation(name="CostUSD", function="Sum")
query_grouping = [QueryGrouping(type="Dimension", name="ResourceId"), QueryGrouping(type="Dimension", name="ChargeType"),
QueryGrouping(type="Dimension", name="PublisherType")]
querydataset = QueryDataset(granularity=None, configuration=None, aggregation=query_aggregation, grouping=query_grouping)
query = QueryDefinition(type="ActualCost", timeframe="Custom", time_period=time_period, dataset=querydataset)
scope = f'/subscriptions/{SubscriptionID}/resourceGroups/{ResourceGroupName}'
result = client.query.usage(scope = scope, parameters=query)
cost_sum = 0
for row in result.as_dict()['rows']:
cost_sum += row[1]
print(f"Cost for [{time_period_in_past}] days for resource group [{ResourceGroupName}] is [{cost_sum}] USD")
要使用 INR
中的 python 从 Azure 获取特定资源组的成本详细信息,请使用以下代码:
import os
from datetime import datetime, timedelta, timezone
from azure.mgmt.costmanagement import CostManagementClient
from azure.mgmt.costmanagement.models import QueryDefinition, QueryDataset, QueryTimePeriod, QueryAggregation, QueryGrouping
from azure.identity import ClientSecretCredential
time_period_in_past = 30
resource_group_name = "ruk"
exchange_rate_usd_to_inr = 83.16 # Replace with the actual exchange rate
maxDateInPast = ((datetime.now(timezone.utc)) - timedelta(days=time_period_in_past))
credentials = ClientSecretCredential(
tenant_id='TenantID',
client_id='ClientID',
client_secret='ClientSecret'
)
time_period = QueryTimePeriod(from_property=maxDateInPast, to=datetime.now(timezone.utc))
client = CostManagementClient(credentials)
query_aggregation = {
"totalCost": QueryAggregation(name="Cost", function="Sum"),
"totalCostUSD": QueryAggregation(name="CostUSD", function="Sum")
}
query_grouping = [QueryGrouping(type="Dimension", name="ResourceId"), QueryGrouping(type="Dimension", name="ChargeType"),
QueryGrouping(type="Dimension", name="PublisherType")]
querydataset = QueryDataset(granularity=None, configuration=None, aggregation=query_aggregation, grouping=query_grouping)
query = QueryDefinition(type="ActualCost", timeframe="Custom", time_period=time_period, dataset=querydataset)
scope = f'/subscriptions/SubscriptionID/resourceGroups/{resource_group_name}'
result = client.query.usage(scope=scope, parameters=query)
cost_sum = 0
for row in result.as_dict()['rows']:
cost_sum += row[1]
# Convert the cost from USD to INR
cost_sum_in_inr = cost_sum * exchange_rate_usd_to_inr
print(f"Cost for [{time_period_in_past}] days for resource group [{resource_group_name}] is [{cost_sum_in_inr}] INR")
Note that: Assign
Reader
role to the service principal to fetch the data.
关于python - 如何使用 python 从 azure 获取特定资源组的成本详细信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77195224/