or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

alerts.mdbenefits.mddimensions.mdexports.mdindex.mdprice-sheet.mdquery-forecast.mdreports.mdscheduled-actions.mdviews.md
tile.json

tessl/pypi-azure-mgmt-costmanagement

Microsoft Azure Cost Management Client Library for Python providing comprehensive access to cost analysis, billing data, budgets, alerts, exports, and recommendations.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/azure-mgmt-costmanagement@4.0.x

To install, run

npx @tessl/cli install tessl/pypi-azure-mgmt-costmanagement@4.0.0

index.mddocs/

Azure Cost Management

Microsoft Azure Cost Management Client Library for Python provides comprehensive access to Azure Cost Management services. This library enables developers to programmatically access cost analysis, billing data, budgets, alerts, exports, recommendations, and detailed cost reporting capabilities. The library follows Azure SDK conventions with both synchronous and asynchronous client implementations, supporting various authentication methods including Azure Active Directory.

Package Information

  • Package Name: azure-mgmt-costmanagement
  • Language: Python
  • Version: 4.0.1
  • API Version: 2022-10-01
  • Installation: pip install azure-mgmt-costmanagement

Core Imports

from azure.mgmt.costmanagement import CostManagementClient

For async operations:

from azure.mgmt.costmanagement.aio import CostManagementClient

Authentication (requires azure-identity):

from azure.identity import DefaultAzureCredential
from azure.mgmt.costmanagement import CostManagementClient

credential = DefaultAzureCredential()

Basic Usage

from azure.identity import DefaultAzureCredential
from azure.mgmt.costmanagement import CostManagementClient

# Initialize client with authentication
credential = DefaultAzureCredential()
client = CostManagementClient(credential)

# Define scope (subscription example)
scope = "/subscriptions/{subscription-id}"

# Query cost data
from azure.mgmt.costmanagement.models import QueryDefinition, QueryDataset, QueryAggregation, QueryTimePeriod, TimeframeType, GranularityType

query_def = QueryDefinition(
    type="Usage",
    timeframe=TimeframeType.MONTH_TO_DATE,
    dataset=QueryDataset(
        granularity=GranularityType.DAILY,
        aggregation={
            "totalCost": QueryAggregation(name="Cost", function="Sum")
        }
    )
)

result = client.query.usage(scope, query_def)
for row in result.rows:
    print(f"Date: {row[0]}, Cost: {row[1]}")

# List cost alerts
alerts = client.alerts.list(scope)
for alert in alerts.value:
    print(f"Alert: {alert.properties.alert_id}, Status: {alert.properties.status}")

# Get cost dimensions for filtering
dimensions = client.dimensions.list(scope)
for dimension in dimensions.value:
    print(f"Dimension: {dimension.name}, Category: {dimension.category}")

Architecture

The Azure Cost Management SDK follows the standard Azure SDK architecture:

  • CostManagementClient: Main client class providing access to all operations
  • Operation Groups: Logical groupings of related operations (query, alerts, exports, etc.)
  • Models: Data classes representing request/response objects and Azure resources
  • Authentication: Integration with Azure Identity for various authentication methods
  • Async Support: Full async/await support with separate async client

The client supports various Azure scopes including subscriptions, resource groups, billing accounts, management groups, and external cloud providers.

Capabilities

Query and Forecast Operations

Core functionality for querying cost data and generating forecasts. Includes cost analysis, usage queries, and predictive cost modeling across different time periods and granularities.

def usage(scope: str, parameters: QueryDefinition) -> QueryResult: ...
def usage_by_external_cloud_provider_type(
    external_cloud_provider_type: str,
    external_cloud_provider_id: str, 
    parameters: QueryDefinition
) -> QueryResult: ...
def usage(scope: str, parameters: ForecastDefinition) -> ForecastResult: ...
def external_cloud_provider_usage(
    external_cloud_provider_type: str,
    external_cloud_provider_id: str,
    parameters: ForecastDefinition
) -> ForecastResult: ...

Query and Forecast

Cost Management Views

Manage and organize cost analysis views for consistent reporting and sharing across teams. Create, update, and delete custom views with specific filters and configurations.

def list() -> ViewListResult: ...
def get(view_name: str) -> View: ...
def create_or_update(view_name: str, parameters: View) -> View: ...
def delete(view_name: str) -> None: ...
def list_by_scope(scope: str) -> ViewListResult: ...

Views Management

Alerts Management

Monitor and manage cost alerts and budget notifications. Set up automated alerts for cost thresholds, budget overruns, and anomaly detection.

def list(scope: str) -> AlertsResult: ...
def get(scope: str, alert_id: str) -> Alert: ...
def dismiss(scope: str, alert_id: str, parameters: DismissAlertPayload) -> Alert: ...
def list_external(
    external_cloud_provider_type: str,
    external_cloud_provider_id: str
) -> AlertsResult: ...

Alerts

Data Export Operations

Schedule and manage automated data exports for cost and usage data. Configure recurring exports to storage accounts with custom formats and delivery schedules.

def list(scope: str, expand: str = None) -> ExportListResult: ...
def get(scope: str, export_name: str, expand: str = None) -> Export: ...
def create_or_update(scope: str, export_name: str, parameters: Export) -> Export: ...
def execute(scope: str, export_name: str) -> ExportRun: ...
def get_execution_history(scope: str, export_name: str) -> ExportExecutionListResult: ...

