Get detailed costs in scope of Azureml workspace, using python sdk

Aziz 0 Reputation points
2024-08-05T10:46:33.44+00:00

Hi, how to get detailed costs in scope of Azureml workspace, using python sdk? I need some kind of json repr of the costs by compute cluster names, online endpoints etc..

Azure Machine Learning
Azure Machine Learning
An Azure machine learning service for building and deploying models.
3,187 questions
Azure Cost Management
Azure Cost Management
A Microsoft offering that enables tracking of cloud usage and expenditures for Azure and other cloud providers.
3,141 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Amira Bedhiafi 29,946 Reputation points
    2024-08-05T16:50:35.01+00:00

    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)
    
    

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.