0
# Query and Forecast Operations
1
2
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.
3
4
## Capabilities
5
6
### Cost and Usage Queries
7
8
Query historical cost and usage data with flexible filtering, grouping, and aggregation options. Supports multiple timeframes and granularities for detailed cost analysis.
9
10
```python { .api }
11
def usage(scope: str, parameters: QueryDefinition) -> QueryResult:
12
"""
13
Query cost and usage data for the specified scope.
14
15
Args:
16
scope (str): The scope for the query (subscription, resource group, etc.)
17
parameters (QueryDefinition): Query configuration including timeframe, dataset, and filters
18
19
Returns:
20
QueryResult: Query results with columns and data rows
21
"""
22
23
def usage_by_external_cloud_provider_type(
24
external_cloud_provider_type: str,
25
external_cloud_provider_id: str,
26
parameters: QueryDefinition
27
) -> QueryResult:
28
"""
29
Query cost and usage data for external cloud providers like AWS.
30
31
Args:
32
external_cloud_provider_type (str): Provider type (e.g., "aws")
33
external_cloud_provider_id (str): Provider account identifier
34
parameters (QueryDefinition): Query configuration
35
36
Returns:
37
QueryResult: Query results for external provider
38
"""
39
```
40
41
### Cost Forecasting
42
43
Generate predictive cost forecasts based on historical usage patterns and trends. Supports various forecast types and time horizons for budget planning.
44
45
```python { .api }
46
def usage(scope: str, parameters: ForecastDefinition) -> ForecastResult:
47
"""
48
Generate cost forecast for the specified scope.
49
50
Args:
51
scope (str): The scope for the forecast
52
parameters (ForecastDefinition): Forecast configuration including type and timeframe
53
54
Returns:
55
ForecastResult: Forecast data with predicted costs
56
"""
57
58
def external_cloud_provider_usage(
59
external_cloud_provider_type: str,
60
external_cloud_provider_id: str,
61
parameters: ForecastDefinition
62
) -> ForecastResult:
63
"""
64
Generate cost forecast for external cloud providers.
65
66
Args:
67
external_cloud_provider_type (str): Provider type
68
external_cloud_provider_id (str): Provider account identifier
69
parameters (ForecastDefinition): Forecast configuration
70
71
Returns:
72
ForecastResult: Forecast data for external provider
73
"""
74
```
75
76
## Usage Examples
77
78
### Basic Cost Query
79
80
```python
81
from azure.mgmt.costmanagement.models import (
82
QueryDefinition,
83
QueryDataset,
84
QueryAggregation,
85
TimeframeType,
86
GranularityType
87
)
88
89
# Query monthly costs for current month
90
query_def = QueryDefinition(
91
type="Usage",
92
timeframe=TimeframeType.MONTH_TO_DATE,
93
dataset=QueryDataset(
94
granularity=GranularityType.DAILY,
95
aggregation={
96
"totalCost": QueryAggregation(name="Cost", function="Sum"),
97
"totalUsage": QueryAggregation(name="UsageQuantity", function="Sum")
98
}
99
)
100
)
101
102
scope = "/subscriptions/{subscription-id}"
103
result = client.query.usage(scope, query_def)
104
105
# Process results
106
for row in result.rows:
107
date = row[0]
108
cost = row[1]
109
usage = row[2]
110
print(f"Date: {date}, Cost: ${cost:.2f}, Usage: {usage}")
111
```
112
113
### Advanced Query with Filtering and Grouping
114
115
```python
116
from azure.mgmt.costmanagement.models import (
117
QueryDefinition,
118
QueryDataset,
119
QueryAggregation,
120
QueryGrouping,
121
QueryFilter,
122
QueryComparisonExpression,
123
TimeframeType,
124
GranularityType,
125
QueryOperatorType
126
)
127
128
# Query costs grouped by resource group with filtering
129
query_def = QueryDefinition(
130
type="ActualCost",
131
timeframe=TimeframeType.THE_LAST_MONTH,
132
dataset=QueryDataset(
133
granularity=GranularityType.MONTHLY,
134
aggregation={
135
"totalCost": QueryAggregation(name="Cost", function="Sum")
136
},
137
grouping=[
138
QueryGrouping(type="Dimension", name="ResourceGroup")
139
],
140
filter=QueryFilter(
141
and_=[
142
QueryComparisonExpression(
143
name="ResourceType",
144
operator=QueryOperatorType.IN,
145
values=["Microsoft.Compute/virtualMachines", "Microsoft.Storage/storageAccounts"]
146
)
147
]
148
)
149
)
150
)
151
152
result = client.query.usage(scope, query_def)
153
print(f"Found {len(result.rows)} resource groups")
154
```
155
156
### Cost Forecast Generation
157
158
```python
159
from azure.mgmt.costmanagement.models import (
160
ForecastDefinition,
161
ForecastDataset,
162
ForecastAggregation,
163
ForecastTimeframe,
164
ForecastType,
165
GranularityType
166
)
167
168
# Generate 30-day cost forecast
169
forecast_def = ForecastDefinition(
170
type=ForecastType.ACTUAL_COST,
171
timeframe=ForecastTimeframe.MONTH_TO_DATE,
172
dataset=ForecastDataset(
173
granularity=GranularityType.DAILY,
174
aggregation={
175
"totalCost": ForecastAggregation(name="Cost", function="Sum")
176
}
177
)
178
)
179
180
forecast_result = client.forecast.usage(scope, forecast_def)
181
182
# Process forecast data
183
for row in forecast_result.rows:
184
date = row[0]
185
forecasted_cost = row[1]
186
print(f"Forecasted - Date: {date}, Cost: ${forecasted_cost:.2f}")
187
```
188
189
### External Cloud Provider Query
190
191
```python
192
# Query AWS costs
193
aws_query = QueryDefinition(
194
type="Usage",
195
timeframe=TimeframeType.THE_LAST_MONTH,
196
dataset=QueryDataset(
197
granularity=GranularityType.DAILY,
198
aggregation={
199
"totalCost": QueryAggregation(name="Cost", function="Sum")
200
}
201
)
202
)
203
204
aws_result = client.query.usage_by_external_cloud_provider_type(
205
external_cloud_provider_type="aws",
206
external_cloud_provider_id="123456789012",
207
parameters=aws_query
208
)
209
```
210
211
## Data Models
212
213
### Query Models
214
215
```python { .api }
216
class QueryDefinition:
217
def __init__(
218
self,
219
type: str,
220
timeframe: TimeframeType,
221
dataset: QueryDataset,
222
time_period: QueryTimePeriod = None
223
): ...
224
225
class QueryDataset:
226
def __init__(
227
self,
228
granularity: GranularityType = None,
229
aggregation: Dict[str, QueryAggregation] = None,
230
grouping: List[QueryGrouping] = None,
231
filter: QueryFilter = None,
232
sorting: List[QuerySorting] = None
233
): ...
234
235
class QueryAggregation:
236
def __init__(self, name: str, function: str): ...
237
238
class QueryGrouping:
239
def __init__(self, type: str, name: str): ...
240
241
class QueryFilter:
242
def __init__(
243
self,
244
and_: List[QueryComparisonExpression] = None,
245
or_: List[QueryComparisonExpression] = None,
246
not_: QueryComparisonExpression = None
247
): ...
248
249
class QueryComparisonExpression:
250
def __init__(self, name: str, operator: QueryOperatorType, values: List[str]): ...
251
252
class QueryResult:
253
columns: List[QueryColumn]
254
rows: List[List[Any]]
255
next_link: str
256
257
class QueryColumn:
258
name: str
259
type: str
260
```
261
262
### Forecast Models
263
264
```python { .api }
265
class ForecastDefinition:
266
def __init__(
267
self,
268
type: ForecastType,
269
timeframe: ForecastTimeframe,
270
dataset: ForecastDataset,
271
time_period: ForecastTimePeriod = None
272
): ...
273
274
class ForecastDataset:
275
def __init__(
276
self,
277
granularity: GranularityType = None,
278
aggregation: Dict[str, ForecastAggregation] = None,
279
filter: ForecastFilter = None
280
): ...
281
282
class ForecastAggregation:
283
def __init__(self, name: str, function: str): ...
284
285
class ForecastResult:
286
columns: List[ForecastColumn]
287
rows: List[List[Any]]
288
next_link: str
289
290
class ForecastColumn:
291
name: str
292
type: str
293
```
294
295
## Enumerations
296
297
### Query Enumerations
298
299
```python { .api }
300
class TimeframeType(str, Enum):
301
MONTH_TO_DATE = "MonthToDate"
302
BILLING_MONTH_TO_DATE = "BillingMonthToDate"
303
THE_LAST_MONTH = "TheLastMonth"
304
THE_LAST_BILLING_MONTH = "TheLastBillingMonth"
305
WEEK_TO_DATE = "WeekToDate"
306
THE_LAST_WEEK = "TheLastWeek"
307
CUSTOM = "Custom"
308
309
class GranularityType(str, Enum):
310
DAILY = "Daily"
311
MONTHLY = "Monthly"
312
313
class MetricType(str, Enum):
314
ACTUAL_COST = "ActualCost"
315
AMORTIZED_COST = "AmortizedCost"
316
USAGE = "Usage"
317
318
class QueryOperatorType(str, Enum):
319
IN = "In"
320
321
class FunctionType(str, Enum):
322
SUM = "Sum"
323
```
324
325
### Forecast Enumerations
326
327
```python { .api }
328
class ForecastType(str, Enum):
329
USAGE = "Usage"
330
ACTUAL_COST = "ActualCost"
331
AMORTIZED_COST = "AmortizedCost"
332
333
class ForecastTimeframe(str, Enum):
334
MONTH_TO_DATE = "MonthToDate"
335
BILLING_MONTH_TO_DATE = "BillingMonthToDate"
336
THE_LAST_MONTH = "TheLastMonth"
337
THE_LAST_BILLING_MONTH = "TheLastBillingMonth"
338
WEEK_TO_DATE = "WeekToDate"
339
THE_LAST_WEEK = "TheLastWeek"
340
CUSTOM = "Custom"
341
342
class ForecastOperatorType(str, Enum):
343
IN = "In"
344
```
345
346
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.