Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 10.0.1
7 # Copyright (C) 2021-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
15 __metaclass__ = type
16
17 DOCUMENTATION = r'''
18 ---
19 module: ome_configuration_compliance_baseline
20 short_description: Create, modify, and delete a configuration compliance baseline and remediate non-compliant devices on
21 OpenManage Enterprise
22 version_added: "3.2.0"
23 description: "This module allows to create, modify, and delete a configuration compliance baseline on OpenManage Enterprise.
24 This module also allows to remediate devices that are non-compliant with the baseline by changing the attributes of devices
25 to match with the associated baseline attributes."
26 extends_documentation_fragment:
27 - dellemc.openmanage.oment_auth_options
28 options:
29 command:
30 description:
31 - "C(create) creates a configuration baseline from an existing compliance template.C(create) supports
32 C(check_mode) or idempotency checking for only I(names)."
33 - "C(modify) modifies an existing baseline.Only I(names), I(description), I(device_ids), I(device_service_tags),
34 and I(device_group_names) can be modified"
35 - "I(WARNING) When a baseline is modified, the provided I(device_ids), I(device_group_names), and I(device_service_tags)
36 replaces the devices previously present in the baseline."
37 - C(delete) deletes the list of configuration compliance baselines based on the baseline name. Invalid baseline
38 names are ignored.
39 - "C(remediate) remediates devices that are non-compliant with the baseline by changing the attributes of devices
40 to match with the associated baseline attributes."
41 - "C(remediate) is performed on all the non-compliant devices if either I(device_ids), or I(device_service_tags)
42 is not provided."
43 choices: [create, modify, delete, remediate]
44 default: create
45 type: str
46 names:
47 description:
48 - Name(s) of the configuration compliance baseline.
49 - This option is applicable when I(command) is C(create), C(modify), or C(delete).
50 - Provide the list of configuration compliance baselines names that are supported when I(command) is C(delete).
51 required: true
52 type: list
53 elements: str
54 new_name:
55 description:
56 - New name of the compliance baseline to be modified.
57 - This option is applicable when I(command) is C(modify).
58 type: str
59 template_name:
60 description:
61 - Name of the compliance template for creating the compliance baseline(s).
62 - Name of the deployment template to be used for creating a compliance baseline.
63 - This option is applicable when I(command) is C(create) and is mutually exclusive with I(template_id).
64 type: str
65 template_id:
66 description:
67 - ID of the deployment template to be used for creating a compliance baseline.
68 - This option is applicable when I(command) is C(create) and is mutually exclusive with I(template_name).
69 type: int
70 device_ids:
71 description:
72 - IDs of the target devices.
73 - This option is applicable when I(command) is C(create), C(modify), or C(remediate), and is mutually exclusive
74 with I(device_service_tag) and I(device_group_names).
75 type: list
76 elements: int
77 device_service_tags:
78 description:
79 - Service tag of the target device.
80 - This option is applicable when I(command) is C(create), C(modify), or C(remediate) and is mutually exclusive with
81 I(device_ids) and I(device_group_names).
82 type: list
83 elements: str
84 device_group_names:
85 description:
86 - Name of the target device group.
87 - This option is applicable when I(command) is C(create), or C(modify)
88 and is mutually exclusive with I(device_ids) and I(device_service_tag).
89 type: list
90 elements: str
91 description:
92 description:
93 - Description of the compliance baseline.
94 - This option is applicable when I(command) is C(create), or C(modify).
95 type: str
96 run_later:
97 description:
98 - Indicates whether to remediate immediately or in the future.
99 - This is applicable when I(command) is C(remediate).
100 - If I(run_later) is C(true), then I(staged_at_reboot) is ignored.
101 - If I(run_later) is C(true), then I(job_wait) is not applicable.
102 - If I(run_later) is C(true), then I(cron) must be specified.
103 type: bool
104 cron:
105 description:
106 - Provide a cron expression based on Quartz cron format.
107 - Time format is "%S %M %H %d %m ? %Y".
108 - This is applicable when I(run_later) is C(true).
109 type: str
110 staged_at_reboot:
111 description:
112 - Indicates whether remediate has to be executed on next reboot.
113 - If I(staged_at_reboot) is C(true), then remediation will occur during the next reboot.
114 type: bool
115 job_wait:
116 description:
117 - Provides the option to wait for job completion.
118 - This option is applicable when I(command) is C(create), C(modify), or C(remediate).
119 type: bool
120 default: true
121 job_wait_timeout:
122 description:
123 - The maximum wait time of I(job_wait) in seconds.The job will only be tracked for this duration.
124 - This option is applicable when I(job_wait) is C(true).
125 type: int
126 default: 10800
127 requirements:
128 - "python >= 3.9.6"
129 author:
130 - "Sajna Shetty(@Sajna-Shetty)"
131 - "Abhishek Sinha(@Abhishek-Dell)"
132 - "Shivam Sharma(@ShivamSh3)"
133 - "Meenakshi Dembi(@meenakshidembi691)"
134 notes:
135 - This module supports C(check_mode).
136 - Ensure that the devices have the required licenses to perform the baseline compliance operations.
137 '''
138
139 EXAMPLES = r'''
140 ---
141 - name: Create a configuration compliance baseline using device IDs
142 dellemc.openmanage.ome_configuration_compliance_baseline:
143 hostname: "192.168.0.1"
144 username: "username"
145 password: "password"
146 ca_path: "/path/to/ca_cert.pem"
147 names: "baseline1"
148 template_name: "template1"
149 description: "description of baseline"
150 device_ids:
151 - 1111
152 - 2222
153
154 - name: Create a configuration compliance baseline using device service tags
155 dellemc.openmanage.ome_configuration_compliance_baseline:
156 hostname: "192.168.0.1"
157 username: "username"
158 password: "password"
159 ca_path: "/path/to/ca_cert.pem"
160 names: "baseline1"
161 template_id: 1234
162 description: "description of baseline"
163 device_service_tags:
164 - "SVCTAG1"
165 - "SVCTAG2"
166
167 - name: Create a configuration compliance baseline using group names
168 dellemc.openmanage.ome_configuration_compliance_baseline:
169 hostname: "192.168.0.1"
170 username: "username"
171 password: "password"
172 ca_path: "/path/to/ca_cert.pem"
173 names: "baseline2"
174 template_id: 2
175 job_wait_timeout: 1000
176 description: "description of baseline"
177 device_group_names:
178 - "Group1"
179 - "Group2"
180
181 - name: Delete the configuration compliance baselines
182 dellemc.openmanage.ome_configuration_compliance_baseline:
183 hostname: "192.168.0.1"
184 username: "username"
185 password: "password"
186 ca_path: "/path/to/ca_cert.pem"
187 command: delete
188 names:
189 - baseline1
190 - baseline2
191
192 - name: Modify a configuration compliance baseline using group names
193 dellemc.openmanage.ome_configuration_compliance_baseline:
194 hostname: "192.168.0.1"
195 username: "username"
196 password: "password"
197 ca_path: "/path/to/ca_cert.pem"
198 command: modify
199 names: "baseline1"
200 new_name: "baseline_update"
201 template_name: "template2"
202 description: "new description of baseline"
203 job_wait_timeout: 1000
204 device_group_names:
205 - Group1
206
207 - name: Remediate specific non-compliant devices to a configuration compliance baseline using device IDs
208 dellemc.openmanage.ome_configuration_compliance_baseline:
209 hostname: "192.168.0.1"
210 username: "username"
211 password: "password"
212 ca_path: "/path/to/ca_cert.pem"
213 command: "remediate"
214 names: "baseline1"
215 device_ids:
216 - 1111
217
218 - name: Remediate specific non-compliant devices to a configuration compliance baseline using device service tags
219 dellemc.openmanage.ome_configuration_compliance_baseline:
220 hostname: "192.168.0.1"
221 username: "username"
222 password: "password"
223 ca_path: "/path/to/ca_cert.pem"
224 command: "remediate"
225 names: "baseline1"
226 device_service_tags:
227 - "SVCTAG1"
228 - "SVCTAG2"
229
230 - name: Remediate all the non-compliant devices to a configuration compliance baseline
231 dellemc.openmanage.ome_configuration_compliance_baseline:
232 hostname: "192.168.0.1"
233 username: "username"
234 password: "password"
235 ca_path: "/path/to/ca_cert.pem"
236 command: "remediate"
237 names: "baseline1"
238
239 - name: Remediate specific non-compliant devices to a configuration compliance baseline using device IDs at scheduled time
240 dellemc.openmanage.ome_configuration_compliance_baseline:
241 hostname: "192.168.0.1"
242 username: "username"
243 password: "password"
244 ca_path: "/path/to/ca_cert.pem"
245 command: "remediate"
246 names: "baseline1"
247 device_ids:
248 - 1111
249 run_later: true
250 cron: "0 10 11 14 02 ? 2032" # Feb 14,2032 11:10:00
251
252 - name: Remediate specific non-compliant devices to a configuration compliance baseline using device service tags on next reboot
253 dellemc.openmanage.ome_configuration_compliance_baseline:
254 hostname: "192.168.0.1"
255 username: "username"
256 password: "password"
257 ca_path: "/path/to/ca_cert.pem"
258 command: "remediate"
259 names: "baseline1"
260 device_service_tags:
261 - "SVCTAG1"
262 - "SVCTAG2"
263 staged_at_reboot: true
264 '''
265
266 RETURN = r'''
267 ---
268 msg:
269 description: Overall status of the configuration compliance baseline operation.
270 returned: always
271 type: str
272 sample: "Successfully created the configuration compliance baseline."
273 incompatible_devices:
274 description: Details of the devices which cannot be used to perform baseline compliance operations
275 returned: when I(device_service_tags) or I(device_ids) contains incompatible devices for C(create) or C(modify)
276 type: list
277 sample: [1234, 5678]
278 compliance_status:
279 description: Status of compliance baseline operation.
280 returned: when I(command) is C(create) or C(modify)
281 type: dict
282 sample: {
283 "Id": 13,
284 "Name": "baseline1",
285 "Description": null,
286 "TemplateId": 102,
287 "TemplateName": "one",
288 "TemplateType": 2,
289 "TaskId": 26584,
290 "PercentageComplete": "100",
291 "TaskStatus": 2070,
292 "LastRun": "2021-02-27 13:15:13.751",
293 "BaselineTargets": [
294 {
295 "Id": 1111,
296 "Type": {
297 "Id": 1000,
298 "Name": "DEVICE"
299 }
300 }
301 ],
302 "ConfigComplianceSummary": {
303 "ComplianceStatus": "OK",
304 "NumberOfCritical": 0,
305 "NumberOfWarning": 0,
306 "NumberOfNormal": 0,
307 "NumberOfIncomplete": 0
308 }
309 }
310 job_id:
311 description:
312 - Task ID created when I(command) is C(remediate).
313 returned: when I(command) is C(remediate)
314 type: int
315 sample: 14123
316 "job_details":
317 description: Details of the failed job.
318 returned: on job failure
319 type: list
320 sample: [
321 {
322 "ElapsedTime": "00:22:17",
323 "EndTime": "2024-06-19 13:42:41.285",
324 "ExecutionHistoryId": 797320,
325 "Id": 14123,
326 "IdBaseEntity": 19559,
327 "JobStatus": {
328 "Id": 2070,
329 "Name": "Failed"
330 },
331 "Key": "SVCTAG1",
332 "Progress": "100",
333 "StartTime": "2024-06-19 13:20:23.495",
334 "Value": "Starting Pre-checks....LC status is : InUse, wait for 30 seconds and retry ...(1)"
335 }
336 ]
337 error_info:
338 description: Details of the HTTP Error.
339 returned: on HTTP error
340 type: dict
341 sample: {
342 "error": {
343 "code": "Base.1.0.GeneralError",
344 "message": "A general error has occurred. See ExtendedInfo for more information.",
345 "@Message.ExtendedInfo": [
346 {
347 "MessageId": "GEN1234",
348 "RelatedProperties": [],
349 "Message": "Unable to process the request because an error occurred.",
350 "MessageArgs": [],
351 "Severity": "Critical",
352 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
353 }
354 ]
355 }
356 }
357 '''
358
359 import time
360 import re
361 import datetime
362 from ssl import SSLError
363 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
364 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
365 from ansible.module_utils.urls import ConnectionError, SSLValidationError
366 from ansible.module_utils.compat.version import LooseVersion
367
368 COMPLIANCE_BASELINE = "TemplateService/Baselines"
369 REMEDIATE_BASELINE = "TemplateService/Actions/TemplateService.Remediate"
370 DELETE_COMPLIANCE_BASELINE = "TemplateService/Actions/TemplateService.RemoveBaseline"
371 MODIFY_COMPLIANCE_BASELINE = "api/TemplateService/Baselines({baseline_id})"
372 TEMPLATE_VIEW = "TemplateService/Templates"
373 DEVICE_VIEW = "DeviceService/Devices"
374 GROUP_VIEW = "GroupService/Groups"
375 OME_INFO = "ApplicationService/Info"
376 CONFIG_COMPLIANCE_URI = "TemplateService/Baselines({0})/DeviceConfigComplianceReports"
377 INVALID_DEVICES = "{identifier} details are not available."
378 TEMPLATE_ID_ERROR_MSG = "Template with ID '{template_id}' not found."
379 TEMPLATE_NAME_ERROR_MSG = "Template '{template_name}' not found."
380 NAMES_ERROR = "Only delete operations accept multiple baseline names. All the other operations accept only a single " \
381 "baseline name."
382 BASELINE_CHECK_MODE_CHANGE_MSG = "Baseline '{name}' already exists."
383 CHECK_MODE_CHANGES_MSG = "Changes found to be applied."
384 CHECK_MODE_NO_CHANGES_MSG = "No changes found to be applied."
385 BASELINE_CHECK_MODE_NOCHANGE_MSG = "Baseline '{name}' does not exist."
386 CREATE_MSG = "Successfully created the configuration compliance baseline."
387 DELETE_MSG = "Successfully deleted the configuration compliance baseline(s)."
388 MODIFY_MSG = "Successfully modified the configuration compliance baseline."
389 TASK_PROGRESS_MSG = "The initiated task for the configuration compliance baseline is in progress."
390 INVALID_IDENTIFIER = "Target with {identifier} {invalid_val} not found."
391 IDEMPOTENCY_MSG = "The specified configuration compliance baseline details are the same as the existing settings."
392 INVALID_COMPLIANCE_IDENTIFIER = "Unable to complete the operation because the entered target {0} {1}" \
393 " is not associated or complaint with the baseline '{2}'."
394 INVALID_TIME = "job_wait_timeout {0} is not valid."
395 REMEDIATE_MSG = "Successfully completed the remediate operation."
396 REMEDIATE_SCHEDULE_MSG = "Successfully scheduled the remediate operation."
397 REMEDIATE_SCHEDULE_FAIL_MSG = "Failed to schedule the remediate operation."
398 REMEDIATE_STAGED_AT_REBOOT_MSG = "Successfully staged the remediate operation at next reboot."
399 JOB_FAILURE_PROGRESS_MSG = "The initiated task for the configuration compliance baseline has failed."
400 NO_CAPABLE_DEVICES = "Target {0} contains devices which cannot be used for a baseline compliance operation."
401 CRON_REGEX = r'(@(annually|yearly|monthly|weekly|daily|hourly|reboot))|(@every (\d+(ns|us|µs|ms|s|m|h))+)|((((\d+,)+\d+|(\d+(\/|-)\d+)|\d+|\*) ?){5,7})'
402 INVALID_CRON_TIME_MSG = "Invalid cron time format."
403 JOB_URI = "JobService/Jobs({job_id})"
404 TIME_URI = "ApplicationService/Network/TimeConfiguration"
405 PAST_TIME_MSG = "The specified time occurs in the past, provide a future time to schedule the job."
406
407
408 def validate_identifiers(available_values, requested_values, identifier_types, module):
409 """
410 Validate if requested group/device ids are valid
411 """
412 val = set(requested_values) - set(available_values)
413 if val:
414 module.exit_json(msg=INVALID_IDENTIFIER.format(identifier=identifier_types, invalid_val=",".join(map(str, val))), failed=True)
415
416
417 def get_identifiers(available_identifiers_map, requested_values):
418 """
419 Get the device id from service tag
420 or Get the group id from Group names
421 or get the id from baseline names
422 """
423 id_list = []
424 for key, val in available_identifiers_map.items():
425 if val in requested_values:
426 id_list.append(key)
427 return id_list
428
429
430 def get_template_details(module, rest_obj):
431 """
432 Validate the template.
433 """
434 template_identifier = module.params.get('template_id')
435 query_param = {"$filter": "Id eq {0}".format(template_identifier)}
436 identifier = 'Id'
437 if not template_identifier:
438 template_identifier = module.params.get('template_name')
439 query_param = {"$filter": "Name eq '{0}'".format(template_identifier)}
440 identifier = 'Name'
441 resp = rest_obj.invoke_request('GET', TEMPLATE_VIEW, query_param=query_param)
442 if resp.success and resp.json_data.get('value'):
443 template_list = resp.json_data.get('value', [])
444 for each_template in template_list:
445 if each_template.get(identifier) == template_identifier:
446 return each_template
447 if identifier == "Id":
448 module.exit_json(msg=TEMPLATE_ID_ERROR_MSG.format(template_id=template_identifier), failed=True)
449 else:
450 module.exit_json(msg=TEMPLATE_NAME_ERROR_MSG.format(template_name=template_identifier), failed=True)
451
452
453 def get_group_ids(module, rest_obj):
454 """
455 Get the group ids
456 """
457 params = module.params
458 resp_data = rest_obj.get_all_items_with_pagination(GROUP_VIEW)
459 values = resp_data["value"]
460 device_group_names_list = params.get("device_group_names")
461 final_target_list = []
462 if values:
463 available_ids_tag_map = dict([(item["Id"], item["Name"]) for item in values])
464 available_device_tags = available_ids_tag_map.values()
465 tags_identifier = "device_group_names"
466 validate_identifiers(available_device_tags, device_group_names_list, tags_identifier, module)
467 final_target_list = get_identifiers(available_ids_tag_map, device_group_names_list)
468 else:
469 module.exit_json(msg=INVALID_DEVICES.format(identifier="Group"), failed=True)
470 return final_target_list
471
472
473 def get_device_capabilities(devices_list, identifier):
474 if identifier == "device_ids":
475 available_ids_capability_map = dict([(item["Id"], item.get("DeviceCapabilities", [])) for item in devices_list])
476 else:
477 available_ids_capability_map = dict(
478 [(item["Identifier"], item.get("DeviceCapabilities", [])) for item in devices_list])
479 capable_devices = []
480 noncapable_devices = []
481 for key, val in available_ids_capability_map.items():
482 if 33 in val:
483 capable_devices.append(key)
484 else:
485 noncapable_devices.append(key)
486 return {"capable": capable_devices, "non_capable": noncapable_devices}
487
488
489 def get_device_ids(module, rest_obj):
490 """
491 Get the requested device ids
492 """
493 params = module.params
494 resp_data = rest_obj.get_all_report_details(DEVICE_VIEW)
495 values = resp_data["report_list"]
496 id_list = params.get("device_ids")
497 service_tags_list = params.get("device_service_tags")
498 final_target_list = []
499 device_capability_map = {}
500 identifier = "device_ids"
501 if values:
502 available_ids_tag_map = dict([(item["Id"], item["Identifier"]) for item in values])
503 if id_list:
504 available_device_ids = available_ids_tag_map.keys()
505 validate_identifiers(available_device_ids, id_list, "device_ids", module)
506 final_target_list = id_list
507 if service_tags_list:
508 available_device_tags = available_ids_tag_map.values()
509 validate_identifiers(available_device_tags, service_tags_list, "device_service_tags", module)
510 id_list = get_identifiers(available_ids_tag_map, service_tags_list)
511 identifier = "device_service_tags"
512 final_target_list = id_list
513 else:
514 module.exit_json(msg=INVALID_DEVICES.format(identifier="Device"), failed=True)
515 if final_target_list:
516 device_capability_map = get_device_capabilities(values, identifier)
517 return final_target_list, device_capability_map
518
519
520 def validate_capability(module, device_capability_map):
521 """
522 For any non capable devices return the module with failure with list of
523 non capable devices
524 """
525 if module.params.get("device_ids"):
526 device_id_list = module.params.get("device_ids")
527 identifier_types = "device_ids"
528 else:
529 device_id_list = module.params.get("device_service_tags")
530 identifier_types = "device_service_tags"
531 capable_devices = set(device_id_list) & set(device_capability_map.get("capable", []))
532 if len(capable_devices) == 0 or capable_devices and len(capable_devices) != len(device_id_list):
533 non_capable_devices = list(set(device_id_list) - capable_devices)
534 module.exit_json(msg=NO_CAPABLE_DEVICES.format(identifier_types),
535 incompatible_devices=non_capable_devices, failed=True)
536
537
538 def create_payload(module, rest_obj):
539 """
540 create the compliance baseline payload
541 """
542 params = module.params
543 device_id_list = params.get("device_ids")
544 device_service_tags_list = params.get("device_service_tags")
545 group_service_tags_list = params.get("device_group_names")
546 final_target_list = []
547 if device_id_list or device_service_tags_list:
548 device_id_list, device_capability_map = get_device_ids(module, rest_obj)
549 validate_capability(module, device_capability_map)
550 final_target_list = device_id_list
551 if group_service_tags_list:
552 group_id_list = get_group_ids(module, rest_obj)
553 final_target_list.extend(group_id_list)
554 payload = {
555 "Name": params["names"][0]
556 }
557 if module.params.get("template_id") or module.params.get("template_name"):
558 template = get_template_details(module, rest_obj)
559 payload["TemplateId"] = template["Id"]
560 if module.params.get("description"):
561 payload["Description"] = module.params["description"]
562 if final_target_list:
563 payload["BaselineTargets"] = [{"Id": item} for item in final_target_list]
564 return payload
565
566
567 def get_baseline_compliance_info(rest_obj, baseline_identifier_val, attribute="Id"):
568 """
569 Get the baseline info for the created compliance baseline
570 """
571 data = rest_obj.get_all_items_with_pagination(COMPLIANCE_BASELINE)
572 value = data["value"]
573 baseline_info = {}
574 for item in value:
575 if item[attribute] == baseline_identifier_val:
576 baseline_info = item
577 baseline_info.pop("@odata.type", None)
578 baseline_info.pop("@odata.id", None)
579 baseline_info.pop("[email protected]", None)
580 break
581 return baseline_info
582
583
584 def track_compliance_task_completion(rest_obj, baseline_identifier_val, module):
585 """
586 wait for the compliance configuration task to complete
587 """
588 baseline_info = get_baseline_compliance_info(rest_obj, baseline_identifier_val)
589 command = module.params["command"]
590 if module.params.get("job_wait"):
591 wait_time = 5
592 retries_count_limit = module.params["job_wait_timeout"] / wait_time
593 retries_count = 0
594 time.sleep(wait_time)
595 if command == "create":
596 msg = CREATE_MSG
597 else:
598 msg = MODIFY_MSG
599 while retries_count <= retries_count_limit:
600 if baseline_info["PercentageComplete"] == "100":
601 break
602 retries_count += 1
603 time.sleep(wait_time)
604 baseline_info = get_baseline_compliance_info(rest_obj, baseline_identifier_val)
605 if baseline_info["PercentageComplete"] != "100":
606 msg = TASK_PROGRESS_MSG
607 else:
608 msg = TASK_PROGRESS_MSG
609 return msg, baseline_info
610
611
612 def validate_create_baseline_idempotency(module, rest_obj):
613 """
614 Idempotency check for compliance baseline create.
615 Return error message if baseline name already exists in the system
616 """
617 name = module.params["names"][0]
618 baseline_info = get_baseline_compliance_info(rest_obj, name, attribute="Name")
619 if any(baseline_info):
620 module.exit_json(msg=BASELINE_CHECK_MODE_CHANGE_MSG.format(name=name), compliance_status=baseline_info, changed=False)
621 if not any(baseline_info) and module.check_mode:
622 module.exit_json(msg=CHECK_MODE_CHANGES_MSG, changed=True)
623
624
625 def create_baseline(module, rest_obj):
626 """
627 Create the compliance baseline.
628 update the response by getting compliance info.
629 Note: The response is updated from GET info reason many attribute values are gving null
630 value. which can be retrieved by getting the created compliance info.
631 """
632 payload = create_payload(module, rest_obj)
633 validate_create_baseline_idempotency(module, rest_obj)
634 resp = rest_obj.invoke_request('POST', COMPLIANCE_BASELINE, data=payload)
635 data = resp.json_data
636 compliance_id = data["Id"]
637 baseline_info = get_baseline_compliance_info(rest_obj, compliance_id)
638 if module.params.get("job_wait"):
639 job_failed, message = rest_obj.job_tracking(baseline_info["TaskId"],
640 job_wait_sec=module.params["job_wait_timeout"],
641 sleep_time=5)
642 baseline_updated_info = get_baseline_compliance_info(rest_obj, compliance_id)
643 if job_failed is True:
644 module.exit_json(msg=message, compliance_status=baseline_updated_info, failed=True)
645 else:
646 if "successfully" in message:
647 module.exit_json(msg=CREATE_MSG, compliance_status=baseline_updated_info, changed=True)
648 else:
649 module.exit_json(msg=message, compliance_status=baseline_updated_info, changed=False)
650 else:
651 module.exit_json(msg=TASK_PROGRESS_MSG, compliance_status=baseline_info, changed=True)
652
653
654 def validate_names(command, module):
655 """
656 The command create, remediate and modify doest not supports more than one name
657 """
658 names = module.params["names"]
659 if command != "delete" and len(names) > 1:
660 module.exit_json(msg=NAMES_ERROR, failed=True)
661
662
663 def delete_idempotency_check(module, rest_obj):
664 delete_names = module.params["names"]
665 data = rest_obj.get_all_items_with_pagination(COMPLIANCE_BASELINE)
666 available_baseline_map = dict([(item["Id"], item["Name"]) for item in data["value"]])
667 valid_names = set(delete_names) & set(available_baseline_map.values())
668 valid_id_list = get_identifiers(available_baseline_map, valid_names)
669 if module.check_mode and len(valid_id_list) > 0:
670 module.exit_json(msg=CHECK_MODE_CHANGES_MSG, changed=True)
671 if len(valid_id_list) == 0:
672 module.exit_json(msg=CHECK_MODE_NO_CHANGES_MSG, changed=False)
673 return valid_id_list
674
675
676 def delete_compliance(module, rest_obj):
677 """
678 Deletes the list of baselines
679 """
680 valid_id_list = delete_idempotency_check(module, rest_obj)
681 rest_obj.invoke_request('POST', DELETE_COMPLIANCE_BASELINE, data={"BaselineIds": valid_id_list})
682 module.exit_json(msg=DELETE_MSG, changed=True)
683
684
685 def compare_payloads(modify_payload, current_payload):
686 """
687 :param modify_payload: payload created to update existing setting
688 :param current_payload: already existing payload for specified baseline
689 :return: bool - compare existing and requested setting values of baseline in case of modify operations
690 if both are same return True
691 """
692 diff = False
693 for key, val in modify_payload.items():
694 if current_payload is None or current_payload.get(key) is None:
695 return True
696 elif isinstance(val, dict):
697 if compare_payloads(val, current_payload.get(key)):
698 return True
699 elif val != current_payload.get(key):
700 return True
701 return diff
702
703
704 def idempotency_check_for_command_modify(current_payload, expected_payload, module):
705 """
706 idempotency check in case of modify operation
707 :param current_payload: payload modify
708 :param expected_payload: already existing payload for specified.
709 :param module: ansible module object
710 :return: None
711 """
712 payload_diff = compare_payloads(expected_payload, current_payload)
713 if module.check_mode:
714 if payload_diff:
715 module.exit_json(msg=CHECK_MODE_CHANGES_MSG, changed=True)
716 else:
717 module.exit_json(msg=CHECK_MODE_NO_CHANGES_MSG, changed=False)
718 elif not module.check_mode and not payload_diff:
719 module.exit_json(msg=IDEMPOTENCY_MSG, changed=False)
720
721
722 def modify_baseline(module, rest_obj):
723 name = module.params["names"][0]
724 baseline_info = get_baseline_compliance_info(rest_obj, name, attribute="Name")
725 if not any(baseline_info):
726 module.exit_json(msg=BASELINE_CHECK_MODE_NOCHANGE_MSG.format(name=name), failed=True)
727 current_payload = create_payload(module, rest_obj)
728 current_payload["Id"] = baseline_info["Id"]
729 if module.params.get("new_name"):
730 new_name = module.params.get("new_name")
731 if name != new_name:
732 baseline_info_new = get_baseline_compliance_info(rest_obj, new_name, attribute="Name")
733 if any(baseline_info_new):
734 module.exit_json(msg=BASELINE_CHECK_MODE_CHANGE_MSG.format(name=new_name), failed=True)
735 current_payload["Name"] = new_name
736 required_attributes = ["Id", "Name", "Description", "TemplateId", "BaselineTargets"]
737 existing_payload = dict([(key, val) for key, val in baseline_info.items() if key in required_attributes and val])
738 if existing_payload.get("BaselineTargets"):
739 target = [{"Id": item["Id"]} for item in existing_payload["BaselineTargets"]]
740 existing_payload["BaselineTargets"] = target
741 idempotency_check_for_command_modify(existing_payload, current_payload, module)
742 existing_payload.update(current_payload)
743 baseline_update_uri = COMPLIANCE_BASELINE + "({baseline_id})".format(baseline_id=existing_payload["Id"])
744 resp = rest_obj.invoke_request('PUT', baseline_update_uri, data=existing_payload)
745 data = resp.json_data
746 compliance_id = data["Id"]
747 baseline_info = get_baseline_compliance_info(rest_obj, compliance_id)
748 if module.params.get("job_wait"):
749 job_failed, message = rest_obj.job_tracking(baseline_info["TaskId"],
750 job_wait_sec=module.params["job_wait_timeout"], sleep_time=5)
751 baseline_updated_info = get_baseline_compliance_info(rest_obj, compliance_id)
752 if job_failed is True:
753 module.exit_json(msg=message, compliance_status=baseline_updated_info, failed=True)
754 else:
755 if "successfully" in message:
756 module.exit_json(msg=MODIFY_MSG, compliance_status=baseline_updated_info, changed=True)
757 else:
758 module.exit_json(msg=message, compliance_status=baseline_updated_info, changed=False)
759 else:
760 module.exit_json(msg=TASK_PROGRESS_MSG, compliance_status=baseline_info, changed=True)
761
762
763 def get_ome_version(rest_obj):
764 resp = rest_obj.invoke_request('GET', OME_INFO)
765 data = resp.json_data
766 return data["Version"]
767
768
769 def validate_remediate_idempotency(module, rest_obj):
770 name = module.params["names"][0]
771 baseline_info = get_baseline_compliance_info(rest_obj, name, attribute="Name")
772 if not any(baseline_info):
773 module.exit_json(msg=BASELINE_CHECK_MODE_NOCHANGE_MSG.format(name=name), failed=True)
774 valid_id_list, device_capability_map = get_device_ids(module, rest_obj)
775 compliance_reports = rest_obj.get_all_items_with_pagination(CONFIG_COMPLIANCE_URI.format(baseline_info["Id"]))
776 device_id_list = module.params.get("device_ids")
777 device_service_tags_list = module.params.get("device_service_tags")
778 if device_id_list:
779 compliance_report_map = dict([(item["Id"], item["ComplianceStatus"]) for item in compliance_reports["value"]])
780 if not any(compliance_report_map):
781 module.exit_json(msg=CHECK_MODE_NO_CHANGES_MSG)
782 invalid_values = list(set(device_id_list) - set(compliance_report_map.keys()))
783 if invalid_values:
784 module.exit_json(
785 INVALID_COMPLIANCE_IDENTIFIER.format("device_ids", ",".join(map(str, invalid_values)), name), failed=True)
786 report_devices = list(set(device_id_list) & set(compliance_report_map.keys()))
787 noncomplaint_devices = [device for device in report_devices if compliance_report_map[device] == "NONCOMPLIANT"
788 or compliance_report_map[device] == 2]
789 elif device_service_tags_list:
790 compliance_report_map = dict(
791 [(item["ServiceTag"], item["ComplianceStatus"]) for item in compliance_reports["value"]])
792 if not any(compliance_report_map):
793 module.exit_json(msg=CHECK_MODE_NO_CHANGES_MSG)
794 invalid_values = list(set(device_service_tags_list) - set(compliance_report_map.keys()))
795 if invalid_values:
796 module.exit_json(
797 INVALID_COMPLIANCE_IDENTIFIER.format("device_service_tags", ",".join(map(str, invalid_values)), name), failed=True)
798 report_devices = list(set(device_service_tags_list) & set(compliance_report_map.keys()))
799 service_tag_id_map = dict(
800 [(item["ServiceTag"], item["Id"]) for item in compliance_reports["value"]])
801 noncomplaint_devices = [service_tag_id_map[device] for device in report_devices if compliance_report_map[device] == "NONCOMPLIANT"
802 or compliance_report_map[device] == 2]
803 else:
804 compliance_report_map = dict([(item["Id"], item["ComplianceStatus"]) for item in compliance_reports["value"]])
805 if not any(compliance_report_map):
806 module.exit_json(msg=CHECK_MODE_NO_CHANGES_MSG)
807 noncomplaint_devices = [device for device, compliance_status in compliance_report_map.items() if
808 compliance_status == "NONCOMPLIANT" or compliance_status == 2]
809 if len(noncomplaint_devices) == 0:
810 module.exit_json(msg=CHECK_MODE_NO_CHANGES_MSG)
811 if module.check_mode and noncomplaint_devices:
812 module.exit_json(msg=CHECK_MODE_CHANGES_MSG, changed=True)
813 return noncomplaint_devices, baseline_info
814
815
816 def create_remediate_payload(module, noncomplaint_devices, baseline_info, rest_obj):
817 ome_version = get_ome_version(rest_obj)
818 payload = {
819 "Id": baseline_info.get("Id"),
820 "Schedule": {
821 "RunNow": True,
822 "RunLater": False
823 }
824 }
825 if module.params.get("run_later"):
826 if not validate_cron(module.params.get("cron")):
827 module.exit_json(msg=INVALID_CRON_TIME_MSG, failed=True)
828 validate_time(module, rest_obj)
829 payload['Schedule']['Cron'] = module.params.get("cron")
830 payload['Schedule']['RunNow'] = False
831 payload['Schedule']['RunLater'] = True
832 elif module.params.get("staged_at_reboot"):
833 payload['IsStaged'] = True
834 payload['Schedule'] = {}
835 if LooseVersion(ome_version) >= "3.5":
836 payload["DeviceIds"] = noncomplaint_devices
837 else:
838 payload["TargetIds"] = noncomplaint_devices
839 return payload
840
841
842 def validate_cron(cron_string):
843 cron_pattern = CRON_REGEX
844 return bool(re.match(cron_pattern, cron_string))
845
846
847 def validate_time(module, rest_obj):
848 cron_string = module.params.get("cron")
849 try:
850 cron_dt = datetime.datetime.strptime(cron_string, "%S %M %H %d %m ? %Y")
851 except ValueError:
852 module.exit_json(msg=INVALID_CRON_TIME_MSG, failed=True)
853 job_resp = rest_obj.invoke_request('GET', TIME_URI)
854 job_dict = job_resp.json_data
855 time_string = job_dict['SystemTime']
856 provided_time_dt = datetime.datetime.strptime(time_string, '%Y-%m-%d %H:%M:%S.%f')
857 if provided_time_dt > cron_dt:
858 module.exit_json(msg=PAST_TIME_MSG, failed=True)
859
860
861 def remediate_baseline(module, rest_obj):
862 noncomplaint_devices, baseline_info = validate_remediate_idempotency(module, rest_obj)
863 remediate_payload = create_remediate_payload(module, noncomplaint_devices, baseline_info, rest_obj)
864 resp = rest_obj.invoke_request('POST', REMEDIATE_BASELINE, data=remediate_payload)
865 job_id = resp.json_data
866 if module.params.get("run_later"):
867 schedule_job(module, rest_obj, job_id)
868 if module.params.get("job_wait"):
869 job_failed, message = rest_obj.job_tracking(job_id, job_wait_sec=module.params["job_wait_timeout"])
870 if job_failed is True:
871 detailed_output = rest_obj.get_job_execution_details(job_id)
872 module.exit_json(msg=message, job_id=job_id, job_details=detailed_output, failed=True)
873 else:
874 if "successfully" in message and module.params.get("staged_at_reboot"):
875 module.exit_json(msg=REMEDIATE_STAGED_AT_REBOOT_MSG, job_id=job_id, changed=True)
876 if "successfully" in message:
877 module.exit_json(msg=REMEDIATE_MSG, job_id=job_id, changed=True)
878 else:
879 module.exit_json(msg=message, job_id=job_id, changed=False)
880 else:
881 module.exit_json(msg=TASK_PROGRESS_MSG, job_id=job_id, changed=True)
882
883
884 def schedule_job(module, rest_obj, job_id):
885 time.sleep(5)
886 job_url = JOB_URI.format(job_id=job_id)
887 job_resp = rest_obj.invoke_request('GET', job_url)
888 job_dict = job_resp.json_data
889 job_status = job_dict['JobStatus']['Name']
890 if job_status == "New":
891 module.exit_json(msg=REMEDIATE_SCHEDULE_FAIL_MSG, job_id=job_id, failed=True)
892 if job_status == "Scheduled":
893 module.exit_json(msg=REMEDIATE_SCHEDULE_MSG, job_id=job_id, changed=True)
894
895
896 def validate_job_time(command, module):
897 """
898 The command create, remediate and modify time validation
899 """
900 job_wait = module.params["job_wait"]
901 if command != "delete" and job_wait:
902 job_wait_timeout = module.params["job_wait_timeout"]
903 if job_wait_timeout <= 0:
904 module.exit_json(msg=INVALID_TIME.format(job_wait_timeout), failed=True)
905
906
907 def compliance_operation(module, rest_obj):
908 command = module.params.get("command")
909 validate_names(command, module)
910 validate_job_time(command, module)
911 if command == "create":
912 create_baseline(module, rest_obj)
913 if command == "modify":
914 modify_baseline(module, rest_obj)
915 if command == "delete":
916 delete_compliance(module, rest_obj)
917 if command == "remediate":
918 remediate_baseline(module, rest_obj)
919
920
921 def main():
922 specs = {
923 "command": {"default": "create",
924 "choices": ['create', 'modify', 'delete', 'remediate']},
925 "names": {"required": True, "type": 'list', "elements": 'str'},
926 "template_name": {"type": 'str'},
927 "template_id": {"type": 'int'},
928 "device_ids": {"required": False, "type": 'list', "elements": 'int'},
929 "device_service_tags": {"required": False, "type": 'list', "elements": 'str'},
930 "device_group_names": {"required": False, "type": 'list', "elements": 'str'},
931 "description": {"type": 'str'},
932 "run_later": {"required": False, "type": 'bool'},
933 "cron": {"type": 'str'},
934 "staged_at_reboot": {"required": False, "type": 'bool'},
935 "job_wait": {"required": False, "type": 'bool', "default": True},
936 "job_wait_timeout": {"required": False, "type": 'int', "default": 10800},
937 "new_name": {"type": 'str'},
938 }
939
940 module = OmeAnsibleModule(
941 argument_spec=specs,
942 required_if=[
943 ['command', 'create', ['template_name', 'template_id'], True],
944 ['command', 'remediate', ['device_ids', 'device_service_tags', 'job_wait', 'job_wait_timeout'], True],
945 ['command', 'modify',
946 ['new_name', 'description', 'template_name', 'template_id', 'device_ids', 'device_service_tags',
947 'device_group_names'], True],
948 ],
949 required_together=[('run_later', 'cron')],
950 mutually_exclusive=[
951 ('device_ids', 'device_service_tags'),
952 ('device_ids', 'device_group_names'),
953 ('device_service_tags', 'device_group_names'),
954 ('template_id', 'template_name')],
955
956 supports_check_mode=True)
957 try:
958 with RestOME(module.params, req_session=True) as rest_obj:
959 compliance_operation(module, rest_obj)
960 except HTTPError as err:
961 module.exit_json(msg=str(err), failed=True)
962 except URLError as err:
963 module.exit_json(msg=str(err), unreachable=True)
964 except (IOError, ValueError, TypeError, SSLError, ConnectionError, SSLValidationError, OSError) as err:
965 module.exit_json(msg=str(err), failed=True)
966
967
968 if __name__ == '__main__':
969 main()