Reputation: 149
Is there any way we can get the cost of individual resources using Azure Python SDK[https://learn.microsoft.com/en-us/python/api/overview/azure/?view=azure-python]?
I have used RateCard[https://learn.microsoft.com/en-us/python/api/azure-mgmt-commerce/azure.mgmt.commerce.operations.ratecardoperations?view=azure-python] and Usage[https://learn.microsoft.com/en-us/python/api/azure-mgmt-commerce/azure.mgmt.commerce.operations.usageaggregatesoperations?view=azure-python] API's to calculate the cost. But looking for a better solution.
query = "OfferDurableId eq '" + offer_id + \
"' and Currency eq 'USD' and Locale eq 'en-US' and RegionInfo eq 'US'"
ratecard = usage_client.rate_card.get(filter=query)
usage = usage_client.usage_aggregates.list(reported_start_time=start,
reported_end_time=end,
show_details=True,
aggregation_granularity="Daily"):
Get cost of individual resource for last 30 days using Azure SDK.
Upvotes: 3
Views: 2338
Reputation: 483
Code I used for getting cost of a resource group
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
resource_group_name="test-rg-name"
maxDateInPast = ((datetime.now(timezone.utc))-timedelta(days=time_period_in_past))
credentials = ClientSecretCredential(
tenant_id=os.environ["TENANT_ID"],
client_id=os.environ["CLIENT_ID"],
client_secret=os.environ["CLIENT_SECRET"]
)
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") # in result, will be column with index = 0
query_aggregation["totalCostUSD"] = QueryAggregation(name="CostUSD", function="Sum") # in result, will be column with index = 1
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/{os.environ["Azure_Subscription_ID"]}/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]
print(f"Cost for [{time_period_in_past}] days for resource group [{resource_group_name}] is [{cost_sum}] USD")
Upvotes: 5