Data Exports

Scheduled Actions

Automate cost management tasks with scheduled actions including email notifications, insights alerts, and custom workflows triggered by cost events.

def list(filter: str = None) -> ScheduledActionListResult: ...
def create_or_update(
    name: str,
    scheduled_action: ScheduledAction,
    if_match: str = None
) -> ScheduledAction: ...
def run(name: str) -> None: ...
def check_name_availability(body: CheckNameAvailabilityRequest) -> CheckNameAvailabilityResponse: ...

Scheduled Actions

Benefit Recommendations and Utilization

Analyze and optimize Azure Reserved Instances, Savings Plans, and other cost-saving benefits. Get recommendations for optimal purchasing decisions and track utilization.

def list(
    scope: str,
    filter: str = None,
    orderby: str = None,
    expand: str = None
) -> BenefitRecommendationsListResult: ...
def list_by_billing_account_id(
    billing_account_id: str,
    filter: str = None,
    grain_parameter: str = None
) -> BenefitUtilizationSummariesListResult: ...
def list_by_savings_plan_order(
    savings_plan_order_id: str,
    filter: str = None,
    grain_parameter: str = None
) -> BenefitUtilizationSummariesListResult: ...

Benefits and Recommendations

Report Generation

Generate detailed cost reports including cost details reports, reservation details, and comprehensive billing reports with custom time periods and formats.

def begin_create_operation(
    scope: str,
    parameters: GenerateCostDetailsReportRequestDefinition
) -> LROPoller[CostDetailsOperationResults]: ...
def begin_create_operation(
    scope: str,
    parameters: GenerateDetailedCostReportDefinition
) -> LROPoller[GenerateDetailedCostReportOperationResult]: ...

Report Generation

Dimensions and Metadata

Query available cost dimensions for building filters and groupings. Access metadata about available cost categories, resource types, and billing dimensions.

def list(
    scope: str,
    filter: str = None,
    expand: str = None,
    skiptoken: str = None,
    top: int = None
) -> DimensionsListResult: ...

Dimensions

Price Sheet Operations

Download pricing information and rate cards for Azure services. Access current and historical pricing data for billing accounts with Microsoft Partner Agreement or Microsoft Customer Agreement.

def begin_download(
    billing_account_name: str,
    billing_profile_name: str,
    invoice_name: str
) -> LROPoller[DownloadURL]: ...
def begin_download_by_billing_profile(
    billing_account_name: str,
    billing_profile_name: str
) -> LROPoller[DownloadURL]: ...

Price Sheet

API Operations Discovery

List and discover all available Cost Management REST API operations for programmatic exploration of service capabilities.

def list() -> Iterable[CostManagementOperation]:
    """
    Lists all available cost management REST API operations.
    
    Returns:
        Iterable[CostManagementOperation]: Iterator of available operations with metadata
    """

Core Data Types

class CostManagementClient:
    def __init__(
        self,
        credential: TokenCredential,
        base_url: str = "https://management.azure.com",
        **kwargs
    ): ...
    
    def close(self) -> None: ...
    def __enter__(self) -> "CostManagementClient": ...
    def __exit__(self, *exc_details) -> None: ...

class QueryDefinition:
    def __init__(
        self,
        type: str,
        timeframe: TimeframeType,
        dataset: QueryDataset,
        time_period: QueryTimePeriod = None
    ): ...

class QueryDataset:
    def __init__(
        self,
        granularity: GranularityType = None,
        aggregation: Dict[str, QueryAggregation] = None,
        grouping: List[QueryGrouping] = None,
        filter: QueryFilter = None
    ): ...

class QueryResult:
    columns: List[QueryColumn]
    rows: List[List[Any]]
    next_link: str

class ForecastDefinition:
    def __init__(
        self,
        type: ForecastType,
        timeframe: ForecastTimeframe,
        dataset: ForecastDataset,
        time_period: ForecastTimePeriod = None
    ): ...

class Alert:
    properties: AlertPropertiesDetails
    id: str
    name: str
    type: str

class Export:
    properties: ExportProperties
    id: str
    name: str
    type: str

class ScheduledAction:
    properties: ScheduleProperties
    kind: ScheduledActionKind
    id: str
    name: str

class DownloadURL:
    """URL to download generated price sheet or report."""
    expiry_time: datetime
    valid_till: datetime
    download_url: str

class CostManagementOperation:
    """A Cost Management REST API operation."""
    name: str
    is_data_action: bool
    display: OperationDisplay
    origin: str

Error Handling

All operations can raise standard Azure SDK exceptions:

from azure.core.exceptions import (
    ClientAuthenticationError,
    HttpResponseError,
    ResourceExistsError,
    ResourceNotFoundError,
    ResourceNotModifiedError
)

The package also includes specific error models:

  • ErrorResponse - Standard error response format
  • GenerateCostDetailsReportErrorResponse - Cost report specific errors
  • GenerateDetailedCostReportErrorResponse - Detailed report specific errors

Supported Scopes

The API supports various Azure resource scopes:

  • Subscription: /subscriptions/{subscriptionId}
  • Resource Group: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}
  • Billing Account: /providers/Microsoft.Billing/billingAccounts/{billingAccountId}
  • Billing Profile: /providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}
  • Management Group: /providers/Microsoft.Management/managementGroups/{managementGroupId}
  • External Cloud Providers: Support for AWS and other external providers