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.00
# Azure Cost Management
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: azure-mgmt-costmanagement
7
- **Language**: Python
8
- **Version**: 4.0.1
9
- **API Version**: 2022-10-01
10
- **Installation**: `pip install azure-mgmt-costmanagement`
11
12
## Core Imports
13
14
```python
15
from azure.mgmt.costmanagement import CostManagementClient
16
```
17
18
For async operations:
19
20
```python
21
from azure.mgmt.costmanagement.aio import CostManagementClient
22
```
23
24
Authentication (requires azure-identity):
25
26
```python
27
from azure.identity import DefaultAzureCredential
28
from azure.mgmt.costmanagement import CostManagementClient
29
30
credential = DefaultAzureCredential()
31
```
32
33
## Basic Usage
34
35
```python
36
from azure.identity import DefaultAzureCredential
37
from azure.mgmt.costmanagement import CostManagementClient
38
39
# Initialize client with authentication
40
credential = DefaultAzureCredential()
41
client = CostManagementClient(credential)
42
43
# Define scope (subscription example)
44
scope = "/subscriptions/{subscription-id}"
45
46
# Query cost data
47
from azure.mgmt.costmanagement.models import QueryDefinition, QueryDataset, QueryAggregation, QueryTimePeriod, TimeframeType, GranularityType
48
49
query_def = QueryDefinition(
50
type="Usage",
51
timeframe=TimeframeType.MONTH_TO_DATE,
52
dataset=QueryDataset(
53
granularity=GranularityType.DAILY,
54
aggregation={
55
"totalCost": QueryAggregation(name="Cost", function="Sum")
56
}
57
)
58
)
59
60
result = client.query.usage(scope, query_def)
61
for row in result.rows:
62
print(f"Date: {row[0]}, Cost: {row[1]}")
63
64
# List cost alerts
65
alerts = client.alerts.list(scope)
66
for alert in alerts.value:
67
print(f"Alert: {alert.properties.alert_id}, Status: {alert.properties.status}")
68
69
# Get cost dimensions for filtering
70
dimensions = client.dimensions.list(scope)
71
for dimension in dimensions.value:
72
print(f"Dimension: {dimension.name}, Category: {dimension.category}")
73
```
74
75
## Architecture
76
77
The Azure Cost Management SDK follows the standard Azure SDK architecture:
78
79
- **CostManagementClient**: Main client class providing access to all operations
80
- **Operation Groups**: Logical groupings of related operations (query, alerts, exports, etc.)
81
- **Models**: Data classes representing request/response objects and Azure resources
82
- **Authentication**: Integration with Azure Identity for various authentication methods
83
- **Async Support**: Full async/await support with separate async client
84
85
The client supports various Azure scopes including subscriptions, resource groups, billing accounts, management groups, and external cloud providers.
86
87
## Capabilities
88
89
### Query and Forecast Operations
90
91
Core functionality for querying cost data and generating forecasts. Includes cost analysis, usage queries, and predictive cost modeling across different time periods and granularities.
92
93
```python { .api }
94
def usage(scope: str, parameters: QueryDefinition) -> QueryResult: ...
95
def usage_by_external_cloud_provider_type(
96
external_cloud_provider_type: str,
97
external_cloud_provider_id: str,
98
parameters: QueryDefinition
99
) -> QueryResult: ...
100
```
101
102
```python { .api }
103
def usage(scope: str, parameters: ForecastDefinition) -> ForecastResult: ...
104
def external_cloud_provider_usage(
105
external_cloud_provider_type: str,
106
external_cloud_provider_id: str,
107
parameters: ForecastDefinition
108
) -> ForecastResult: ...
109
```
110
111
[Query and Forecast](./query-forecast.md)
112
113
### Cost Management Views
114
115
Manage and organize cost analysis views for consistent reporting and sharing across teams. Create, update, and delete custom views with specific filters and configurations.
116
117
```python { .api }
118
def list() -> ViewListResult: ...
119
def get(view_name: str) -> View: ...
120
def create_or_update(view_name: str, parameters: View) -> View: ...
121
def delete(view_name: str) -> None: ...
122
def list_by_scope(scope: str) -> ViewListResult: ...
123
```
124
125
[Views Management](./views.md)
126
127
### Alerts Management
128
129
Monitor and manage cost alerts and budget notifications. Set up automated alerts for cost thresholds, budget overruns, and anomaly detection.
130
131
```python { .api }
132
def list(scope: str) -> AlertsResult: ...
133
def get(scope: str, alert_id: str) -> Alert: ...
134
def dismiss(scope: str, alert_id: str, parameters: DismissAlertPayload) -> Alert: ...
135
def list_external(
136
external_cloud_provider_type: str,
137
external_cloud_provider_id: str
138
) -> AlertsResult: ...
139
```
140
141
[Alerts](./alerts.md)
142
143
### Data Export Operations
144
145
Schedule and manage automated data exports for cost and usage data. Configure recurring exports to storage accounts with custom formats and delivery schedules.
146
147
```python { .api }
148
def list(scope: str, expand: str = None) -> ExportListResult: ...
149
def get(scope: str, export_name: str, expand: str = None) -> Export: ...
150
def create_or_update(scope: str, export_name: str, parameters: Export) -> Export: ...
151
def execute(scope: str, export_name: str) -> ExportRun: ...
152
def get_execution_history(scope: str, export_name: str) -> ExportExecutionListResult: ...
153
```
154
155
[Data Exports](./exports.md)
156
157
### Scheduled Actions
158
159
Automate cost management tasks with scheduled actions including email notifications, insights alerts, and custom workflows triggered by cost events.
160
161
```python { .api }
162
def list(filter: str = None) -> ScheduledActionListResult: ...
163
def create_or_update(
164
name: str,
165
scheduled_action: ScheduledAction,
166
if_match: str = None
167
) -> ScheduledAction: ...
168
def run(name: str) -> None: ...
169
def check_name_availability(body: CheckNameAvailabilityRequest) -> CheckNameAvailabilityResponse: ...
170
```
171
172
[Scheduled Actions](./scheduled-actions.md)
173
174
### Benefit Recommendations and Utilization
175
176
Analyze and optimize Azure Reserved Instances, Savings Plans, and other cost-saving benefits. Get recommendations for optimal purchasing decisions and track utilization.
177
178
```python { .api }
179
def list(
180
scope: str,
181
filter: str = None,
182
orderby: str = None,
183
expand: str = None
184
) -> BenefitRecommendationsListResult: ...
185
```
186
187
```python { .api }
188
def list_by_billing_account_id(
189
billing_account_id: str,
190
filter: str = None,
191
grain_parameter: str = None
192
) -> BenefitUtilizationSummariesListResult: ...
193
def list_by_savings_plan_order(
194
savings_plan_order_id: str,
195
filter: str = None,
196
grain_parameter: str = None
197
) -> BenefitUtilizationSummariesListResult: ...
198
```
199
200
[Benefits and Recommendations](./benefits.md)
201
202
### Report Generation
203
204
Generate detailed cost reports including cost details reports, reservation details, and comprehensive billing reports with custom time periods and formats.
205
206
```python { .api }
207
def begin_create_operation(
208
scope: str,
209
parameters: GenerateCostDetailsReportRequestDefinition
210
) -> LROPoller[CostDetailsOperationResults]: ...
211
```
212
213
```python { .api }
214
def begin_create_operation(
215
scope: str,
216
parameters: GenerateDetailedCostReportDefinition
217
) -> LROPoller[GenerateDetailedCostReportOperationResult]: ...
218
```
219
220
[Report Generation](./reports.md)
221
222
### Dimensions and Metadata
223
224
Query available cost dimensions for building filters and groupings. Access metadata about available cost categories, resource types, and billing dimensions.
225
226
```python { .api }
227
def list(
228
scope: str,
229
filter: str = None,
230
expand: str = None,
231
skiptoken: str = None,
232
top: int = None
233
) -> DimensionsListResult: ...
234
```
235
236
[Dimensions](./dimensions.md)
237
238
### Price Sheet Operations
239
240
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.
241
242
```python { .api }
243
def begin_download(
244
billing_account_name: str,
245
billing_profile_name: str,
246
invoice_name: str
247
) -> LROPoller[DownloadURL]: ...
248
def begin_download_by_billing_profile(
249
billing_account_name: str,
250
billing_profile_name: str
251
) -> LROPoller[DownloadURL]: ...
252
```
253
254
[Price Sheet](./price-sheet.md)
255
256
### API Operations Discovery
257
258
List and discover all available Cost Management REST API operations for programmatic exploration of service capabilities.
259
260
```python { .api }
261
def list() -> Iterable[CostManagementOperation]:
262
"""
263
Lists all available cost management REST API operations.
264
265
Returns:
266
Iterable[CostManagementOperation]: Iterator of available operations with metadata
267
"""
268
```
269
270
## Core Data Types
271
272
```python { .api }
273
class CostManagementClient:
274
def __init__(
275
self,
276
credential: TokenCredential,
277
base_url: str = "https://management.azure.com",
278
**kwargs
279
): ...
280
281
def close(self) -> None: ...
282
def __enter__(self) -> "CostManagementClient": ...
283
def __exit__(self, *exc_details) -> None: ...
284
285
class QueryDefinition:
286
def __init__(
287
self,
288
type: str,
289
timeframe: TimeframeType,
290
dataset: QueryDataset,
291
time_period: QueryTimePeriod = None
292
): ...
293
294
class QueryDataset:
295
def __init__(
296
self,
297
granularity: GranularityType = None,
298
aggregation: Dict[str, QueryAggregation] = None,
299
grouping: List[QueryGrouping] = None,
300
filter: QueryFilter = None
301
): ...
302
303
class QueryResult:
304
columns: List[QueryColumn]
305
rows: List[List[Any]]
306
next_link: str
307
308
class ForecastDefinition:
309
def __init__(
310
self,
311
type: ForecastType,
312
timeframe: ForecastTimeframe,
313
dataset: ForecastDataset,
314
time_period: ForecastTimePeriod = None
315
): ...
316
317
class Alert:
318
properties: AlertPropertiesDetails
319
id: str
320
name: str
321
type: str
322
323
class Export:
324
properties: ExportProperties
325
id: str
326
name: str
327
type: str
328
329
class ScheduledAction:
330
properties: ScheduleProperties
331
kind: ScheduledActionKind
332
id: str
333
name: str
334
335
class DownloadURL:
336
"""URL to download generated price sheet or report."""
337
expiry_time: datetime
338
valid_till: datetime
339
download_url: str
340
341
class CostManagementOperation:
342
"""A Cost Management REST API operation."""
343
name: str
344
is_data_action: bool
345
display: OperationDisplay
346
origin: str
347
```
348
349
## Error Handling
350
351
All operations can raise standard Azure SDK exceptions:
352
353
```python { .api }
354
from azure.core.exceptions import (
355
ClientAuthenticationError,
356
HttpResponseError,
357
ResourceExistsError,
358
ResourceNotFoundError,
359
ResourceNotModifiedError
360
)
361
```
362
363
The package also includes specific error models:
364
- `ErrorResponse` - Standard error response format
365
- `GenerateCostDetailsReportErrorResponse` - Cost report specific errors
366
- `GenerateDetailedCostReportErrorResponse` - Detailed report specific errors
367
368
## Supported Scopes
369
370
The API supports various Azure resource scopes:
371
372
- **Subscription**: `/subscriptions/{subscriptionId}`
373
- **Resource Group**: `/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}`
374
- **Billing Account**: `/providers/Microsoft.Billing/billingAccounts/{billingAccountId}`
375
- **Billing Profile**: `/providers/Microsoft.Billing/billingAccounts/{billingAccountId}/billingProfiles/{billingProfileId}`
376
- **Management Group**: `/providers/Microsoft.Management/managementGroups/{managementGroupId}`
377
- **External Cloud Providers**: Support for AWS and other external providers