Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_alert_policies.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.3.0
7 # Copyright (C) 2023-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12
13 from __future__ import (absolute_import, division, print_function)
14 __metaclass__ = type
15
16 DOCUMENTATION = r'''
17 ---
18 module: ome_alert_policies
19 short_description: Manage OME alert policies.
20 version_added: "8.3.0"
21 description: This module allows you to create, modify, or delete alert policies on OpenManage Enterprise or OpenManage Enterprise Modular.
22 extends_documentation_fragment:
23 - dellemc.openmanage.ome_auth_options
24 options:
25 name:
26 description:
27 - Name of an alert policy or a list of alert policies.
28 - More than one policy name is applicable when I(state) is C(absent) and I(state) is C(present) with only I(enable) provided.
29 type: list
30 elements: str
31 required: true
32 state:
33 description:
34 - C(present) allows you to create an alert policy or update if the policy name already exists.
35 - C(absent) allows you to delete an alert policy.
36 default: present
37 choices: [present, absent]
38 type: str
39 enable:
40 description:
41 - C(true) allows you to enable an alert policy.
42 - C(false) allows you to disable an alert policy.
43 - This is applicable only when I(state) is C(present).
44 type: bool
45 new_name:
46 description:
47 - New name for the alert policy.
48 - This is applicable only when I(state) is C(present), and an alert policy exists.
49 type: str
50 description:
51 description:
52 - Description for the alert policy.
53 - This is applicable only when I(state) is C(present)
54 type: str
55 device_service_tag:
56 description:
57 - List of device service tags on which the alert policy will be applicable.
58 - This option is mutually exclusive with I(device_group), I(specific_undiscovered_devices), I(any_undiscovered_devices) and I(all_devices).
59 - This is applicable only when I(state) is C(present)
60 type: list
61 elements: str
62 device_group:
63 description:
64 - List of device group names on which the alert policy is applicable.
65 - This option is mutually exclusive with I(device_service_tag), I(specific_undiscovered_devices), I(any_undiscovered_devices) and I(all_devices) .
66 - This is applicable only when I(state) is C(present)
67 type: list
68 elements: str
69 specific_undiscovered_devices:
70 description:
71 - List of undiscovered IPs, hostnames, or range of IPs of devices on which the alert policy is applicable.
72 - This option is mutually exclusive with I(device_service_tag), I(device_group), I(any_undiscovered_devices) and I(all_devices) .
73 - This is applicable only when I(state) is C(present)
74 - "Examples of valid IP range format:"
75 - " 10.35.0.0"
76 - " 10.36.0.0-10.36.0.255"
77 - " 10.37.0.0/24"
78 - " 2607:f2b1:f083:135::5500/118"
79 - " 2607:f2b1:f083:135::a500-2607:f2b1:f083:135::a600"
80 - " hostname.domain.com"
81 - "Examples of invalid IP range format:"
82 - " 10.35.0.*"
83 - " 10.36.0.0-255"
84 - " 10.35.0.0/255.255.255.0"
85 - These values will not be validated.
86 type: list
87 elements: str
88 any_undiscovered_devices:
89 description:
90 - This option indicates whether the alert policy is applicable to any undiscovered devices or not.
91 - This option is mutually exclusive with I(device_service_tag), I(specific_undiscovered_devices), I(device_group) and I(all_devices).
92 - This is applicable only when I(state) is C(present).
93 type: bool
94 all_devices:
95 description:
96 - This option indicates whether the alert policy is applicable to all the discovered and undiscovered devices or not.
97 - This option is mutually exclusive with I(device_service_tag), I(specific_undiscovered_devices), I(any_undiscovered_devices) and I(device_group).
98 - This is applicable only when I(state) is C(present).
99 type: bool
100 category:
101 description:
102 - Category of the alerts received.
103 - This is mutually exclusive with the I(message_ids), I(message_file).
104 - This is fetched from the M(dellemc.openmanage.ome_alert_policies_category_info).
105 - This is applicable only when I(state) is C(present).
106 type: list
107 elements: dict
108 suboptions:
109 catalog_name:
110 description: Name of the catalog.
111 type: str
112 required: true
113 catalog_category:
114 description: Category of the catalog.
115 type: list
116 elements: dict
117 suboptions:
118 category_name:
119 description: Name of the category.
120 type: str
121 sub_category_names:
122 description: List of sub-categories.
123 type: list
124 elements: str
125 message_ids:
126 description:
127 - List of Message ids
128 - This is mutually exclusive with the I(category), I(message_file)
129 - This is applicable only when I(state) is C(present)
130 - This is fetched from the M(dellemc.openmanage.ome_alert_policies_message_id_info).
131 type: list
132 elements: str
133 message_file:
134 description:
135 - Local path of a CSV formatted file with message IDs
136 - This is mutually exclusive with the I(category), I(message_ids)
137 - This is applicable only when I(state) is C(present)
138 - This is fetched from the M(dellemc.openmanage.ome_alert_policies_message_id_info).
139 type: path
140 date_and_time:
141 description:
142 - Specifies the schedule for when the alert policy is applicable.
143 - I(date_and_time) is mandatory for creating a policy and optional when updating a policy.
144 - This is applicable only when I(state) is C(present).
145 type: dict
146 suboptions:
147 date_from:
148 description:
149 - "Start date in the format YYYY-MM-DD."
150 - This parameter to be provided in quotes.
151 type: str
152 required: true
153 date_to:
154 description:
155 - "End date in the format YYYY-MM-DD."
156 - This parameter to be provided in quotes.
157 type: str
158 time_from:
159 description:
160 - "Interval start time in the format HH:MM"
161 - This parameter to be provided in quotes.
162 - This is mandatory when I(time_interval) is C(true).
163 type: str
164 time_to:
165 description:
166 - "Interval end time in the format HH:MM"
167 - This parameter to be provided in quotes.
168 - This is mandatory when I(time_interval) is C(true)
169 type: str
170 days:
171 description: Required days of the week on which alert policy operation must be scheduled.
172 type: list
173 elements: str
174 choices: [monday, tuesday, wednesday, thursday, friday, saturday, sunday]
175 time_interval:
176 description: Enable the time interval for which alert policy must be scheduled.
177 type: bool
178 severity:
179 description:
180 - Severity of the alert policy.
181 - This is mandatory for creating a policy and optional for updating a policy.
182 - This is applicable only when I(state) is C(present).
183 type: list
184 elements: str
185 choices: [all, unknown, info, normal, warning, critical]
186 actions:
187 description:
188 - Actions to be triggered for the alert policy.
189 - This parameter is case-sensitive.
190 - This is mandatory for creating a policy and optional for updating a policy.
191 - This is applicable only when I(state) is C(present)
192 type: list
193 elements: dict
194 suboptions:
195 action_name:
196 description:
197 - Name of the action.
198 - This is fetched from the M(dellemc.openmanage.ome_alert_policies_action_info).
199 - This is mandatory for creating a policy and optional for updating a policy.
200 - This parameter is case-sensitive.
201 type: str
202 required: true
203 parameters:
204 description:
205 - Predefined parameters required to set for I(action_name).
206 type: list
207 elements: dict
208 default: []
209 suboptions:
210 name:
211 description:
212 - Name of the predefined parameter.
213 - This is fetched from the M(dellemc.openmanage.ome_alert_policies_action_info).
214 type: str
215 value:
216 description:
217 - Value of the predefined parameter.
218 - These values will not be validated.
219 type: str
220 requirements:
221 - "python >= 3.9.6"
222 author: "Jagadeesh N V(@jagadeeshnv)"
223 notes:
224 - Run this module from a system that has direct access to Dell OpenManage Enterprise
225 or OpenManage Enterprise Modular.
226 - This module supports IPv4 and IPv6 addresses.
227 - This module supports C(check_mode).
228 '''
229
230 EXAMPLES = r'''
231 ---
232 - name: "Create an alert policy"
233 dellemc.openamanage.ome_alert_policies:
234 hostname: "192.168.0.1"
235 username: "username"
236 password: "password"
237 ca_path: "/path/to/ca_cert.pem"
238 name: "Alert Policy One"
239 device_service_tag:
240 - ABCD123
241 - SVC7845
242 category:
243 - catalog_name: Application
244 catalog_category:
245 - category_name: Audit
246 sub_category_names:
247 - Generic
248 - Devices
249 - catalog_name: iDRAC
250 catalog_category:
251 - category_name: Audit
252 sub_category_names:
253 - BIOS Management
254 - iDRAC Service Module
255 date_and_time:
256 date_from: "2023-10-10"
257 date_to: "2023-10-11"
258 time_from: "11:00"
259 time_to: "12:00"
260 severity:
261 - unknown
262 - critical
263 actions:
264 - action_name: Trap
265 parameters:
266 - name: "192.1.2.3:162"
267 value: true
268 - name: "traphostname.domain.com:162"
269 value: true
270 tags: create_alert_policy
271
272 - name: "Update an alert Policy"
273 dellemc.openamanage.ome_alert_policies:
274 hostname: "192.168.0.1"
275 username: "username"
276 password: "password"
277 ca_path: "/path/to/ca_cert.pem"
278 new_name: "Update Policy Name"
279 device_group: "Group Name"
280 message_ids:
281 - AMP400
282 - CTL201
283 - BIOS101
284 date_and_time:
285 date_from: "2023-10-10"
286 date_to: "2023-10-11"
287 time_from: "11:00"
288 time_to: "12:00"
289 time_interval: true
290 actions:
291 - action_name: Trap
292 parameters:
293 - name: "192.1.2.3:162"
294 value: true
295 tags: update_alert_policy
296
297 - name: "Enable an alert policy"
298 dellemc.openamanage.ome_alert_policies:
299 hostname: "192.168.0.1"
300 username: "username"
301 password: "password"
302 ca_path: "/path/to/ca_cert.pem"
303 name: "Policy Name"
304 enable: true
305 tags: enable_alert_policy
306
307 - name: "Disable multiple alert policies"
308 dellemc.openamanage.ome_alert_policies:
309 hostname: "192.168.0.1"
310 username: "username"
311 password: "password"
312 ca_path: "/path/to/ca_cert.pem"
313 name:
314 - "Policy Name 1"
315 - "Policy Name 2"
316 enable: false
317 tags: disable_alert_policy
318
319 - name: "Delete an alert policy"
320 dellemc.openamanage.ome_alert_policies:
321 hostname: "192.168.0.1"
322 username: "username"
323 password: "password"
324 ca_path: "/path/to/ca_cert.pem"
325 name:
326 - "Policy Name"
327 state: absent
328 tags: delete_alert_policy
329 '''
330
331 RETURN = r'''
332 ---
333 msg:
334 type: str
335 description: Status of the alert policies operation.
336 returned: always
337 sample: "Successfully created the alert policy."
338 status:
339 type: dict
340 description: The policy which was created or modified.
341 returned: when state is present
342 sample: {
343 "Id": 12345,
344 "Name": "Policy",
345 "Description": "Details of the Policy",
346 "Enabled": true,
347 "DefaultPolicy": false,
348 "Editable": true,
349 "Visible": true,
350 "PolicyData": {
351 "Catalogs": [
352 {
353 "CatalogName": "iDRAC",
354 "Categories": [
355 4
356 ],
357 "SubCategories": [
358 41
359 ]
360 },
361 {
362 "CatalogName": "Application",
363 "Categories": [
364 0
365 ],
366 "SubCategories": [
367 0
368 ]
369 }
370 ],
371 "Severities": [
372 16,
373 1,
374 2,
375 4,
376 8
377 ],
378 "Devices": [
379 10086,
380 10088
381 ],
382 "DeviceTypes": [
383 1000,
384 2000
385 ],
386 "Groups": [],
387 "Schedule": {
388 "StartTime": "2023-06-06 15:02:46.000",
389 "EndTime": "2023-06-06 18:02:46.000",
390 "CronString": "* * * ? * * *"
391 },
392 "Actions": [
393 {
394 "Id": 8,
395 "Name": "Email",
396 "ParameterDetails": [
397 {
398 "Id": 1,
399 "Name": "subject",
400 "Value": "Device Name: $name, Device IP Address: $ip, Severity: $severity",
401 "Type": "string",
402 "TypeParams": [
403 {
404 "Name": "maxLength",
405 "Value": "255"
406 }
407 ]
408 },
409 {
410 "Id": 1,
411 "Name": "to",
412 "Value": "[email protected]",
413 "Type": "string",
414 "TypeParams": [
415 {
416 "Name": "maxLength",
417 "Value": "255"
418 }
419 ]
420 },
421 {
422 "Id": 1,
423 "Name": "from",
424 "Value": "[email protected]",
425 "Type": "string",
426 "TypeParams": [
427 {
428 "Name": "maxLength",
429 "Value": "255"
430 }
431 ]
432 },
433 {
434 "Id": 1,
435 "Name": "message",
436 "Value": "Event occurred for Device Name: $name, Device IP Address: $ip",
437 "Type": "string",
438 "TypeParams": [
439 {
440 "Name": "maxLength",
441 "Value": "255"
442 }
443 ]
444 }
445 ]
446 }
447 ],
448 "UndiscoveredTargets": [],
449 "State": true,
450 "Owner": 10069
451 }
452 }
453 error_info:
454 description: Details of the HTTP Error.
455 returned: on HTTP error
456 type: dict
457 sample: {
458 "error": {
459 "code": "Base.1.0.GeneralError",
460 "message": "A general error has occurred. See ExtendedInfo for more information.",
461 "@Message.ExtendedInfo": [
462 {
463 "MessageId": "CMON7011",
464 "RelatedProperties": [],
465 "Message": "Unable to create or modify the alert policy because an invalid value [To Email] is entered for the action Email.",
466 "MessageArgs": [
467 "[To Email]",
468 "Email"
469 ],
470 "Severity": "Warning",
471 "Resolution": "Enter a valid value for the action identified in the message and retry the operation."
472 }
473 ]
474 }
475 }
476 '''
477
478 import csv
479 import os
480 import json
481 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import get_all_data_with_pagination, strip_substr_dict
482 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
483 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
484 from ansible.module_utils.urls import ConnectionError, SSLValidationError
485 from ansible.module_utils.common.dict_transformations import recursive_diff
486 from datetime import datetime
487
488
489 POLICIES_URI = "AlertService/AlertPolicies"
490 MESSAGES_URI = "AlertService/AlertMessageDefinitions"
491 ACTIONS_URI = "AlertService/AlertActionTemplates"
492 SEVERITY_URI = "AlertService/AlertSeverities"
493 DEVICES_URI = "DeviceService/Devices"
494 GROUPS_URI = "GroupService/Groups"
495 REMOVE_URI = "AlertService/Actions/AlertService.RemoveAlertPolicies"
496 ENABLE_URI = "AlertService/Actions/AlertService.EnableAlertPolicies"
497 DISABLE_URI = "AlertService/Actions/AlertService.DisableAlertPolicies"
498 CATEGORY_URI = "AlertService/AlertCategories"
499 SUCCESS_MSG = "Successfully {0}d the alert policy."
500 NO_CHANGES_MSG = "No changes found to be applied."
501 CHANGES_MSG = "Changes found to be applied."
502 INVALID_TIME = "The specified {0} date or {0} time `{1}` to schedule the policy is not valid. Enter a valid date and time."
503 END_START_TIME = "The end time `{0}` to schedule the policy must be greater than the start time `{1}`."
504 CATEGORY_FETCH_FAILED = "Unable to retrieve the category details from OpenManage Enterprise."
505 INVALID_TARGETS = "Specify target devices to apply the alert policy."
506 INVALID_CATEGORY_MESSAGE = "Specify categories or message to create the alert policy."
507 INVALID_SCHEDULE = "Specify a date and time to schedule the alert policy."
508 INVALID_ACTIONS = "Specify alert actions for the alert policy."
509 INVALID_SEVERITY = "Specify the severity to create the alert policy."
510 MULTIPLE_POLICIES = "Unable to update the alert policies because the number of alert policies entered are more than " \
511 "one. The update policy operation supports only one alert policy at a time."
512 DISABLED_ACTION = "Action {0} is disabled. Enable it before applying to the alert policy."
513 ACTION_INVALID_PARAM = "The Action {0} attribute contains invalid parameter name {1}. The valid values are {2}."
514 ACTION_INVALID_VALUE = "The Action {0} attribute contains invalid value for {1} for parameter name {2}. The valid " \
515 "values are {3}."
516 ACTION_DIS_EXIST = "Action {0} does not exist."
517 SUBCAT_IN_CATEGORY = "The subcategory {0} does not exist in the category {1}."
518 CATEGORY_IN_CATALOG = "The category {0} does not exist in the catalog {1}."
519 OME_DATA_MSG = "The {0} with the following {1} do not exist: {2}."
520 CATALOG_DIS_EXIST = "The catalog {0} does not exist."
521 CSV_PATH = "The message file {0} does not exist."
522 DEFAULT_POLICY_DELETE = "The following default policies cannot be deleted: {0}."
523 POLICY_ENABLE_MISSING = "Unable to {0} the alert policies {1} because the policy names are invalid. Enter the valid " \
524 "alert policy names and retry the operation."
525 NO_POLICY_EXIST = "The alert policy does not exist."
526 SEPARATOR = ", "
527
528
529 def get_alert_policies(rest_obj, name_list):
530 report = get_all_data_with_pagination(rest_obj, POLICIES_URI)
531 all_policies = report.get("report_list", [])
532 policies = []
533 nameset = set(name_list)
534 for policy in all_policies:
535 if policy.get("Name") in nameset:
536 policies.append(policy)
537 return policies
538
539
540 def get_items_to_remove(filter_param, return_param_tuple, return_dict, all_items, mset):
541 collector = set()
542 for dev in all_items:
543 k = dev.get(filter_param)
544 if k in mset:
545 for v in return_param_tuple:
546 return_dict[v].append(dev.get(v))
547 collector.add(k)
548 return collector
549
550
551 def validate_ome_data(module, rest_obj, item_list, filter_param, return_param_tuple, ome_uri, item_name="Items"):
552 mset = set(item_list)
553 return_dict = {v: [] for v in return_param_tuple}
554 # can be further optimized if len(mset) == 1
555 resp = rest_obj.invoke_request("GET", ome_uri)
556 all_items = resp.json_data.get("value", [])
557 dvdr = len(all_items) if len(all_items) else 100
558 collector = get_items_to_remove(filter_param, return_param_tuple, return_dict, all_items, mset)
559 mset = mset - collector
560 all_item_count = resp.json_data.get("@odata.count")
561 next_link = resp.json_data.get("@odata.nextLink")
562 if mset and next_link:
563 if len(mset) < (all_item_count // dvdr):
564 for item_id in mset:
565 query_param = {"$filter": f"{filter_param} eq '{item_id}'"}
566 resp = rest_obj.invoke_request('GET', ome_uri, query_param=query_param)
567 one_item = resp.json_data.get("value", [])
568 collector = collector | get_items_to_remove(filter_param, return_param_tuple, return_dict, one_item, mset)
569 mset = mset - collector
570 else:
571 while next_link and mset:
572 resp = rest_obj.invoke_request('GET', next_link.lstrip("/api"))
573 all_items = resp.json_data.get("value", [])
574 collector = get_items_to_remove(filter_param, return_param_tuple, return_dict, all_items, mset)
575 mset = mset - collector
576 next_link = resp.json_data.get("@odata.nextLink", None)
577 if mset:
578 module.exit_json(failed=True,
579 msg=OME_DATA_MSG.format(item_name, filter_param, SEPARATOR.join(mset)))
580 ret_list = [(return_dict[id]) for id in return_param_tuple]
581 return tuple(ret_list)
582
583
584 def get_target_payload(module, rest_obj):
585 target_payload = {'AllTargets': False,
586 'DeviceTypes': [],
587 'Devices': [],
588 'Groups': [],
589 'UndiscoveredTargets': []}
590 mparams = module.params
591 target_provided = False
592 if mparams.get('all_devices'):
593 target_payload['AllTargets'] = True
594 target_provided = True
595 elif mparams.get('any_undiscovered_devices'):
596 target_payload['UndiscoveredTargets'] = ["ALL_UNDISCOVERED_TARGETS"]
597 target_provided = True
598 elif mparams.get('specific_undiscovered_devices'):
599 target_payload['UndiscoveredTargets'] = list(set(module.params.get('specific_undiscovered_devices')))
600 target_payload['UndiscoveredTargets'].sort()
601 target_provided = True
602 elif mparams.get('device_service_tag'):
603 devicetype, deviceids = validate_ome_data(module, rest_obj, mparams.get('device_service_tag'),
604 'DeviceServiceTag', ('Type', 'Id'), DEVICES_URI, 'devices')
605 target_payload['Devices'] = deviceids
606 target_payload['Devices'].sort()
607 target_payload['DeviceTypes'] = list(set(devicetype))
608 target_payload['DeviceTypes'].sort()
609 target_provided = True
610 elif mparams.get('device_group'):
611 groups = validate_ome_data(module, rest_obj, mparams.get('device_group'), 'Name', ('Id',), GROUPS_URI, 'groups')
612 target_payload['Groups'] = groups[0]
613 target_payload['Groups'].sort()
614 target_provided = True
615 if not target_provided:
616 target_payload = {}
617 return target_payload
618
619
620 def get_category_data_tree(rest_obj):
621 resp = rest_obj.invoke_request("GET", CATEGORY_URI)
622 cat_raw = resp.json_data.get("value", [])
623 cat_dict = dict(
624 (category.get("Name"),
625 dict((y.get("Name"),
626 {y.get("Id"): dict((z.get('Name'), z.get('Id')
627 ) for z in y.get("SubCategoryDetails"))}
628 ) for y in category.get("CategoriesDetails")
629 )
630 ) for category in cat_raw
631 )
632 return cat_dict
633
634
635 def get_all_actions(rest_obj):
636 resp = rest_obj.invoke_request("GET", ACTIONS_URI)
637 actions = resp.json_data.get("value", [])
638 cmp_actions = dict((x.get("Name"), {"Id": x.get("Id"),
639 "Disabled": x.get("Disabled"),
640 "Parameters": dict((y.get("Name"), y.get("Value")) for y in x.get("ParameterDetails")),
641 "Type": dict((y.get("Name"),
642 ["true", "false"]
643 if y.get("Type") == "boolean"
644 else [z.get("Value") for z in y.get("TemplateParameterTypeDetails")
645 if y.get("Type") != "string"]) for y in x.get("ParameterDetails"))
646 }
647 ) for x in actions)
648 return cmp_actions
649
650
651 def validate_time(module, time, time_format, time_type):
652 try:
653 ftime = datetime.strptime(time, time_format)
654 except ValueError:
655 module.exit_json(failed=True, msg=INVALID_TIME.format(time_type, time))
656 return ftime
657
658
659 def get_ftime(module, inp_schedule, time_type, time_interval):
660 def_time = "00:00"
661 time_format = "%Y-%m-%d %H:%M:%S.%f"
662 hhmm = inp_schedule.get(f"time_{time_type}") if time_interval else def_time
663 date_x = inp_schedule.get(f"date_{time_type}")
664 time_x = None
665 if date_x:
666 dtime = f"{date_x} {hhmm}:00.000"
667 time_x = validate_time(module, dtime, time_format, time_type)
668 elif time_interval:
669 dtime = f"{hhmm}:00.000"
670 else:
671 dtime = ""
672 return dtime, time_x
673
674
675 def get_schedule_payload(module):
676 schedule_payload = {}
677 inp_schedule = module.params.get('date_and_time')
678 if inp_schedule:
679 time_interval = bool(inp_schedule.get('time_interval'))
680 schedule_payload['Interval'] = time_interval
681 schedule_payload["StartTime"], start_time_x = get_ftime(module, inp_schedule, "from", time_interval)
682 schedule_payload["EndTime"], end_time_x = get_ftime(module, inp_schedule, "to", time_interval)
683 if inp_schedule.get('date_to') and end_time_x < start_time_x:
684 module.exit_json(failed=True, msg=END_START_TIME.format(end_time_x, start_time_x))
685 weekdays = {'monday': 'mon', 'tuesday': 'tue', 'wednesday': 'wed', 'thursday': 'thu', 'friday': 'fri',
686 'saturday': 'sat', 'sunday': 'sun'}
687 inp_week_list = ['*']
688 cron_sep = ","
689 if inp_schedule.get('days'):
690 week_order = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']
691 inp_week_list = sorted(list(set(inp_schedule.get('days'))), key=week_order.index)
692 schedule_payload["CronString"] = f"* * * ? * {cron_sep.join([weekdays.get(x, '*') for x in inp_week_list])} *"
693 return {"Schedule": schedule_payload} if schedule_payload else {}
694
695
696 def create_action_payload(inp_k, inp_val, ref_actions, module):
697 if ref_actions.get(inp_k).get('Disabled'):
698 module.exit_json(failed=True, msg=DISABLED_ACTION.format(inp_k))
699 pld = {
700 'TemplateId': ref_actions.get(inp_k).get('Id'),
701 'Name': inp_k,
702 'ParameterDetails': {}
703 }
704 diff = set(inp_val.keys()) - set(ref_actions.get(inp_k).get('Parameters').keys())
705 if diff:
706 module.exit_json(failed=True,
707 msg=ACTION_INVALID_PARAM.format(
708 inp_k, SEPARATOR.join(diff), SEPARATOR.join(ref_actions.get(inp_k).get('Parameters').keys())))
709 for sub_k, sub_val in inp_val.items():
710 valid_values = ref_actions.get(inp_k).get('Type').get(sub_k)
711 if valid_values:
712 if str(sub_val).lower() not in valid_values:
713 module.exit_json(failed=True, msg=ACTION_INVALID_VALUE.format(inp_k, sub_val, sub_k, SEPARATOR.join(valid_values)))
714 else:
715 inp_val[sub_k] = str(sub_val).lower() if str(sub_val).lower() in ("true", "false") else sub_val
716 pld['ParameterDetails'] = inp_val
717 return pld
718
719
720 def get_actions_payload(module, rest_obj):
721 action_payload = {}
722 inp_actions = module.params.get('actions')
723 if inp_actions:
724 ref_actions = get_all_actions(rest_obj)
725 inp_dict = {x.get("action_name"): {y.get("name"): y.get("value")
726 for y in x.get("parameters", [])} for x in inp_actions}
727 if 'Ignore' in inp_dict:
728 action_payload['Ignore'] = {'TemplateId': ref_actions.get('Ignore').get('Id'),
729 'Name': "Ignore",
730 'ParameterDetails': {}}
731 else:
732 for inp_k, inp_val in inp_dict.items():
733 if inp_k in ref_actions:
734 action_payload[inp_k] = create_action_payload(inp_k, inp_val, ref_actions, module)
735 else:
736 module.exit_json(failed=True, msg=ACTION_DIS_EXIST.format(inp_k))
737 return {"Actions": action_payload} if action_payload else {}
738
739
740 def load_subcategory_data(module, inp_sub_cat_list, sub_cat_dict, key_id, payload_cat, payload_subcat, inp_category):
741 if inp_sub_cat_list:
742 for sub_cat in inp_sub_cat_list:
743 if sub_cat in sub_cat_dict:
744 payload_cat.append(key_id)
745 payload_subcat.append(
746 sub_cat_dict.get(sub_cat))
747 else:
748 module.exit_json(failed=True, msg=SUBCAT_IN_CATEGORY.format(sub_cat, inp_category.get('category_name')))
749 else:
750 payload_cat.append(key_id)
751 payload_subcat.append(0)
752
753
754 def load_category_data(module, catalog_name, category_list, category_det, payload_cat, payload_subcat):
755 if category_list:
756 for inp_category in category_list:
757 if inp_category.get('category_name') in category_det:
758 resp_category_dict = category_det.get(inp_category.get('category_name'))
759 key_id = list(resp_category_dict.keys())[0]
760 sub_cat_dict = resp_category_dict.get(key_id)
761 inp_sub_cat_list = inp_category.get('sub_category_names')
762 load_subcategory_data(module, inp_sub_cat_list, sub_cat_dict, key_id, payload_cat, payload_subcat, inp_category)
763 else:
764 module.exit_json(failed=True, msg=CATEGORY_IN_CATALOG.format(inp_category.get('category_name'), catalog_name))
765 else:
766 payload_cat.append(0)
767 payload_subcat.append(0)
768
769
770 def get_category_payloadlist(module, inp_catalog_list, cdict_ref):
771 payload_cat_list = []
772 for inp_catalog in inp_catalog_list:
773 new_dict = {}
774 catalog_name = inp_catalog.get('catalog_name')
775 if catalog_name in cdict_ref:
776 new_dict["CatalogName"] = catalog_name
777 payload_cat = []
778 category_det = cdict_ref.get(catalog_name)
779 payload_subcat = []
780 category_list = inp_catalog.get('catalog_category')
781 load_category_data(module, catalog_name, category_list, category_det, payload_cat, payload_subcat)
782 new_dict["Categories"] = payload_cat
783 new_dict['SubCategories'] = payload_subcat
784 else:
785 module.exit_json(failed=True, msg=CATALOG_DIS_EXIST.format(catalog_name))
786 payload_cat_list.append(new_dict)
787 return payload_cat_list
788
789
790 def get_category_payload(module, rest_obj):
791 inp_catalog_list = module.params.get('category')
792 cdict_ref = get_category_data_tree(rest_obj)
793 if not cdict_ref:
794 module.exit_json(failed=True, msg=CATEGORY_FETCH_FAILED)
795 payload_cat_list = get_category_payloadlist(module, inp_catalog_list, cdict_ref)
796 return payload_cat_list
797
798
799 def get_message_payload(module):
800 mlist = []
801 if module.params.get('message_file'):
802 csvpath = module.params.get('message_file')
803 if not os.path.isfile(csvpath):
804 module.exit_json(
805 failed=True, msg=CSV_PATH.format(csvpath))
806 with open(csvpath) as csvfile:
807 spamreader = csv.reader(csvfile)
808 for row in spamreader:
809 mlist.extend(row)
810 if mlist[0].lower().startswith('message'):
811 mlist.pop(0)
812 elif module.params.get('message_ids'):
813 mlist = module.params.get('message_ids')
814 return mlist
815
816
817 def get_category_or_message(module, rest_obj):
818 cat_payload = {"Catalogs": {},
819 "MessageIds": []}
820 cat_msg_provided = False
821 if module.params.get('category'):
822 payload_cat_list = get_category_payload(module, rest_obj)
823 cat_dict = dict((x.get('CatalogName'), x) for x in payload_cat_list)
824 cat_msg_provided = True
825 cat_payload['Catalogs'] = cat_dict
826 else:
827 mlist = get_message_payload(module)
828 if mlist:
829 validate_ome_data(module, rest_obj, mlist, 'MessageId', ('MessageId',), MESSAGES_URI, 'messages')
830 cat_msg_provided = True
831 cat_payload['MessageIds'] = list(set(mlist))
832 cat_payload['MessageIds'].sort()
833 if not cat_msg_provided:
834 cat_payload = {}
835 return cat_payload
836
837
838 def get_severity_payload(module, rest_obj):
839 try:
840 resp = rest_obj.invoke_request("GET", SEVERITY_URI)
841 severity_dict = dict((x.get('Name').lower(), x.get('Id'))
842 for x in resp.json_data.get("Value"))
843 except Exception:
844 severity_dict = {"unknown": 1, "info": 2,
845 "normal": 4, "warning": 8, "critical": 16}
846 inp_sev_list = module.params.get('severity')
847 sev_payload = {}
848 if inp_sev_list:
849 if 'all' in inp_sev_list:
850 sev_payload = {"Severities": list(severity_dict.values())}
851 else:
852 sev_payload = {"Severities": [
853 severity_dict.get(x) for x in inp_sev_list]}
854 sev_payload['Severities'].sort()
855 return sev_payload
856
857
858 def transform_existing_policy_data(policy):
859 pdata = policy.get('PolicyData')
860 undiscovered = pdata.get('UndiscoveredTargets')
861 if undiscovered:
862 pdata['UndiscoveredTargets'] = [x.get('TargetAddress') for x in undiscovered]
863 actions = pdata.get('Actions')
864 if actions:
865 for action in actions:
866 if action.get('Name') == "RemoteCommand":
867 # Special case handling for RemoteCommand, appends 1 after every post call to "remotecommandaction"
868 action['ParameterDetails'] = dict((str(act_param.get('Name')).rstrip('1'), act_param.get('Value'))
869 for act_param in action.get('ParameterDetails', []))
870 else:
871 action['ParameterDetails'] = dict((act_param.get('Name'), act_param.get('Value'))
872 for act_param in action.get('ParameterDetails', []))
873 action.pop('Id', None)
874 pdata['Actions'] = dict((x.get('Name'), x) for x in actions)
875 catalogs = pdata.get('Catalogs')
876 pdata['Catalogs'] = dict((x.get('CatalogName'), x) for x in catalogs)
877 # for Devices, DeviceTypes, Groups, Severities
878 for pol_data in pdata.values():
879 if isinstance(pol_data, list):
880 pol_data.sort()
881 messages = pdata.get('MessageIds', [])
882 pdata['MessageIds'] = [m.strip("'") for m in messages]
883
884
885 def format_payload(policy):
886 pdata = policy.get('PolicyData')
887 undiscovered = pdata.get('UndiscoveredTargets')
888 if undiscovered:
889 pdata['UndiscoveredTargets'] = [({"TargetAddress": x}) for x in undiscovered]
890 actions = pdata.get('Actions')
891 if actions:
892 for action in actions.values():
893 action['ParameterDetails'] = [
894 {"Name": k, "Value": v} for k, v in action.get('ParameterDetails', {}).items()]
895 pdata['Actions'] = list(actions.values())
896 catalogs = pdata.get('Catalogs')
897 pdata['Catalogs'] = list(catalogs.values())
898
899
900 def compare_policy_payload(module, rest_obj, policy):
901 diff = 0
902 new_payload = {}
903 new_policy_data = {}
904 new_payload["PolicyData"] = new_policy_data
905 transform_existing_policy_data(policy)
906 payload_items = []
907 payload_items.append(get_target_payload(module, rest_obj))
908 payload_items.append(get_category_or_message(module, rest_obj))
909 payload_items.append(get_actions_payload(module, rest_obj))
910 payload_items.append(get_schedule_payload(module))
911 payload_items.append(get_severity_payload(module, rest_obj))
912 for payload in payload_items:
913 if payload:
914 new_policy_data.update(payload)
915 diff_tuple = recursive_diff(new_payload['PolicyData'], policy['PolicyData'])
916 if diff_tuple and diff_tuple[0]:
917 diff = diff + 1
918 policy['PolicyData'].update(payload)
919 if module.params.get('new_name'):
920 new_payload['Name'] = module.params.get('new_name')
921 if module.params.get('description'):
922 new_payload['Description'] = module.params.get('description')
923 if module.params.get('enable') is not None:
924 new_payload['Enabled'] = module.params.get('enable')
925 policy = strip_substr_dict(policy)
926 new_payload.pop('PolicyData', None)
927 diff_tuple = recursive_diff(new_payload, policy)
928 if diff_tuple and diff_tuple[0]:
929 diff = diff + 1
930 policy.update(diff_tuple[0])
931 return diff
932
933
934 def get_policy_data(module, rest_obj):
935 policy_data = {}
936 target = get_target_payload(module, rest_obj)
937 if not target:
938 module.exit_json(failed=True, msg=INVALID_TARGETS)
939 policy_data.update(target)
940 cat_msg = get_category_or_message(module, rest_obj)
941 if not cat_msg:
942 module.exit_json(failed=True, msg=INVALID_CATEGORY_MESSAGE)
943 policy_data.update(cat_msg)
944 schedule = get_schedule_payload(module)
945 if not schedule:
946 module.exit_json(failed=True, msg=INVALID_SCHEDULE)
947 policy_data.update(schedule)
948 actions = get_actions_payload(module, rest_obj)
949 if not actions:
950 module.exit_json(failed=True, msg=INVALID_ACTIONS)
951 policy_data.update(actions)
952 sev_payload = get_severity_payload(module, rest_obj)
953 if not sev_payload.get('Severities'):
954 module.exit_json(failed=True, msg=INVALID_SEVERITY)
955 policy_data.update(sev_payload)
956 return policy_data
957
958
959 def remove_policy(module, rest_obj, policies):
960 id_list = [x.get("Id")
961 for x in policies if x.get("DefaultPolicy") is False]
962 if len(id_list) != len(policies):
963 module.exit_json(failed=True,
964 msg=DEFAULT_POLICY_DELETE.format(SEPARATOR.join([x.get('Name') for x in policies if x.get('DefaultPolicy')])))
965 if module.check_mode:
966 module.exit_json(msg=CHANGES_MSG, changed=True)
967 rest_obj.invoke_request("POST", REMOVE_URI, data={
968 "AlertPolicyIds": id_list})
969 module.exit_json(changed=True, msg=SUCCESS_MSG.format("delete"))
970
971
972 def enable_toggle_policy(module, rest_obj, policies):
973 enabler = module.params.get('enable')
974 id_list = [x.get("Id") for x in policies if x.get("Enabled") is not enabler]
975 if not id_list:
976 module.exit_json(msg=NO_CHANGES_MSG)
977 if module.check_mode:
978 module.exit_json(msg=CHANGES_MSG, changed=True)
979 uri = ENABLE_URI if enabler else DISABLE_URI
980 rest_obj.invoke_request("POST", uri, data={"AlertPolicyIds": id_list})
981 module.exit_json(changed=True, msg=SUCCESS_MSG.format("enable" if enabler else "disable"))
982
983
984 def update_policy(module, rest_obj, policy):
985 diff = compare_policy_payload(module, rest_obj, policy)
986 if not diff:
987 module.exit_json(msg=NO_CHANGES_MSG)
988 if module.check_mode:
989 module.exit_json(msg=CHANGES_MSG, changed=True)
990 format_payload(policy)
991 resp = rest_obj.invoke_request("PUT", f"{POLICIES_URI}({policy.get('Id')})", data=policy)
992 module.exit_json(changed=True, msg=SUCCESS_MSG.format("update"),
993 status=resp.json_data)
994
995
996 def create_policy(module, rest_obj):
997 create_payload = {}
998 policy_data = get_policy_data(module, rest_obj)
999 create_payload['PolicyData'] = policy_data
1000 create_payload['Name'] = module.params.get('name')[0]
1001 create_payload['Description'] = module.params.get('description')
1002 create_payload['Enabled'] = module.params.get(
1003 'enable') if module.params.get('enable', True) is not None else True
1004 if module.check_mode:
1005 module.exit_json(msg=CHANGES_MSG, changed=True)
1006 format_payload(create_payload)
1007 resp = rest_obj.invoke_request("POST", POLICIES_URI, data=create_payload)
1008 module.exit_json(changed=True, msg=SUCCESS_MSG.format(
1009 "create"), status=resp.json_data)
1010
1011
1012 def handle_policy_enable(module, rest_obj, policies, name_list):
1013 if len(policies) == len(name_list):
1014 enable_toggle_policy(module, rest_obj, policies)
1015 else:
1016 invalid_policies = set(name_list) - set(x.get("Name") for x in policies)
1017 enabler = module.params.get('enable')
1018 module.exit_json(failed=True, msg=POLICY_ENABLE_MISSING.format("enable" if enabler else "disable", SEPARATOR.join(invalid_policies)))
1019
1020
1021 def handle_absent_state(module, rest_obj, policies):
1022 if policies:
1023 remove_policy(module, rest_obj, policies)
1024 else:
1025 module.exit_json(msg=NO_POLICY_EXIST)
1026
1027
1028 def handle_present_state(module, rest_obj, policies, name_list, present_args):
1029 present_args.remove('enable')
1030 enable = module.params.get('enable')
1031 if not any(module.params.get(prm) is not None for prm in present_args) and enable is not None:
1032 handle_policy_enable(module, rest_obj, policies, name_list)
1033 if len(name_list) > 1:
1034 module.exit_json(failed=True, msg=MULTIPLE_POLICIES)
1035 if policies:
1036 update_policy(module, rest_obj, policies[0])
1037 else:
1038 create_policy(module, rest_obj)
1039
1040
1041 def main():
1042 specs = {
1043 "name": {'type': 'list', 'elements': 'str', 'required': True},
1044 "state": {'default': 'present', 'choices': ['present', 'absent'], 'type': 'str'},
1045 "enable": {'type': 'bool'},
1046 "new_name": {'type': 'str'},
1047 "description": {'type': 'str'},
1048 "device_service_tag": {'type': 'list', 'elements': 'str'},
1049 "device_group": {'type': 'list', 'elements': 'str'},
1050 "specific_undiscovered_devices": {'type': 'list', 'elements': 'str'},
1051 "any_undiscovered_devices": {'type': 'bool'},
1052 "all_devices": {'type': 'bool'},
1053 "category": {'type': 'list', 'elements': 'dict',
1054 'options': {'catalog_name': {'type': 'str', 'required': True},
1055 'catalog_category': {'type': 'list', 'elements': 'dict',
1056 'options': {'category_name': {'type': 'str'},
1057 'sub_category_names': {'type': 'list', 'elements': 'str'}
1058 },
1059 }
1060 }
1061 },
1062 "message_ids": {'type': 'list', 'elements': 'str'},
1063 "message_file": {'type': 'path'},
1064 "date_and_time": {'type': 'dict',
1065 'options': {'date_from': {'type': 'str', 'required': True},
1066 'date_to': {'type': 'str'},
1067 'time_from': {'type': 'str'},
1068 'time_to': {'type': 'str'},
1069 'days': {'type': 'list', 'elements': 'str',
1070 'choices': ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']},
1071 'time_interval': {'type': 'bool'}
1072 },
1073 'required_if': [['time_interval', True, ('time_from', 'time_to')]]
1074 },
1075 "severity": {'type': 'list', 'elements': 'str', 'choices': ['info', 'normal', 'warning', 'critical', 'unknown', 'all']},
1076 "actions": {'type': 'list', 'elements': 'dict',
1077 'options': {'action_name': {'type': 'str', 'required': True},
1078 'parameters': {'type': 'list', 'elements': 'dict', 'default': [],
1079 'options': {'name': {'type': 'str'},
1080 'value': {'type': 'str'}}
1081 }
1082 }
1083 }
1084 }
1085
1086 present_args = ['enable', 'new_name', 'description', 'device_service_tag', 'device_group',
1087 'specific_undiscovered_devices', 'any_undiscovered_devices', 'all_devices',
1088 'category', 'message_ids', 'message_file', 'date_and_time', 'severity', 'actions']
1089 module = OmeAnsibleModule(
1090 argument_spec=specs,
1091 required_if=[['state', 'present', present_args, True]],
1092 mutually_exclusive=[('device_service_tag', 'device_group', 'any_undiscovered_devices', 'specific_undiscovered_devices', 'all_devices',),
1093 ('message_ids', 'message_file', 'category',)],
1094 supports_check_mode=True)
1095 try:
1096 with RestOME(module.params, req_session=True) as rest_obj:
1097 state = module.params.get('state')
1098 name_list = list(set(module.params.get('name')))
1099 policies = get_alert_policies(rest_obj, name_list)
1100 if state == 'absent':
1101 handle_absent_state(module, rest_obj, policies)
1102 else:
1103 handle_present_state(module, rest_obj, policies, name_list, present_args)
1104 except HTTPError as err:
1105 module.exit_json(failed=True, msg=str(err), error_info=json.load(err))
1106 except URLError as err:
1107 module.exit_json(msg=str(err), unreachable=True)
1108 except (SSLValidationError, ConnectionError, TypeError, ValueError, OSError) as err:
1109 module.exit_json(failed=True, msg=str(err))
1110
1111
1112 if __name__ == '__main__':
1113 main()