CtrlK
BlogDocsLog inGet started
Tessl Logo

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.

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

query-forecast.mddocs/

Query and Forecast Operations

Core functionality for querying historical cost data and generating predictive cost forecasts. These operations provide the foundation for cost analysis, usage reporting, and financial planning across Azure resources and external cloud providers.

Capabilities

Cost and Usage Queries

Query historical cost and usage data with flexible filtering, grouping, and aggregation options. Supports multiple timeframes and granularities for detailed cost analysis.

def usage(scope: str, parameters: QueryDefinition) -> QueryResult:
    """
    Query cost and usage data for the specified scope.
    
    Args:
        scope (str): The scope for the query (subscription, resource group, etc.)
        parameters (QueryDefinition): Query configuration including timeframe, dataset, and filters
    
    Returns:
        QueryResult: Query results with columns and data rows
    """

def usage_by_external_cloud_provider_type(
    external_cloud_provider_type: str,
    external_cloud_provider_id: str,
    parameters: QueryDefinition
) -> QueryResult:
    """
    Query cost and usage data for external cloud providers like AWS.
    
    Args:
        external_cloud_provider_type (str): Provider type (e.g., "aws")
        external_cloud_provider_id (str): Provider account identifier
        parameters (QueryDefinition): Query configuration
    
    Returns:
        QueryResult: Query results for external provider
    """

Cost Forecasting

Generate predictive cost forecasts based on historical usage patterns and trends. Supports various forecast types and time horizons for budget planning.

def usage(scope: str, parameters: ForecastDefinition) -> ForecastResult:
    """
    Generate cost forecast for the specified scope.
    
    Args:
        scope (str): The scope for the forecast
        parameters (ForecastDefinition): Forecast configuration including type and timeframe
    
    Returns:
        ForecastResult: Forecast data with predicted costs
    """

def external_cloud_provider_usage(
    external_cloud_provider_type: str,
    external_cloud_provider_id: str,
    parameters: ForecastDefinition
) -> ForecastResult:
    """
    Generate cost forecast for external cloud providers.
    
    Args:
        external_cloud_provider_type (str): Provider type
        external_cloud_provider_id (str): Provider account identifier
        parameters (ForecastDefinition): Forecast configuration
    
    Returns:
        ForecastResult: Forecast data for external provider
    """

Usage Examples

Basic Cost Query

from azure.mgmt.costmanagement.models import (
    QueryDefinition,
    QueryDataset,
    QueryAggregation,
    TimeframeType,
    GranularityType
)

# Query monthly costs for current month
query_def = QueryDefinition(
    type="Usage",
    timeframe=TimeframeType.MONTH_TO_DATE,
    dataset=QueryDataset(
        granularity=GranularityType.DAILY,
        aggregation={
            "totalCost": QueryAggregation(name="Cost", function="Sum"),
            "totalUsage": QueryAggregation(name="UsageQuantity", function="Sum")
        }
    )
)

scope = "/subscriptions/{subscription-id}"
result = client.query.usage(scope, query_def)

# Process results
for row in result.rows:
    date = row[0]
    cost = row[1]
    usage = row[2]
    print(f"Date: {date}, Cost: ${cost:.2f}, Usage: {usage}")

Advanced Query with Filtering and Grouping

from azure.mgmt.costmanagement.models import (
    QueryDefinition,
    QueryDataset,
    QueryAggregation,
    QueryGrouping,
    QueryFilter,
    QueryComparisonExpression,
    TimeframeType,
    GranularityType,
    QueryOperatorType
)

# Query costs grouped by resource group with filtering
query_def = QueryDefinition(
    type="ActualCost",
    timeframe=TimeframeType.THE_LAST_MONTH,
    dataset=QueryDataset(
        granularity=GranularityType.MONTHLY,
        aggregation={
            "totalCost": QueryAggregation(name="Cost", function="Sum")
        },
        grouping=[
            QueryGrouping(type="Dimension", name="ResourceGroup")
        ],
        filter=QueryFilter(
            and_=[
                QueryComparisonExpression(
                    name="ResourceType",
                    operator=QueryOperatorType.IN,
                    values=["Microsoft.Compute/virtualMachines", "Microsoft.Storage/storageAccounts"]
                )
            ]
        )
    )
)

result = client.query.usage(scope, query_def)
print(f"Found {len(result.rows)} resource groups")

Cost Forecast Generation

