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

reports.mddocs/

Report Generation

Generate detailed cost reports including cost details reports, reservation details, and comprehensive billing reports with custom time periods and formats. Support for long-running operations with status monitoring and result retrieval for large-scale cost analysis and reporting workflows.

Capabilities

Cost Details Report Generation

Generate detailed cost reports with comprehensive cost breakdown and analysis for specified scopes and time periods.

def begin_create_operation(
    scope: str,
    parameters: GenerateCostDetailsReportRequestDefinition
) -> LROPoller[CostDetailsOperationResults]:
    """
    Start long-running cost details report generation.
    
    Args:
        scope (str): The scope for the report generation
        parameters (GenerateCostDetailsReportRequestDefinition): Report configuration
    
    Returns:
        LROPoller[CostDetailsOperationResults]: Long-running operation poller for cost details
    """

Detailed Cost Report Generation

Generate comprehensive detailed cost reports with advanced configuration options and custom metrics.

def begin_create_operation(
    scope: str,
    parameters: GenerateDetailedCostReportDefinition
) -> LROPoller[GenerateDetailedCostReportOperationResult]:
    """
    Start long-running detailed cost report generation.
    
    Args:
        scope (str): The scope for the report generation
        parameters (GenerateDetailedCostReportDefinition): Detailed report configuration
    
    Returns:
        LROPoller[GenerateDetailedCostReportOperationResult]: Long-running operation poller
    """

Detailed Cost Report Operation Management

Monitor and retrieve results from detailed cost report generation operations.

def get(operation_id: str, scope: str) -> GenerateDetailedCostReportOperationResult:
    """
    Get detailed cost report operation results by ID.
    
    Args:
        operation_id (str): The operation ID from the long-running operation
        scope (str): The scope of the operation
    
    Returns:
        GenerateDetailedCostReportOperationResult: Report generation results and download URLs
    """
def get(operation_id: str, scope: str) -> GenerateDetailedCostReportOperationStatuses:
    """
    Get detailed cost report operation status by ID.
    
    Args:
        operation_id (str): The operation ID from the long-running operation
        scope (str): The scope of the operation
    
    Returns:
        GenerateDetailedCostReportOperationStatuses: Current status of the report generation
    """

Reservation Details Report Generation

Generate specialized reports for Azure Reserved Instances with detailed usage and cost breakdown.

def begin_by_billing_account_id(
    billing_account_id: str,
    start_date: str,
    end_date: str
) -> LROPoller[ReservationDetailsOperationResults]:
    """
    Generate reservation details report by billing account.
    
    Args:
        billing_account_id (str): The billing account ID
        start_date (str): Report start date (YYYY-MM-DD format)
        end_date (str): Report end date (YYYY-MM-DD format)
    
    Returns:
        LROPoller[ReservationDetailsOperationResults]: Long-running operation for reservation report
    """

def begin_by_billing_profile_id(
    billing_account_id: str,
    billing_profile_id: str,
    start_date: str,
    end_date: str
) -> LROPoller[ReservationDetailsOperationResults]:
    """
    Generate reservation details report by billing profile.
    
    Args:
        billing_account_id (str): The billing account ID
        billing_profile_id (str): The billing profile ID
        start_date (str): Report start date (YYYY-MM-DD format)
        end_date (str): Report end date (YYYY-MM-DD format)
    
    Returns:
        LROPoller[ReservationDetailsOperationResults]: Long-running operation for reservation report
    """

Usage Examples

Generate Basic Cost Details Report

from azure.mgmt.costmanagement.models import (
    GenerateCostDetailsReportRequestDefinition,
    CostDetailsTimePeriod,
    CostDetailsMetricType,
    CostDetailsDataFormat
)

# Configure cost details report
report_config = GenerateCostDetailsReportRequestDefinition(
    metric=CostDetailsMetricType.ACTUAL_COST,
    time_period=CostDetailsTimePeriod(
        start="2024-01-01",
        end="2024-01-31"
    ),
    billing_period=None
)

