How to get the actual cost for a resource group in python?

211 Views Asked by At

I am working on connecting with the azure portal and fetch informations like resource groups, tags and cost data. In that I can able to fetch resource groups and tags, but I am stuck on getting the cost information from the portal. Particularly I need the actual cost from the azure portal as shown in the image below.

actual amount

python code below:

import requests

url = "https://management.azure.com/subscriptions/000000-0000-0000-0000-00000000000000/providers/Microsoft.Consumption/usageDetails?api-version=2023-05-01&metric=actualcost"

# Make the GET request to the Azure Consumption API
headers = {
     "Authorization": f"Bearer {access_token.token}"
}

response = requests.get(url, headers=headers)

if response.status_code == 200:
    cost_details = response.json()
    print(cost_details)

Sample response I am getting is below:

"value": [
        {
            "kind": "legacy",
            "id": "/subscriptions/blurred/providers/Microsoft.Billing/billingPeriods/blurred/providers/Microsoft.Consumption/usageDetails/blurred",
            "name": "blurred",
            "type": "Microsoft.Consumption/usageDetails",
            "tags": {
                "DEPLOYMENT_ID": "blurred",
                "ENVIRONMENT": "blurred",
                "OWNER": "blurred",
                "ROLE_PURPOSE": "storageAccounts"
            },
            "properties": {
                "billingAccountId": "00000",
                "billingAccountName": "TEST NAME",
                "billingPeriodStartDate": "2023-11-01T00:00:00.0000000Z",
                "billingPeriodEndDate": "2023-11-30T00:00:00.0000000Z",
                "billingProfileId": "00000",
                "billingProfileName": "TEST NAME",
                "accountOwnerId": "blurred",
                "accountName": "blurred",
                "subscriptionId": "00000-00000-000-0000",
                "subscriptionName": "blurred",
                "date": "2023-11-05T00:00:00.0000000Z",
                "product": "blurred",
                "partNumber": "blurred",
                "meterId": "blurred",
                "quantity": 0.000288,
                "effectivePrice": 0.013,
                "cost": 0.000003744,
                "unitPrice": 0.013,
                "billingCurrency": "USD",
                "resourceLocation": "EastUS",
                "consumedService": "Microsoft.Storage",
                "resourceId": "/subscriptions/ blurred/resourceGroups/lineage-ingestion-rg/providers/Microsoft.Storage/storageAccounts/blurred",
                "resourceName": "blurred",
                "invoiceSection": "blurred",
                "costCenter": "blurred",
                "resourceGroup": "blurred",
                "offerId": "blurred",
                "isAzureCreditEligible": true,
                "publisherName": "Microsoft",
                "publisherType": "Azure",
                "planName": "Hot",
                "chargeType": "Usage",
                "frequency": "UsageBased",
                "payGPrice": 0.0191,
                "pricingModel": "OnDemand",
                "meterDetails": null
            }}

I am expecting that 16.20$ to print for my resource group.

1

There are 1 best solutions below

7
On

To fetch the actual cost for a resource group in python, make use of below script:

import msal
import requests

tenant_id = "TenantID"
client_id = "ClientID"
client_secret = "ClientSecret"
resource = "https://management.azure.com/"
authority_url = f"https://login.microsoftonline.com/{tenant_id}"
app = msal.ConfidentialClientApplication(client_id, authority=authority_url, client_credential=client_secret)

result = None
try:
    result = app.acquire_token_for_client(scopes=[resource + "/.default"])
except Exception as e:
    print(f"Authentication error: {e}")

if "access_token" in result:
    access_token = result["access_token"]
    print(f"Access Token: {access_token}")
else:
    print("Failed to acquire access token.")

subscription_id = "SubID"
resource_group_name = "ruk"
usage_start = "2023-11-01"
usage_end = "2023-11-30"
url = f"https://management.azure.com/subscriptions/{subscription_id}/providers/Microsoft.Consumption/usageDetails?api-version=2023-05-01&metric=actualcost&$filter=properties/usageStart eq '{usage_start}' and properties/usageEnd eq '{usage_end}'"
headers = {
     "Authorization": f"Bearer {access_token}"
}
response = requests.get(url, headers=headers)

if response.status_code == 200:
    cost_details = response.json()["value"]
    total_cost = sum(detail["properties"]["cost"] for detail in cost_details if detail["properties"]["resourceGroup"] == resource_group_name)
    print(f"Total actual cost for resource group {resource_group_name} from {usage_start} to {usage_end}: ${total_cost:.2f}")
else:
    print(f"Failed to get usage details: {response.text}")

In the Azure Portal, the cost of the resource group is like below:

enter image description here

The cost of the Resource Group displayed successfully:

enter image description here