0
# Alert Policy Management
1
2
Comprehensive alert policy management for Google Cloud Monitoring, enabling creation, modification, and monitoring of alerting conditions based on metrics, logs, and resource states. Alert policies define when and how notifications are sent when specified conditions are met.
3
4
## Capabilities
5
6
### Alert Policy Operations
7
8
Manage the complete lifecycle of alert policies including creation, updates, retrieval, and deletion.
9
10
```python { .api }
11
class AlertPolicyServiceClient:
12
def list_alert_policies(
13
self,
14
request=None,
15
*,
16
name: str = None,
17
retry=None,
18
timeout=None,
19
metadata=()
20
) -> pagers.ListAlertPoliciesPager:
21
"""
22
Lists the existing alerting policies for the workspace.
23
24
Args:
25
request: The request object or dict equivalent
26
name: Required. Project name in format 'projects/[PROJECT_ID]'
27
retry: Retry configuration
28
timeout: Request timeout in seconds
29
metadata: Additional metadata
30
31
Returns:
32
Pager for iterating over AlertPolicy objects
33
"""
34
35
def get_alert_policy(
36
self,
37
request=None,
38
*,
39
name: str = None,
40
retry=None,
41
timeout=None,
42
metadata=()
43
) -> alert.AlertPolicy:
44
"""
45
Gets a single alerting policy.
46
47
Args:
48
request: The request object or dict equivalent
49
name: Required. Alert policy name in format 'projects/[PROJECT_ID]/alertPolicies/[ALERT_POLICY_ID]'
50
retry: Retry configuration
51
timeout: Request timeout in seconds
52
metadata: Additional metadata
53
54
Returns:
55
AlertPolicy object
56
"""
57
58
def create_alert_policy(
59
self,
60
request=None,
61
*,
62
name: str = None,
63
alert_policy: alert.AlertPolicy = None,
64
retry=None,
65
timeout=None,
66
metadata=()
67
) -> alert.AlertPolicy:
68
"""
69
Creates a new alerting policy.
70
71
Args:
72
request: The request object or dict equivalent
73
name: Required. Project name in format 'projects/[PROJECT_ID]'
74
alert_policy: Required. The alert policy to create
75
retry: Retry configuration
76
timeout: Request timeout in seconds
77
metadata: Additional metadata
78
79
Returns:
80
Created AlertPolicy object
81
"""
82
83
def update_alert_policy(
84
self,
85
request=None,
86
*,
87
update_mask=None,
88
alert_policy: alert.AlertPolicy = None,
89
retry=None,
90
timeout=None,
91
metadata=()
92
) -> alert.AlertPolicy:
93
"""
94
Updates an alerting policy.
95
96
Args:
97
request: The request object or dict equivalent
98
update_mask: Field mask for selective updates
99
alert_policy: Required. Updated alert policy
100
retry: Retry configuration
101
timeout: Request timeout in seconds
102
metadata: Additional metadata
103
104
Returns:
105
Updated AlertPolicy object
106
"""
107
108
def delete_alert_policy(
109
self,
110
request=None,
111
*,
112
name: str = None,
113
retry=None,
114
timeout=None,
115
metadata=()
116
) -> None:
117
"""
118
Deletes an alerting policy.
119
120
Args:
121
request: The request object or dict equivalent
122
name: Required. Alert policy name to delete
123
retry: Retry configuration
124
timeout: Request timeout in seconds
125
metadata: Additional metadata
126
"""
127
```
128
129
### Async Alert Policy Operations
130
131
Asynchronous versions of all alert policy operations for use with async/await patterns.
132
133
```python { .api }
134
class AlertPolicyServiceAsyncClient:
135
async def list_alert_policies(
136
self,
137
request=None,
138
*,
139
name: str = None,
140
retry=None,
141
timeout=None,
142
metadata=()
143
) -> pagers.ListAlertPoliciesAsyncPager:
144
"""Async version of list_alert_policies."""
145
146
async def get_alert_policy(
147
self,
148
request=None,
149
*,
150
name: str = None,
151
retry=None,
152
timeout=None,
153
metadata=()
154
) -> alert.AlertPolicy:
155
"""Async version of get_alert_policy."""
156
157
async def create_alert_policy(
158
self,
159
request=None,
160
*,
161
name: str = None,
162
alert_policy: alert.AlertPolicy = None,
163
retry=None,
164
timeout=None,
165
metadata=()
166
) -> alert.AlertPolicy:
167
"""Async version of create_alert_policy."""
168
169
async def update_alert_policy(
170
self,
171
request=None,
172
*,
173
update_mask=None,
174
alert_policy: alert.AlertPolicy = None,
175
retry=None,
176
timeout=None,
177
metadata=()
178
) -> alert.AlertPolicy:
179
"""Async version of update_alert_policy."""
180
181
async def delete_alert_policy(
182
self,
183
request=None,
184
*,
185
name: str = None,
186
retry=None,
187
timeout=None,
188
metadata=()
189
) -> None:
190
"""Async version of delete_alert_policy."""
191
```
192
193
## Data Types
194
195
### AlertPolicy
196
197
Main alert policy configuration containing conditions, notification channels, and policy metadata.
198
199
```python { .api }
200
class AlertPolicy:
201
name: str # Resource name
202
display_name: str # Human-readable name
203
documentation: AlertPolicy.Documentation # Alert documentation
204
user_labels: Dict[str, str] # User-defined labels
205
conditions: List[AlertPolicy.Condition] # Alert conditions
206
combiner: ConditionCombinerType # How to combine conditions
207
enabled: bool # Whether policy is enabled
208
validity: Status # Validation status
209
notification_channels: List[str] # Notification channel names
210
creation_record: MutationRecord # Creation metadata
211
mutation_record: MutationRecord # Last modification metadata
212
alert_strategy: AlertPolicy.AlertStrategy # Alert strategy configuration
213
214
class AlertPolicy.Condition:
215
name: str # Condition name
216
display_name: str # Human-readable name
217
condition_threshold: MetricThreshold # Threshold condition
218
condition_absent: MetricAbsence # Absence condition
219
condition_matched_log: LogMatch # Log match condition
220
condition_monitoring_query_language: MonitoringQueryLanguageCondition # MQL condition
221
222
class AlertPolicy.Documentation:
223
content: str # Documentation content
224
mime_type: str # Content MIME type
225
226
class AlertPolicy.AlertStrategy:
227
auto_close: Duration # Auto-close duration
228
notification_rate_limit: AlertPolicy.AlertStrategy.NotificationRateLimit # Rate limiting
229
```
230
231
### Request and Response Types
232
233
```python { .api }
234
class CreateAlertPolicyRequest:
235
name: str # Required. Project name
236
alert_policy: AlertPolicy # Required. Alert policy to create
237
238
class DeleteAlertPolicyRequest:
239
name: str # Required. Alert policy name to delete
240
241
class GetAlertPolicyRequest:
242
name: str # Required. Alert policy name to retrieve
243
244
class ListAlertPoliciesRequest:
245
name: str # Required. Project name
246
filter: str # Filter expression
247
order_by: str # Ordering specification
248
page_size: int # Maximum results per page
249
page_token: str # Page token for pagination
250
251
class ListAlertPoliciesResponse:
252
alert_policies: List[AlertPolicy] # Alert policies
253
next_page_token: str # Token for next page
254
255
class UpdateAlertPolicyRequest:
256
update_mask: FieldMask # Fields to update
257
alert_policy: AlertPolicy # Required. Updated alert policy
258
```
259
260
## Usage Examples
261
262
### Creating a Basic Threshold Alert Policy
263
264
```python
265
from google.cloud.monitoring import AlertPolicyServiceClient, AlertPolicy
266
from google.cloud.monitoring_v3.types import ComparisonType, Aggregation
267
268
client = AlertPolicyServiceClient()
269
project_name = f"projects/{project_id}"
270
271
# Create alert policy
272
policy = AlertPolicy()
273
policy.display_name = "High CPU Usage"
274
policy.enabled = True
275
276
# Create condition
277
condition = AlertPolicy.Condition()
278
condition.display_name = "CPU usage exceeds 80%"
279
280
# Configure threshold condition
281
threshold = condition.condition_threshold
282
threshold.filter = 'resource.type="gce_instance"'
283
threshold.comparison = ComparisonType.COMPARISON_GREATER
284
threshold.threshold_value.double_value = 0.8
285
286
# Configure aggregation
287
aggregation = Aggregation()
288
aggregation.alignment_period.seconds = 300 # 5 minutes
289
aggregation.per_series_aligner = Aggregation.Aligner.ALIGN_MEAN
290
threshold.aggregations = [aggregation]
291
292
policy.conditions = [condition]
293
policy.combiner = AlertPolicy.ConditionCombinerType.AND
294
295
# Add notification channels
296
policy.notification_channels = [
297
f"projects/{project_id}/notificationChannels/{channel_id}"
298
]
299
300
# Create the policy
301
created_policy = client.create_alert_policy(
302
name=project_name,
303
alert_policy=policy
304
)
305
print(f"Created alert policy: {created_policy.name}")
306
```
307
308
### Listing and Filtering Alert Policies
309
310
```python
311
client = AlertPolicyServiceClient()
312
project_name = f"projects/{project_id}"
313
314
# List all alert policies
315
for policy in client.list_alert_policies(name=project_name):
316
print(f"Policy: {policy.display_name}, Enabled: {policy.enabled}")
317
318
# List with filtering
319
filter_expr = 'display_name:"High CPU"'
320
for policy in client.list_alert_policies(name=project_name, filter=filter_expr):
321
print(f"Filtered policy: {policy.display_name}")
322
```
323
324
### Updating an Alert Policy
325
326
```python
327
from google.protobuf import field_mask_pb2
328
329
client = AlertPolicyServiceClient()
330
331
# Get existing policy
332
policy_name = f"projects/{project_id}/alertPolicies/{policy_id}"
333
policy = client.get_alert_policy(name=policy_name)
334
335
# Modify policy
336
policy.display_name = "Updated High CPU Alert"
337
policy.enabled = False
338
339
# Update with field mask
340
update_mask = field_mask_pb2.FieldMask()
341
update_mask.paths.extend(["display_name", "enabled"])
342
343
updated_policy = client.update_alert_policy(
344
alert_policy=policy,
345
update_mask=update_mask
346
)
347
print(f"Updated policy: {updated_policy.display_name}")
348
```
349
350
### Async Alert Policy Management
351
352
```python
353
import asyncio
354
from google.cloud.monitoring import AlertPolicyServiceAsyncClient
355
356
async def manage_alert_policies():
357
client = AlertPolicyServiceAsyncClient()
358
project_name = f"projects/{project_id}"
359
360
# List policies asynchronously
361
async for policy in await client.list_alert_policies(name=project_name):
362
print(f"Async policy: {policy.display_name}")
363
364
# Get policy asynchronously
365
policy = await client.get_alert_policy(name=policy_name)
366
print(f"Retrieved policy: {policy.display_name}")
367
368
# Run async function
369
asyncio.run(manage_alert_policies())
370
```
371
372
## Resource Path Helpers
373
374
```python { .api }
375
class AlertPolicyServiceClient:
376
@staticmethod
377
def alert_policy_path(project: str, alert_policy: str) -> str:
378
"""Returns a fully-qualified alert_policy string."""
379
380
@staticmethod
381
def alert_policy_condition_path(project: str, alert_policy: str, condition: str) -> str:
382
"""Returns a fully-qualified alert_policy_condition string."""
383
384
@staticmethod
385
def parse_alert_policy_path(path: str) -> Dict[str, str]:
386
"""Parses a alert_policy path into its component segments."""
387
```
388
389
## Error Handling
390
391
Alert policy operations can raise specific exceptions:
392
393
```python
394
from google.api_core import exceptions
395
from google.cloud.monitoring import AlertPolicyServiceClient
396
397
client = AlertPolicyServiceClient()
398
399
try:
400
policy = client.get_alert_policy(name="invalid/path")
401
except exceptions.NotFound:
402
print("Alert policy not found")
403
except exceptions.InvalidArgument as e:
404
print(f"Invalid request: {e}")
405
except exceptions.PermissionDenied:
406
print("Insufficient permissions")
407
except exceptions.ResourceExhausted:
408
print("Quota exceeded")
409
```