# Start report generation
scope = "/subscriptions/{subscription-id}"
operation = client.generate_cost_details_report.begin_create_operation(
    scope=scope,
    parameters=report_config
)

print("Cost details report generation started...")
print(f"Operation ID: {operation.result().id}")

# Wait for completion
result = operation.result()
print(f"Report completed. Status: {result.status}")

if result.download_url:
    print(f"Download URL: {result.download_url}")

Generate Detailed Cost Report with Custom Configuration

from azure.mgmt.costmanagement.models import (
    GenerateDetailedCostReportDefinition,
    ReportConfigTimePeriod,
    GenerateDetailedCostReportTimePeriod,
    GenerateDetailedCostReportMetricType,
    ReportTimeframeType
)

# Configure detailed report with custom metrics
detailed_config = GenerateDetailedCostReportDefinition(
    metric=GenerateDetailedCostReportMetricType.AMORTIZED_COST,
    time_period=GenerateDetailedCostReportTimePeriod(
        start="2024-01-01",
        end="2024-03-31"
    ),
    billing_period=None,
    custom_filters=None
)

# Generate detailed report
detailed_operation = client.generate_detailed_cost_report.begin_create_operation(
    scope=scope,
    parameters=detailed_config
)

print("Detailed cost report generation started...")

# Monitor progress
while not detailed_operation.done():
    print("Report generation in progress...")
    time.sleep(30)  # Wait 30 seconds before checking again

detailed_result = detailed_operation.result()
print(f"Detailed report completed: {detailed_result.status}")

# Get download information
if hasattr(detailed_result, 'blob_info') and detailed_result.blob_info:
    print(f"Report size: {detailed_result.blob_info.blob_count} blobs")
    for i, blob in enumerate(detailed_result.blob_info.blobs):
        print(f"  Blob {i+1}: {blob.name}")

Monitor Report Generation Status

# Check operation status
operation_id = "report-op-123456"
status = client.generate_detailed_cost_report_operation_status.get(
    operation_id=operation_id,
    scope=scope
)

print(f"Report Operation Status:")
print(f"  Operation ID: {operation_id}")
print(f"  Status: {status.status}")
print(f"  Start Time: {status.start_time}")

if status.status == "Completed":
    # Get results when completed
    results = client.generate_detailed_cost_report_operation_results.get(
        operation_id=operation_id,
        scope=scope
    )
    
    print(f"Report Results:")
    print(f"  Manifest Version: {results.manifest_version}")
    print(f"  Data Format: {results.data_format}")
    
    if results.blob_info:
        print(f"  Number of Blobs: {len(results.blob_info.blobs)}")
        for blob in results.blob_info.blobs:
            print(f"    Blob: {blob.name} ({blob.size} bytes)")
            
elif status.status == "Failed":
    print(f"  Error: {status.error}")

Generate Reservation Details Report

import time
from datetime import datetime, timedelta

# Generate reservation report for last month
end_date = datetime.now().strftime("%Y-%m-%d")
start_date = (datetime.now() - timedelta(days=30)).strftime("%Y-%m-%d")

billing_account_id = "12345678"

# Start reservation report generation
reservation_operation = client.generate_reservation_details_report.begin_by_billing_account_id(
    billing_account_id=billing_account_id,
    start_date=start_date,
    end_date=end_date
)

print(f"Reservation details report generation started for period {start_date} to {end_date}")

# Wait for completion with progress updates
while not reservation_operation.done():
    print("Generating reservation report...")
    time.sleep(45)

reservation_result = reservation_operation.result()
print(f"Reservation report completed: {reservation_result.status}")

if hasattr(reservation_result, 'download_url') and reservation_result.download_url:
    print(f"Reservation report download URL: {reservation_result.download_url}")

Generate Report by Billing Profile

# Generate reservation report for specific billing profile
billing_profile_id = "bp-67890"

profile_operation = client.generate_reservation_details_report.begin_by_billing_profile_id(
    billing_account_id=billing_account_id,
    billing_profile_id=billing_profile_id,
    start_date=start_date,
    end_date=end_date
)

print("Generating billing profile reservation report...")
profile_result = profile_operation.result()

