Debian Codegraph @

ansible_collections/azure/azcollection/plugins/modules/azure_rm_monitoractivitylogalerts.py

raw symbols SCIP
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2025 Klaas Demter (@Klaas-)
4 #
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = '''
11 ---
12 module: azure_rm_monitoractivitylogalerts
13 version_added: "3.7.0"
14 short_description: Create, update and delete Activity Log Alerts.
15 description:
16 - Create, update and delete Activity Log Alerts.
17 - >-
18 U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2020_10_01.aio.operations.activitylogalertsoperations?view=azure-python#azure-mgmt-monitor-v2020-10-01-aio-operations-activitylogalertsoperations-create-or-update)
19 - U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2020_10_01.models.activitylogalertresource?view=azure-python)
20
21 options:
22 name:
23 description:
24 - The name of the activity log alert you're creating, updating or deleting.
25 required: true
26 type: str
27 resource_group:
28 description:
29 - The name of the resource group
30 required: true
31 type: str
32 location:
33 description:
34 - Location of the activity log alert.
35 - Should be optional, but is not optional on creation.
36 - U(https://github.com/Azure/azure-rest-api-specs/issues/35342)
37 - Activity log alerts are usually 'Global'. On creation module will default to 'Global' if unspecified.
38 required: false
39 type: str
40 scopes:
41 description:
42 - A list of resource IDs that will be used as prefixes.
43 - The alert will only apply to Activity Log events with resource IDs that fall under one of these prefixes.
44 - This list must include at least one item for creation.
45 type: list
46 elements: str
47 condition:
48 description:
49 - The condition that will cause this alert to activate.
50 - >-
51 U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2020_10_01.models.alertruleallofcondition?view=azure-python)
52 type: dict
53 suboptions:
54 all_of:
55 description:
56 - The list of Activity Log Alert rule conditions.
57 - >-
58 U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2020_10_01.models.alertruleanyoforleafcondition?view=azure-python)
59 type: list
60 elements: dict
61 suboptions:
62 field:
63 description:
64 - The name of the Activity Log event's field that this condition will examine.
65 - The possible values for this field are (case-insensitive) resourceId, category, caller, level,
66 operationName, resourceGroup, resourceProvider, status, subStatus, resourceType
67 or anything beginning with properties.
68 type: str
69 equals:
70 description:
71 - The value of the events field will be compared to this value (case-insensitive) to determine if the condition is met.
72 type: str
73 contains_any:
74 description:
75 - The value of the events field will be compared to the values in this
76 array (case-insensitive) to determine if the condition is met.
77 type: list
78 elements: str
79 any_of:
80 description:
81 - An Activity Log Alert rule condition that is met when at least one of its member leaf conditions are met.
82 - >-
83 U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2020_10_01.models.alertruleleafcondition?view=azure-python)
84 type: list
85 elements: dict
86 suboptions:
87 field:
88 description:
89 - The name of the Activity Log events field that this condition will examine. The possible values for this field are
90 (case-insensitive) resourceId, category, caller, level, operationName, resourceGroup, resourceProvider,
91 status, subStatus, resourceType, or anything beginning with properties.
92 type: str
93 equals:
94 description:
95 - The value of the event's field will be compared to this value (case-insensitive) to determine if the condition is met.
96 type: str
97 contains_any:
98 description:
99 - The value of the event's field will be compared to the values in this array
100 (case-insensitive) to determine if the condition is met.
101 type: list
102 elements: str
103 actions:
104 description:
105 - The actions that will activate when the condition is met.
106 - U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2020_10_01.models.actionlist?view=azure-python)
107 type: dict
108 suboptions:
109 action_groups:
110 description:
111 - The list of the Action Groups.
112 - U(https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2020_10_01.models.actiongroup?view=azure-python)
113 type: list
114 elements: dict
115 suboptions:
116 action_group_id:
117 description:
118 - The resource ID of the Action Group.
119 - Must be set when setting an action group.
120 type: str
121 webhook_properties:
122 description:
123 - the dictionary of custom properties to include with the post operation. These data are appended to the webhook payload.
124 type: dict
125 enabled:
126 description:
127 - Indicates whether this activity log alert is enabled.
128 - If an activity log alert is not enabled, then none of its receivers will receive communications.
129 - Server side default false -- should be true.
130 - U(https://github.com/Azure/azure-rest-api-specs/issues/35343)
131 type: bool
132 description:
133 description:
134 - A description of this Activity Log Alert rule.
135 type: str
136 state:
137 description:
138 - State of the activity log alert.
139 - Use C(present) for creating/updating a activity log alert.
140 - Use C(absent) for deleting a activity log alert.
141 default: present
142 type: str
143 choices:
144 - present
145 - absent
146 extends_documentation_fragment:
147 - azure.azcollection.azure
148 - azure.azcollection.azure_tags
149
150 author:
151 - Klaas Demter (@Klaas-)
152 '''
153
154 EXAMPLES = '''
155 - name: Add a activity log alert
156 azure.azcollection.azure_rm_monitoractivitylogalerts:
157 state: present
158 resource_group: resource_group_name
159 location: global
160 name: activity_log_alert_resource_health_example
161 scopes:
162 - /subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/resource_group_name
163 condition:
164 all_of:
165 - equals: ResourceHealth
166 field: category
167 - any_of:
168 - equals: Unknown
169 field: properties.currentHealthStatus
170 - equals: Unavailable
171 field: properties.currentHealthStatus
172 - equals: Degraded
173 field: properties.currentHealthStatus
174 - any_of:
175 - equals: Unknown
176 field: properties.previousHealthStatus
177 - equals: Unavailable
178 field: properties.previousHealthStatus
179 - equals: Degraded
180 field: properties.previousHealthStatus
181 - equals: Available
182 field: properties.previousHealthStatus
183 - any_of:
184 - equals: PlatformInitiated
185 field: properties.cause
186 actions:
187 action_groups:
188 - action_group_id: "/subscriptions/<sub-id>/resourceGroups/resource_group_name/providers/microsoft.insights/actionGroups/action_group_name"
189
190 - name: Add tag to existing activity log alert
191 azure.azcollection.azure_rm_monitoractivitylogalerts:
192 state: present
193 name: activity_log_alert_name
194 resource_group: resource_group_name
195 append_tags: true
196 tags:
197 ThisIsAnAddedExampleTag: ExampleValue
198
199 - name: Delete a activity log alert
200 azure.azcollection.azure_rm_monitoractivitylogalerts:
201 state: absent
202 name: activity_log_alert_name
203 resource_group: resource_group_name
204 '''
205
206 RETURN = '''
207 activitylogalert:
208 description:
209 - Details of the activity log alert
210 - Is null on state==absent (activity log alert does not exist or will be deleted)
211 - Assumes you make legal changes in check mode
212 type: dict
213 returned: always
214 sample: {
215 "actions": {
216 "action_groups": [
217 {
218 "action_group_id": \
219 "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/resource_group_name/providers/microsoft.insights/actionGroups/action_group_name"
220 }
221 ]
222 },
223 "condition": {
224 "all_of": [
225 {
226 "equals": "ResourceHealth",
227 "field": "category"
228 },
229 {
230 "any_of": [
231 {
232 "equals": "Unknown",
233 "field": "properties.currentHealthStatus"
234 },
235 {
236 "equals": "Unavailable",
237 "field": "properties.currentHealthStatus"
238 },
239 {
240 "equals": "Degraded",
241 "field": "properties.currentHealthStatus"
242 }
243 ]
244 },
245 {
246 "any_of": [
247 {
248 "equals": "Unknown",
249 "field": "properties.previousHealthStatus"
250 },
251 {
252 "equals": "Unavailable",
253 "field": "properties.previousHealthStatus"
254 },
255 {
256 "equals": "Degraded",
257 "field": "properties.previousHealthStatus"
258 },
259 {
260 "equals": "Available",
261 "field": "properties.previousHealthStatus"
262 }
263 ]
264 },
265 {
266 "any_of": [
267 {
268 "equals": "PlatformInitiated",
269 "field": "properties.cause"
270 }
271 ]
272 }
273 ]
274 },
275 "enabled": false,
276 "id": \
277 "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/resource_group_name/providers/Microsoft.Insights/activityLogAlerts/activity_log_alert_name",
278 "location": "global",
279 "name": "activity_log_alert_name",
280 "scopes": [
281 "/subscriptions/xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/resource_group_name"
282 ],
283 "tags": {},
284 "type": "Microsoft.Insights/ActivityLogAlerts"
285 }
286 '''
287
288 from ansible_collections.azure.azcollection.plugins.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
289
290
291 try:
292 from azure.core.exceptions import ResourceNotFoundError
293
294 except ImportError:
295 # This is handled in azure_rm_common
296 pass
297
298 AZURE_OBJECT_CLASS = 'ActivityLogAlert'
299
300 any_of_all_of_condition_spec = dict(
301 field=dict(type='str'),
302 equals=dict(type='str'),
303 contains_any=dict(type='list', elements='str')
304 )
305
306 all_of_condition_spec = dict(
307 field=dict(type='str'),
308 equals=dict(type='str'),
309 contains_any=dict(type='list', elements='str'),
310 any_of=dict(type='list', elements='dict', options=any_of_all_of_condition_spec)
311 )
312 condition_spec = dict(
313 all_of=dict(type='list', elements='dict', options=all_of_condition_spec)
314 )
315
316 action_groups_actions_spec = dict(
317 action_group_id=dict(type='str'),
318 webhook_properties=dict(type='dict')
319 )
320
321 actions_spec = dict(
322 action_groups=dict(type='list', elements='dict', options=action_groups_actions_spec)
323 )
324
325
326 class AzureRMMonitorActivityLogAlert(AzureRMModuleBaseExt):
327 """Information class for an Azure RM Activity Log Alerts"""
328
329 def __init__(self):
330 # https://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2020_10_01.models.activitylogalertresource?view=azure-python
331 self.module_arg_spec = dict(
332 name=dict(type='str', required=True),
333 resource_group=dict(type='str', required=True),
334 location=dict(type='str'),
335 scopes=dict(type='list', elements='str'),
336 condition=dict(type='dict', options=condition_spec),
337 actions=dict(type='dict', options=actions_spec),
338 enabled=dict(type='bool'),
339 description=dict(type='str'),
340 state=dict(type='str', choices=['present', 'absent'], default='present')
341 )
342
343 self.name = None
344 self.resource_group = None
345 self.location = None
346 self.tags = None
347 self.scopes = None
348 self.condition = None
349 self.actions = None
350 self.enabled = None
351 self.description = None
352 self.state = None
353 self.log_path = None
354 self.log_mode = None
355
356 self.results = dict(
357 changed=False,
358 activitylogalert=dict(),
359 diff=dict(
360 before=None,
361 after=None
362 )
363 )
364
365 super(AzureRMMonitorActivityLogAlert, self).__init__(derived_arg_spec=self.module_arg_spec,
366 supports_check_mode=True,
367 supports_tags=True)
368
369 def exec_module(self, **kwargs):
370 """Main module execution method"""
371
372 for key in list(self.module_arg_spec.keys()) + ['tags']:
373 if hasattr(self, key):
374 setattr(self, key, kwargs[key])
375
376 # Defaults for variables
377 result = None
378 result_compare = dict(compare=[])
379 before_dict = None
380
381 # Get current activity log alert if it exists
382 before_dict = self.get_activity_log_alert()
383
384 # Create dict from input, without None values
385 # hhttps://learn.microsoft.com/en-us/python/api/azure-mgmt-monitor/azure.mgmt.monitor.v2020_10_01.models.activitylogalertresource?view=azure-python
386 activity_log_alert_template = {
387 "location": self.location,
388 "scopes": self.scopes,
389 "condition": self.condition,
390 "actions": self.actions,
391 "enabled": self.enabled,
392 "description": self.description
393 }
394 # Filter out all None values
395 activity_log_alert_input = {key: value for key, value in activity_log_alert_template.items() if value is not None}
396
397 # Create/Update if state==present
398 if self.state == 'present':
399 if before_dict is None:
400 # activity log alert does not exist, create
401 # On creation default to location of resource group unless otherwise noted in input variables
402 if not self.location:
403 activity_log_alert_input['location'] = 'Global'
404 # On creation input == what we send to api
405 activity_log_alert_update = activity_log_alert_input
406 # Needs to be extended by tags if set
407 if self.tags:
408 activity_log_alert_update['tags'] = self.tags
409 self.results['changed'] = True
410 if self.check_mode:
411 # Check mode, skipping actual creation
412 pass
413 else:
414 create_response = self.create_or_update(activity_log_alert_update)
415 else:
416 # activity log alert already exists, updating it
417 # Dict for update is the union of existing object overwritten by input data
418 activity_log_alert_update = before_dict | activity_log_alert_input
419
420 # Enhanced with tags (special behaviour because of append_tags possibility)
421 update_tags, update_tags_content = self.update_tags(before_dict.get('tags'))
422 # Check if we need to update the activity log alert
423 if update_tags or not self.default_compare({}, activity_log_alert_update, before_dict, '', result_compare):
424 activity_log_alert_update['tags'] = update_tags_content
425 # Need to create/update the activity log alert; changed -> True
426 self.results['changed'] = True
427 if self.check_mode:
428 # Check mode, skipping actual creation
429 pass
430 else:
431 create_response = self.create_or_update(activity_log_alert_update)
432
433 if self.check_mode or not self.results['changed']:
434 # When object was not updated or when running in check mode
435 # assume activity_log_alert_update is resulting object
436 result = activity_log_alert_update
437 else:
438 # otherwise take resulting new object from response of create call
439 result = create_response
440
441 # Delete activity log alert if state is absent and it exists
442 # if it doesn't exist, it's already absent
443 elif self.state == 'absent' and before_dict is not None:
444 self.results['changed'] = True
445 if self.check_mode:
446 # do not delete in check mode
447 pass
448 else:
449 self.delete()
450
451 self.results['diff']['before'] = before_dict
452 self.results['diff']['after'] = result
453 self.results['activitylogalert'] = result
454
455 return self.results
456
457 def get_activity_log_alert(self):
458 '''
459 Gets the properties of the specified activity log alert.
460
461 :return: List of Activity Log Alerts
462 '''
463 self.log("Checking if activity log alert {0} in resource group {1} is present".format(self.name,
464 self.resource_group))
465
466 result = None
467 response = None
468
469 try:
470 response = self.monitor_management_client_activity_log_alerts.activity_log_alerts.get(activity_log_alert_name=self.name,
471 resource_group_name=self.resource_group)
472 except ResourceNotFoundError as ex:
473 self.log("Could not find activity log alert {0} in resource group {1}".format(self.name, self.resource_group))
474 if response:
475 result = self.serialize_obj(response, AZURE_OBJECT_CLASS)
476
477 return result
478
479 def create_or_update(self, activity_log_alert_update):
480 result = None
481 response = None
482 activity_log_alerts = self.monitor_management_client_activity_log_alerts.activity_log_alerts
483 try:
484 response = activity_log_alerts.create_or_update(resource_group_name=self.resource_group,
485 activity_log_alert_name=self.name,
486 activity_log_alert_rule=activity_log_alert_update,
487 logging_enable=False)
488 except Exception as ex:
489 self.fail("Error creating or update activity log alert {0} in resource group {1}: {2}".format(self.name, self.resource_group, str(ex)))
490
491 if response:
492 result = self.serialize_obj(response, AZURE_OBJECT_CLASS)
493
494 return result
495
496 def delete(self):
497 response = None
498 try:
499 response = self.monitor_management_client_activity_log_alerts.activity_log_alerts.delete(resource_group_name=self.resource_group,
500 activity_log_alert_name=self.name)
501 except Exception as ex:
502 self.fail("Error deleting activity log alert {0} in resource group {1}: {2}".format(self.name, self.resource_group, str(ex)))
503
504 return response
505
506
507 def main():
508 """Main execution"""
509 AzureRMMonitorActivityLogAlert()
510
511
512 if __name__ == '__main__':
513 main()