from azure.mgmt.costmanagement.models import (
    ForecastDefinition,
    ForecastDataset,
    ForecastAggregation,
    ForecastTimeframe,
    ForecastType,
    GranularityType
)

# Generate 30-day cost forecast
forecast_def = ForecastDefinition(
    type=ForecastType.ACTUAL_COST,
    timeframe=ForecastTimeframe.MONTH_TO_DATE,
    dataset=ForecastDataset(
        granularity=GranularityType.DAILY,
        aggregation={
            "totalCost": ForecastAggregation(name="Cost", function="Sum")
        }
    )
)

forecast_result = client.forecast.usage(scope, forecast_def)

# Process forecast data
for row in forecast_result.rows:
    date = row[0]
    forecasted_cost = row[1]
    print(f"Forecasted - Date: {date}, Cost: ${forecasted_cost:.2f}")

External Cloud Provider Query

# Query AWS costs
aws_query = QueryDefinition(
    type="Usage",
    timeframe=TimeframeType.THE_LAST_MONTH,
    dataset=QueryDataset(
        granularity=GranularityType.DAILY,
        aggregation={
            "totalCost": QueryAggregation(name="Cost", function="Sum")
        }
    )
)

aws_result = client.query.usage_by_external_cloud_provider_type(
    external_cloud_provider_type="aws",
    external_cloud_provider_id="123456789012",
    parameters=aws_query
)

Data Models

Query Models

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,
        sorting: List[QuerySorting] = None
    ): ...

class QueryAggregation:
    def __init__(self, name: str, function: str): ...

class QueryGrouping:
    def __init__(self, type: str, name: str): ...

class QueryFilter:
    def __init__(
        self,
        and_: List[QueryComparisonExpression] = None,
        or_: List[QueryComparisonExpression] = None,
        not_: QueryComparisonExpression = None
    ): ...

class QueryComparisonExpression:
    def __init__(self, name: str, operator: QueryOperatorType, values: List[str]): ...

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

class QueryColumn:
    name: str
    type: str

Forecast Models

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

class ForecastDataset:
    def __init__(
        self,
        granularity: GranularityType = None,
        aggregation: Dict[str, ForecastAggregation] = None,
        filter: ForecastFilter = None
    ): ...

class ForecastAggregation:
    def __init__(self, name: str, function: str): ...

class ForecastResult:
    columns: List[ForecastColumn]
    rows: List[List[Any]]
    next_link: str

class ForecastColumn:
    name: str
    type: str

Enumerations

Query Enumerations

class TimeframeType(str, Enum):
    MONTH_TO_DATE = "MonthToDate"
    BILLING_MONTH_TO_DATE = "BillingMonthToDate"
    THE_LAST_MONTH = "TheLastMonth"
    THE_LAST_BILLING_MONTH = "TheLastBillingMonth"
    WEEK_TO_DATE = "WeekToDate"
    THE_LAST_WEEK = "TheLastWeek"
    CUSTOM = "Custom"

class GranularityType(str, Enum):
    DAILY = "Daily"
    MONTHLY = "Monthly"

class MetricType(str, Enum):
    ACTUAL_COST = "ActualCost"
    AMORTIZED_COST = "AmortizedCost"
    USAGE = "Usage"

class QueryOperatorType(str, Enum):
    IN = "In"

class FunctionType(str, Enum):  
    SUM = "Sum"

Forecast Enumerations

class ForecastType(str, Enum):
    USAGE = "Usage"
    ACTUAL_COST = "ActualCost"
    AMORTIZED_COST = "AmortizedCost"

class ForecastTimeframe(str, Enum):
    MONTH_TO_DATE = "MonthToDate"
    BILLING_MONTH_TO_DATE = "BillingMonthToDate"
    THE_LAST_MONTH = "TheLastMonth"
    THE_LAST_BILLING_MONTH = "TheLastBillingMonth"
    WEEK_TO_DATE = "WeekToDate"
    THE_LAST_WEEK = "TheLastWeek"
    CUSTOM = "Custom"

class ForecastOperatorType(str, Enum):
    IN = "In"

This module provides comprehensive cost querying and forecasting capabilities, supporting complex analytical queries with flexible filtering, grouping, and aggregation options across Azure and external cloud resources.

Install with Tessl CLI

npx tessl i tessl/pypi-azure-mgmt-costmanagement

docs

alerts.md

benefits.md

dimensions.md

exports.md

index.md

price-sheet.md

query-forecast.md

reports.md

scheduled-actions.md

views.md

tile.json