You need the azure-mgmt-costmanagement
library and azureml-core
SDK.
pip install azure-mgmt-costmanagement azureml-core
You'll need to authenticate using your Azure credentials and initialize the required clients. This example uses a service principal for authentication.
from azure.identity import ClientSecretCredential
from azure.mgmt.costmanagement import CostManagementClient
from azureml.core import Workspace
import os
# Set your Azure credentials
TENANT_ID = os.getenv("AZURE_TENANT_ID")
CLIENT_ID = os.getenv("AZURE_CLIENT_ID")
CLIENT_SECRET = os.getenv("AZURE_CLIENT_SECRET")
SUBSCRIPTION_ID = os.getenv("AZURE_SUBSCRIPTION_ID")
RESOURCE_GROUP = os.getenv("AZURE_RESOURCE_GROUP")
WORKSPACE_NAME = os.getenv("AZURE_WORKSPACE_NAME")
# Authenticate using service principal
credential = ClientSecretCredential(tenant_id=TENANT_ID, client_id=CLIENT_ID, client_secret=CLIENT_SECRET)
# Initialize Cost Management client
cost_management_client = CostManagementClient(credential, subscription_id=SUBSCRIPTION_ID)
# Initialize AzureML workspace
workspace = Workspace(subscription_id=SUBSCRIPTION_ID, resource_group=RESOURCE_GROUP, workspace_name=WORKSPACE_NAME)
Now, you can query the cost data. You can use the QueryClient
from the azure-mgmt-costmanagement
library to get cost details.
from azure.mgmt.costmanagement.models import QueryDefinition, QueryTimePeriod
from datetime import datetime, timedelta
# Define the query time period
end_date = datetime.today().date()
start_date = end_date - timedelta(days=30)
# Define the query
query_definition = QueryDefinition(
time_period=QueryTimePeriod(
from_property=start_date,
to=end_date
),
dataset={
"granularity": "None",
"aggregation": {
"totalCost": {
"name": "PreTaxCost",
"function": "Sum"
}
},
"grouping": [
{
"type": "Dimension",
"name": "ResourceGroupName"
},
{
"type": "Dimension",
"name": "ResourceId"
}
]
}
)
# Execute the query
cost_query = cost_management_client.query.usage(workspace.id, query_definition)
Finally, process the results and convert them to JSON .
import json
# Process the results
cost_details = []
for row in cost_query.rows:
cost_details.append({
"ResourceGroupName": row[0],
"ResourceId": row[1],
"TotalCost": row[2]
})
# Convert to JSON
cost_details_json = json.dumps(cost_details, indent=4)
print(cost_details_json)