| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
__metaclass__ = type |
| 9 |
|
| 10 |
DOCUMENTATION = ''' |
| 11 |
--- |
| 12 |
module: azure_rm_monitormetricalerts |
| 13 |
version_added: "3.7.0" |
| 14 |
short_description: Create, update and delete metric alerts. |
| 15 |
description: |
| 16 |
- Create, update and delete metric alerts. |
| 17 |
- >- |
| 18 |
U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2018_03_01.operations.metricalertsoperations?view=azure-python#azure-mgmt-monitor-v2018-03-01-operations-metricalertsoperations-create-or-update) |
| 19 |
- U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2018_03_01.models.metricalertresource?view=azure-python) |
| 20 |
options: |
| 21 |
name: |
| 22 |
description: |
| 23 |
- The name of the metric alert you're creating, updateing or deleting. |
| 24 |
required: true |
| 25 |
type: str |
| 26 |
resource_group: |
| 27 |
description: |
| 28 |
- The name of the resource group. |
| 29 |
required: true |
| 30 |
type: str |
| 31 |
location: |
| 32 |
description: |
| 33 |
- Location of the metric alert. |
| 34 |
- Metric alerts are usually 'Global'. |
| 35 |
- If unspecified will default to 'Global' on creation. |
| 36 |
required: false |
| 37 |
type: str |
| 38 |
description: |
| 39 |
description: |
| 40 |
- A description of this metric alert rule. |
| 41 |
type: str |
| 42 |
severity: |
| 43 |
description: |
| 44 |
- Severity 1-4 of the alert. |
| 45 |
- Required on creation. |
| 46 |
type: int |
| 47 |
enabled: |
| 48 |
description: |
| 49 |
- Indicates whether this metric alert is enabled. |
| 50 |
- If an metric alert is not enabled, then none of its receivers will receive communications. |
| 51 |
- Required on creation. |
| 52 |
type: bool |
| 53 |
scopes: |
| 54 |
description: |
| 55 |
- A list of resource IDs that will be used as prefixes. |
| 56 |
- The alert will only apply to Metric events with resource IDs that fall under one of these prefixes. |
| 57 |
- This list must include at least one item for creation. |
| 58 |
type: list |
| 59 |
elements: str |
| 60 |
evaluation_frequency: |
| 61 |
description: |
| 62 |
- How often the metric alert is evaluated represented in ISO 8601 duration format. |
| 63 |
- U(https://en.wikipedia.org/wiki/ISO_8601#Durations) |
| 64 |
- Required for creation. |
| 65 |
type: str |
| 66 |
window_size: |
| 67 |
description: |
| 68 |
- The period of time (in ISO 8601 duration format) that is used to monitor alert activity based on the threshold. |
| 69 |
- U(https://en.wikipedia.org/wiki/ISO_8601#Durations) |
| 70 |
- Required for creation. |
| 71 |
type: str |
| 72 |
target_resource_type: |
| 73 |
description: |
| 74 |
- The resource type of the target resource(s) on which the alert is created/updated. |
| 75 |
- Mandatory (for creation) if the scope contains a subscription, resource group, or more than one resource. |
| 76 |
type: str |
| 77 |
target_resource_region: |
| 78 |
description: |
| 79 |
- The region of the target resource(s) on which the alert is created/updated. |
| 80 |
- Mandatory (for creation) if the scope contains a subscription, resource group, or more than one resource. |
| 81 |
type: str |
| 82 |
criteria: |
| 83 |
description: |
| 84 |
- Defines the specific alert criteria information. |
| 85 |
- Required for creation. |
| 86 |
type: dict |
| 87 |
suboptions: |
| 88 |
extra_keys: |
| 89 |
description: |
| 90 |
- U(https://learn.microsoft.com/en-us/rest/api/monitor/metric-alerts/create-or-update?view=rest-monitor-2018-03-01&tabs=HTTP#request-body) |
| 91 |
- extra keys depends on the odata_type |
| 92 |
type: dict |
| 93 |
odata_type: |
| 94 |
description: |
| 95 |
- Specifies the type of the alert criteria. |
| 96 |
- Required on creation. |
| 97 |
type: str |
| 98 |
choices: |
| 99 |
- Microsoft.Azure.Monitor.SingleResourceMultipleMetricCriteria |
| 100 |
- Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria |
| 101 |
- Microsoft.Azure.Monitor.WebtestLocationAvailabilityCriteria |
| 102 |
auto_mitigate: |
| 103 |
description: |
| 104 |
- the flag that indicates whether the alert should be auto resolved or not. The default is true. |
| 105 |
type: bool |
| 106 |
actions: |
| 107 |
description: |
| 108 |
- The actions that will activate when the condition is met. |
| 109 |
- U(https://learn.microsoft.com/en-us/rest/api/monitor/metric-alerts/create-or-update?view=rest-monitor-2018-03-01&tabs=HTTP#metricalertaction) |
| 110 |
type: list |
| 111 |
elements: dict |
| 112 |
suboptions: |
| 113 |
action_group_id: |
| 114 |
description: |
| 115 |
- The resource ID of the Action Group. |
| 116 |
- Must be set when setting an action group. |
| 117 |
type: str |
| 118 |
webhook_properties: |
| 119 |
description: |
| 120 |
- The dictionary of custom properties to include with the post operation. These data are appended to the webhook payload. |
| 121 |
type: dict |
| 122 |
state: |
| 123 |
description: |
| 124 |
- State of the metric alert |
| 125 |
- Use C(present) for creating/updating a metric alert. |
| 126 |
- Use C(absent) for deleting a metric alert. |
| 127 |
default: present |
| 128 |
type: str |
| 129 |
choices: |
| 130 |
- present |
| 131 |
- absent |
| 132 |
extends_documentation_fragment: |
| 133 |
- azure.azcollection.azure |
| 134 |
- azure.azcollection.azure_tags |
| 135 |
|
| 136 |
author: |
| 137 |
- Klaas Demter (@Klaas-) |
| 138 |
''' |
| 139 |
|
| 140 |
EXAMPLES = ''' |
| 141 |
- name: Add a metric alert |
| 142 |
azure.azcollection.azure_rm_monitormetricalerts: |
| 143 |
state: present |
| 144 |
resource_group: myrg |
| 145 |
location: Global |
| 146 |
name: metric_alert_name |
| 147 |
actions: |
| 148 |
- action_group_id: subscriptions/<sub-id>/resourceGroups/myrg/providers/microsoft.insights/actionGroups/action_group_name |
| 149 |
auto_mitigate: true |
| 150 |
criteria: |
| 151 |
all_of: |
| 152 |
- criterion_type: StaticThresholdCriterion |
| 153 |
dimensions: |
| 154 |
- name: dataSourceURL |
| 155 |
operator: Include |
| 156 |
values: |
| 157 |
- '*' |
| 158 |
- name: healthStatus |
| 159 |
operator: Exclude |
| 160 |
values: |
| 161 |
- Healthy |
| 162 |
metric_name: BackupHealthEvent |
| 163 |
metric_namespace: Microsoft.RecoveryServices/vaults |
| 164 |
name: Metric1 |
| 165 |
operator: GreaterThan |
| 166 |
skip_metric_validation: false |
| 167 |
threshold: 0.0 |
| 168 |
time_aggregation: Count |
| 169 |
odata_type: Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria |
| 170 |
description: Alert on Backup Health Events |
| 171 |
enabled: true |
| 172 |
evaluation_frequency: PT1H |
| 173 |
scopes: |
| 174 |
- /subscriptions/<sub-id>/resourceGroups/myrg/providers/Microsoft.RecoveryServices/vaults/recovery_vault_name |
| 175 |
severity: 3 |
| 176 |
tags: |
| 177 |
TestTag1: TestValue1 |
| 178 |
target_resource_type: Microsoft.RecoveryServices/vaults |
| 179 |
window_size: P1D |
| 180 |
|
| 181 |
- name: Add tag to existing metric alert |
| 182 |
azure.azcollection.azure_rm_monitormetricalerts: |
| 183 |
state: present |
| 184 |
name: metric_alert_name |
| 185 |
resource_group: myrg |
| 186 |
append_tags: true |
| 187 |
tags: |
| 188 |
ThisIsAnAddedExampleTag: ExampleValue |
| 189 |
|
| 190 |
- name: Delete a metric alert |
| 191 |
azure.azcollection.azure_rm_monitormetricalerts: |
| 192 |
state: absent |
| 193 |
name: metric_alert_name |
| 194 |
resource_group: myrg |
| 195 |
''' |
| 196 |
|
| 197 |
RETURN = ''' |
| 198 |
metricalert: |
| 199 |
description: |
| 200 |
- Details of the metric alert |
| 201 |
- Is null on state==absent (metric alert does not exist or will be deleted) |
| 202 |
- Assumes you make legal changes in check mode |
| 203 |
type: dict |
| 204 |
returned: always |
| 205 |
sample: { |
| 206 |
"actions": [ |
| 207 |
{ |
| 208 |
"action_group_id": "subscriptions/<sub-id>/resourceGroups/myrg/providers/microsoft.insights/actionGroups/action_group_name" |
| 209 |
} |
| 210 |
], |
| 211 |
"auto_mitigate": true, |
| 212 |
"criteria": { |
| 213 |
"all_of": [ |
| 214 |
{ |
| 215 |
"criterion_type": "StaticThresholdCriterion", |
| 216 |
"dimensions": [ |
| 217 |
{ |
| 218 |
"name": "dataSourceURL", |
| 219 |
"operator": "Include", |
| 220 |
"values": [ |
| 221 |
"*" |
| 222 |
] |
| 223 |
}, |
| 224 |
{ |
| 225 |
"name": "healthStatus", |
| 226 |
"operator": "Exclude", |
| 227 |
"values": [ |
| 228 |
"Healthy" |
| 229 |
] |
| 230 |
} |
| 231 |
], |
| 232 |
"metric_name": "BackupHealthEvent", |
| 233 |
"metric_namespace": "Microsoft.RecoveryServices/vaults", |
| 234 |
"name": "Metric1", |
| 235 |
"operator": "GreaterThan", |
| 236 |
"skip_metric_validation": false, |
| 237 |
"threshold": 0.0, |
| 238 |
"time_aggregation": "Count" |
| 239 |
} |
| 240 |
], |
| 241 |
"odata_type": "Microsoft.Azure.Monitor.MultipleResourceMultipleMetricCriteria" |
| 242 |
}, |
| 243 |
"description": "Alert on Backup Health Events", |
| 244 |
"enabled": true, |
| 245 |
"evaluation_frequency": "PT1H", |
| 246 |
"id": "subscriptions/<sub-id>/resourceGroups/myrg/providers/Microsoft.Insights/metricAlerts/metric_alert_name", |
| 247 |
"location": "Global", |
| 248 |
"name": "metric_alert_name", |
| 249 |
"scopes": [ |
| 250 |
"/subscriptions/<sub-id>/resourceGroups/myrg/providers/Microsoft.RecoveryServices/vaults/recovery_vault_name" |
| 251 |
], |
| 252 |
"severity": 3, |
| 253 |
"tags": { |
| 254 |
"TestTag1": "TestValue1" |
| 255 |
}, |
| 256 |
"target_resource_type": "Microsoft.RecoveryServices/vaults", |
| 257 |
"type": "Microsoft.Insights/metricAlerts", |
| 258 |
"window_size": "P1D" |
| 259 |
} |
| 260 |
''' |
| 261 |
|
| 262 |
from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt |
| 263 |
|
| 264 |
try: |
| 265 |
from azure.core.exceptions import ResourceNotFoundError |
| 266 |
|
| 267 |
except ImportError: |
| 268 |
|
| 269 |
pass |
| 270 |
|
| 271 |
AZURE_OBJECT_CLASS = 'MetricAlert' |
| 272 |
|
| 273 |
actions_spec = dict( |
| 274 |
action_group_id=dict(type='str'), |
| 275 |
webhook_properties=dict(type='dict') |
| 276 |
) |
| 277 |
|
| 278 |
|
| 279 |
class AzureRMMonitorMetricAlert(AzureRMModuleBaseExt): |
| 280 |
"""Information class for an Azure RM metric alerts""" |
| 281 |
|
| 282 |
def __init__(self): |
| 283 |
|
| 284 |
self.module_arg_spec = dict( |
| 285 |
name=dict(type='str', required=True), |
| 286 |
resource_group=dict(type='str', required=True), |
| 287 |
location=dict(type='str'), |
| 288 |
description=dict(type='str'), |
| 289 |
severity=dict(type='int'), |
| 290 |
enabled=dict(type='bool'), |
| 291 |
scopes=dict(type='list', elements='str'), |
| 292 |
evaluation_frequency=dict(type='str'), |
| 293 |
window_size=dict(type='str'), |
| 294 |
target_resource_type=dict(type='str'), |
| 295 |
target_resource_region=dict(type='str'), |
| 296 |
|
| 297 |
|
| 298 |
criteria=dict(type='dict'), |
| 299 |
auto_mitigate=dict(type='bool'), |
| 300 |
actions=dict(type='list', elements='dict', options=actions_spec), |
| 301 |
state=dict(type='str', choices=['present', 'absent'], default='present') |
| 302 |
) |
| 303 |
|
| 304 |
self.name = None |
| 305 |
self.resource_group = None |
| 306 |
self.location = None |
| 307 |
self.tags = None |
| 308 |
self.description = None |
| 309 |
self.severity = None |
| 310 |
self.enabled = None |
| 311 |
self.scopes = None |
| 312 |
self.evaluation_frequency = None |
| 313 |
self.window_size = None |
| 314 |
self.target_resource_type = None |
| 315 |
self.target_resource_region = None |
| 316 |
self.criteria = None |
| 317 |
self.auto_mitigate = None |
| 318 |
self.actions = None |
| 319 |
self.state = None |
| 320 |
self.log_path = None |
| 321 |
self.log_mode = None |
| 322 |
|
| 323 |
self.results = dict( |
| 324 |
changed=False, |
| 325 |
metricalert=dict(), |
| 326 |
diff=dict( |
| 327 |
before=None, |
| 328 |
after=None |
| 329 |
) |
| 330 |
) |
| 331 |
|
| 332 |
super(AzureRMMonitorMetricAlert, self).__init__(derived_arg_spec=self.module_arg_spec, |
| 333 |
supports_check_mode=True, |
| 334 |
supports_tags=True) |
| 335 |
|
| 336 |
def exec_module(self, **kwargs): |
| 337 |
"""Main module execution method""" |
| 338 |
|
| 339 |
for key in list(self.module_arg_spec.keys()) + ['tags']: |
| 340 |
if hasattr(self, key): |
| 341 |
setattr(self, key, kwargs[key]) |
| 342 |
|
| 343 |
|
| 344 |
result = None |
| 345 |
result_compare = dict(compare=[]) |
| 346 |
before_dict = None |
| 347 |
|
| 348 |
|
| 349 |
before_dict = self.get_metric_alert() |
| 350 |
|
| 351 |
|
| 352 |
|
| 353 |
|
| 354 |
metric_alert_template = { |
| 355 |
"location": self.location, |
| 356 |
"description": self.description, |
| 357 |
"severity": self.severity, |
| 358 |
"enabled": self.enabled, |
| 359 |
"scopes": self.scopes, |
| 360 |
"evaluation_frequency": self.evaluation_frequency, |
| 361 |
"window_size": self.window_size, |
| 362 |
"target_resource_type": self.target_resource_type, |
| 363 |
"target_resource_region": self.target_resource_region, |
| 364 |
"criteria": self.criteria, |
| 365 |
"auto_mitigate": self.auto_mitigate, |
| 366 |
"actions": self.actions |
| 367 |
} |
| 368 |
|
| 369 |
metric_alert_input = {key: value for key, value in metric_alert_template.items() if value is not None} |
| 370 |
|
| 371 |
|
| 372 |
if self.state == 'present': |
| 373 |
if before_dict is None: |
| 374 |
|
| 375 |
|
| 376 |
if not self.location: |
| 377 |
metric_alert_input['location'] = 'Global' |
| 378 |
|
| 379 |
metric_alert_update = metric_alert_input |
| 380 |
|
| 381 |
if self.tags: |
| 382 |
metric_alert_update['tags'] = self.tags |
| 383 |
self.results['changed'] = True |
| 384 |
if self.check_mode: |
| 385 |
|
| 386 |
pass |
| 387 |
else: |
| 388 |
create_response = self.create_or_update(metric_alert_update) |
| 389 |
else: |
| 390 |
|
| 391 |
|
| 392 |
metric_alert_update = before_dict | metric_alert_input |
| 393 |
|
| 394 |
|
| 395 |
update_tags, update_tags_content = self.update_tags(before_dict.get('tags')) |
| 396 |
|
| 397 |
if update_tags or not self.default_compare({}, metric_alert_update, before_dict, '', result_compare): |
| 398 |
metric_alert_update['tags'] = update_tags_content |
| 399 |
|
| 400 |
self.results['changed'] = True |
| 401 |
if self.check_mode: |
| 402 |
|
| 403 |
pass |
| 404 |
else: |
| 405 |
create_response = self.create_or_update(metric_alert_update) |
| 406 |
|
| 407 |
if self.check_mode or not self.results['changed']: |
| 408 |
|
| 409 |
|
| 410 |
result = metric_alert_update |
| 411 |
else: |
| 412 |
|
| 413 |
result = create_response |
| 414 |
|
| 415 |
|
| 416 |
|
| 417 |
elif self.state == 'absent' and before_dict is not None: |
| 418 |
self.results['changed'] = True |
| 419 |
if self.check_mode: |
| 420 |
|
| 421 |
pass |
| 422 |
else: |
| 423 |
self.delete() |
| 424 |
|
| 425 |
self.results['diff']['before'] = before_dict |
| 426 |
self.results['diff']['after'] = result |
| 427 |
self.results['metricalert'] = result |
| 428 |
|
| 429 |
return self.results |
| 430 |
|
| 431 |
def get_metric_alert(self): |
| 432 |
''' |
| 433 |
Gets the properties of the specified metric alert. |
| 434 |
|
| 435 |
:return: List of metric alerts |
| 436 |
''' |
| 437 |
self.log("Checking if metric alert {0} in resource group {1} is present".format(self.name, |
| 438 |
self.resource_group)) |
| 439 |
|
| 440 |
result = None |
| 441 |
response = None |
| 442 |
|
| 443 |
try: |
| 444 |
response = self.monitor_management_client_metric_alerts.metric_alerts.get(rule_name=self.name, |
| 445 |
resource_group_name=self.resource_group) |
| 446 |
except ResourceNotFoundError as ex: |
| 447 |
self.log("Could not find metric alert {0} in resource group {1}".format(self.name, self.resource_group)) |
| 448 |
if response: |
| 449 |
result = self.serialize_obj(response, AZURE_OBJECT_CLASS) |
| 450 |
|
| 451 |
return result |
| 452 |
|
| 453 |
def create_or_update(self, metric_alert_update): |
| 454 |
result = None |
| 455 |
response = None |
| 456 |
metric_alerts = self.monitor_management_client_metric_alerts.metric_alerts |
| 457 |
try: |
| 458 |
response = metric_alerts.create_or_update(resource_group_name=self.resource_group, |
| 459 |
rule_name=self.name, |
| 460 |
parameters=metric_alert_update, |
| 461 |
logging_enable=False) |
| 462 |
except Exception as ex: |
| 463 |
self.fail("Error creating or update metric alert {0} in resource group {1}: {2}".format(self.name, self.resource_group, str(ex))) |
| 464 |
|
| 465 |
if response: |
| 466 |
result = self.serialize_obj(response, AZURE_OBJECT_CLASS) |
| 467 |
|
| 468 |
return result |
| 469 |
|
| 470 |
def delete(self): |
| 471 |
response = None |
| 472 |
try: |
| 473 |
response = self.monitor_management_client_metric_alerts.metric_alerts.delete(resource_group_name=self.resource_group, |
| 474 |
rule_name=self.name) |
| 475 |
except Exception as ex: |
| 476 |
self.fail("Error deleting metric alert {0} in resource group {1}: {2}".format(self.name, self.resource_group, str(ex))) |
| 477 |
|
| 478 |
return response |
| 479 |
|
| 480 |
|
| 481 |
def main(): |
| 482 |
"""Main execution""" |
| 483 |
AzureRMMonitorMetricAlert() |
| 484 |
|
| 485 |
|
| 486 |
if __name__ == '__main__': |
| 487 |
main() |