Microsoft Azure Cost Management Client Library for Python providing comprehensive access to cost analysis, billing data, budgets, alerts, exports, and recommendations.
npx @tessl/cli install tessl/pypi-azure-mgmt-costmanagement@4.0.0Microsoft 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.
pip install azure-mgmt-costmanagementfrom azure.mgmt.costmanagement import CostManagementClientFor async operations:
from azure.mgmt.costmanagement.aio import CostManagementClientAuthentication (requires azure-identity):
from azure.identity import DefaultAzureCredential
from azure.mgmt.costmanagement import CostManagementClient
credential = DefaultAzureCredential()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}")The Azure Cost Management SDK follows the standard Azure SDK architecture:
The client supports various Azure scopes including subscriptions, resource groups, billing accounts, management groups, and external cloud providers.
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: ...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: ...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: ...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: ...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: ...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: ...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]: ...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: ...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]: ...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
"""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: strAll 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 formatGenerateCostDetailsReportErrorResponse - Cost report specific errorsGenerateDetailedCostReportErrorResponse - Detailed report specific errorsThe API supports various Azure resource scopes:
/subscriptions/{subscriptionId}/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}/providers/Microsoft.Management/managementGroups/{managementGroupId}