print(f"Billing profile report status: {profile_result.status}")

Batch Report Generation

# Generate multiple reports concurrently
import concurrent.futures

def generate_monthly_reports(months):
    """Generate reports for multiple months concurrently"""
    operations = []
    
    for month in months:
        start_date = f"2024-{month:02d}-01"
        if month == 12:
            end_date = f"2024-{month:02d}-31"
        else:
            end_date = f"2024-{month:02d}-28"  # Simplified for example
            
        config = GenerateCostDetailsReportRequestDefinition(
            metric=CostDetailsMetricType.ACTUAL_COST,
            time_period=CostDetailsTimePeriod(start=start_date, end=end_date)
        )
        
        operation = client.generate_cost_details_report.begin_create_operation(
            scope=scope,
            parameters=config
        )
        operations.append((month, operation))
    
    # Wait for all operations to complete
    results = {}
    for month, operation in operations:
        result = operation.result()
        results[month] = result
        print(f"Month {month} report: {result.status}")
    
    return results

# Generate reports for Q1
monthly_results = generate_monthly_reports([1, 2, 3])

Data Models

Cost Details Report Models

class GenerateCostDetailsReportRequestDefinition:
    metric: CostDetailsMetricType
    time_period: CostDetailsTimePeriod
    billing_period: str

class CostDetailsTimePeriod:
    start: str
    end: str

class CostDetailsOperationResults:
    id: str
    name: str
    type: str
    status: str
    download_url: str
    blob_info: BlobInfo
    error: ErrorDetails

Detailed Cost Report Models

class GenerateDetailedCostReportDefinition:
    metric: GenerateDetailedCostReportMetricType
    time_period: GenerateDetailedCostReportTimePeriod
    billing_period: str
    custom_filters: List[str]

class GenerateDetailedCostReportTimePeriod:
    start: str
    end: str

class GenerateDetailedCostReportOperationResult:
    id: str
    name: str
    type: str
    status: ReportOperationStatusType
    manifest_version: str
    data_format: str
    blob_info: BlobInfo
    error: ErrorDetails

class GenerateDetailedCostReportOperationStatuses:
    id: str
    name: str
    type: str
    status: ReportOperationStatusType
    start_time: str
    end_time: str
    error: ErrorDetails

Reservation Report Models

class ReservationDetailsOperationResults:
    id: str
    name: str
    type: str
    status: str
    download_url: DownloadURL
    error: ErrorDetails

class DownloadURL:
    expires_on: str
    url: str

Common Report Models

class BlobInfo:
    blob_count: int
    blobs: List[BlobDetails]

class BlobDetails:
    name: str
    size: int
    url: str

class ErrorDetails:
    code: str
    message: str
    details: List[ErrorDetails]

Report Enumerations

class CostDetailsMetricType(str, Enum):
    ACTUAL_COST = "ActualCost"
    AMORTIZED_COST = "AmortizedCost"

class GenerateDetailedCostReportMetricType(str, Enum):
    ACTUAL_COST = "ActualCost"
    AMORTIZED_COST = "AmortizedCost"

class CostDetailsDataFormat(str, Enum):
    CSV = "Csv"

class ReportOperationStatusType(str, Enum):
    RUNNING = "Running"
    COMPLETED = "Completed"
    FAILED = "Failed"
    TIMED_OUT = "TimedOut"

class CostDetailsStatusType(str, Enum):
    COMPLETED = "Completed"
    DATA_NOT_AVAILABLE = "DataNotAvailable"
    FAILED = "Failed"
    IN_PROGRESS = "InProgress"
    QUEUED = "Queued"
    TIMED_OUT = "TimedOut"

class ReservationReportSchema(str, Enum):
    INSTANCE_FLEXIBILITY_RATIO = "InstanceFlexibilityRatio"
    INSTANCE_FLEXIBILITY_GROUP = "InstanceFlexibilityGroup"

This module provides comprehensive report generation capabilities for detailed cost analysis, reservation tracking, and large-scale billing data export with support for long-running operations and multiple output formats.

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