Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.12.3
7 # Copyright (C) 2019-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_firmware_baseline
19 short_description: Create, modify, or delete a firmware baseline on OpenManage Enterprise or OpenManage Enterprise Modular
20 description: This module allows to create, modify, or delete a firmware baseline on OpenManage Enterprise or OpenManage Enterprise Modular.
21 version_added: "2.0.0"
22 author:
23 - "Jagadeesh N V(@jagadeeshnv)"
24 - "Kritika Bhateja (@Kritika-Bhateja-03)"
25 - "Sapana Gupta (@sapana05)"
26 extends_documentation_fragment:
27 - dellemc.openmanage.ome_auth_options
28 options:
29 state:
30 description:
31 - C(present) creates or modifies a baseline.
32 - C(absent) deletes an existing baseline.
33 choices:
34 - present
35 - absent
36 default: present
37 type: str
38 version_added: 3.4.0
39 baseline_name:
40 type: str
41 description:
42 - Name of the the baseline.
43 - This option is mutually exclusive with I(baseline_id).
44 baseline_id:
45 type: int
46 description:
47 - ID of the existing baseline.
48 - This option is mutually exclusive with I(baseline_name).
49 version_added: 3.4.0
50 new_baseline_name:
51 description: New name of the baseline.
52 type: str
53 version_added: 3.4.0
54 baseline_description:
55 type: str
56 description:
57 - Description for the baseline being created.
58 catalog_name:
59 type: str
60 description:
61 - Name of the catalog to be associated with the baseline.
62 downgrade_enabled:
63 type: bool
64 description:
65 - Indicates whether firmware downgrade is allowed for the devices in the baseline.
66 - This value will be set to C(true) by default, if not provided during baseline creation.
67 is_64_bit:
68 type: bool
69 description:
70 - Indicates if the repository contains 64-bit DUPs.
71 - This value will be set to C(true) by default, if not provided during baseline creation.
72 device_ids:
73 type: list
74 elements: int
75 description:
76 - List of device IDs.
77 - This option is mutually exclusive with I(device_service_tags) and I(device_group_names).
78 device_service_tags:
79 type: list
80 elements: str
81 description:
82 - List of device service tags.
83 - This option is mutually exclusive with I(device_ids) and I(device_group_names).
84 device_group_names:
85 type: list
86 elements: str
87 description:
88 - List of group names.
89 - This option is mutually exclusive with I(device_ids) and I(device_service_tags).
90 job_wait:
91 description:
92 - Provides the option to wait for job completion.
93 - This option is applicable when I(state) is C(present).
94 type: bool
95 default: true
96 version_added: 3.4.0
97 job_wait_timeout:
98 description:
99 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
100 - This option is applicable when I(job_wait) is C(true).
101 type: int
102 default: 600
103 version_added: 3.4.0
104 filter_no_reboot_required:
105 description:
106 - Select only components with no reboot required allows to create a
107 firmware/driver baseline that consists of only the components of the
108 target devices that don't require a reboot of the target devices.
109 type: bool
110 version_added: 8.1.0
111
112 requirements:
113 - "python >= 3.9.6"
114 notes:
115 - Run this module from a system that has direct access to Dell OpenManage Enterprise or OpenManage Enterprise Modular.
116 - I(device_group_names) option is not applicable for OpenManage Enterprise Modular.
117 - This module supports C(check_mode).
118 '''
119
120 EXAMPLES = r'''
121 ---
122 - name: Create baseline for device IDs
123 dellemc.openmanage.ome_firmware_baseline:
124 hostname: "192.168.0.1"
125 username: "username"
126 password: "password"
127 ca_path: "/path/to/ca_cert.pem"
128 baseline_name: "baseline_name"
129 baseline_description: "baseline_description"
130 catalog_name: "catalog_name"
131 device_ids:
132 - 1010
133 - 2020
134
135 - name: Create baseline for device IDs with no reboot required
136 dellemc.openmanage.ome_firmware_baseline:
137 hostname: "192.168.0.1"
138 username: "username"
139 password: "password"
140 ca_path: "/path/to/ca_cert.pem"
141 baseline_name: "baseline_name"
142 baseline_description: "baseline_description"
143 catalog_name: "catalog_name"
144 filter_no_reboot_required: true
145 device_ids:
146 - 1010
147 - 2020
148
149 - name: Create baseline for servicetags
150 dellemc.openmanage.ome_firmware_baseline:
151 hostname: "192.168.0.1"
152 username: "username"
153 password: "password"
154 ca_path: "/path/to/ca_cert.pem"
155 baseline_name: "baseline_name"
156 baseline_description: "baseline_description"
157 catalog_name: "catalog_name"
158 device_service_tags:
159 - "SVCTAG1"
160 - "SVCTAG2"
161
162 - name: Create baseline for servicetags with no reboot required
163 dellemc.openmanage.ome_firmware_baseline:
164 hostname: "192.168.0.1"
165 username: "username"
166 password: "password"
167 ca_path: "/path/to/ca_cert.pem"
168 baseline_name: "baseline_name"
169 baseline_description: "baseline_description"
170 catalog_name: "catalog_name"
171 filter_no_reboot_required: true
172 device_service_tags:
173 - "SVCTAG1"
174 - "SVCTAG2"
175
176 - name: Create baseline for device groups without job tracking
177 dellemc.openmanage.ome_firmware_baseline:
178 hostname: "192.168.0.1"
179 username: "username"
180 password: "password"
181 ca_path: "/path/to/ca_cert.pem"
182 baseline_name: "baseline_name"
183 baseline_description: "baseline_description"
184 catalog_name: "catalog_name"
185 device_group_names:
186 - "Group1"
187 - "Group2"
188 job_wait: false
189
190 - name: Modify an existing baseline
191 dellemc.openmanage.ome_firmware_baseline:
192 hostname: "192.168.0.1"
193 username: "username"
194 password: "password"
195 ca_path: "/path/to/ca_cert.pem"
196 baseline_name: "existing_baseline_name"
197 new_baseline_name: "new_baseline_name"
198 baseline_description: "new baseline_description"
199 catalog_name: "catalog_other"
200 device_group_names:
201 - "Group3"
202 - "Group4"
203 - "Group5"
204 downgrade_enabled: false
205 is_64_bit: true
206
207 - name: Modify no reboot filter in existing baseline
208 dellemc.openmanage.ome_firmware_baseline:
209 hostname: "192.168.0.1"
210 username: "username"
211 password: "password"
212 ca_path: "/path/to/ca_cert.pem"
213 baseline_name: "existing_baseline_name"
214 new_baseline_name: "new_baseline_name"
215 filter_no_reboot_required: true
216
217 - name: Delete a baseline
218 dellemc.openmanage.ome_firmware_baseline:
219 hostname: "192.168.0.1"
220 username: "username"
221 password: "password"
222 ca_path: "/path/to/ca_cert.pem"
223 state: absent
224 baseline_name: "baseline_name"
225 '''
226
227 RETURN = r'''
228 ---
229 msg:
230 description: Overall status of the firmware baseline operation.
231 returned: always
232 type: str
233 sample: "Successfully created the firmware baseline."
234 baseline_status:
235 description: Details of the baseline status.
236 returned: success
237 type: dict
238 sample: {
239 "CatalogId": 123,
240 "Description": "BASELINE DESCRIPTION",
241 "DeviceComplianceReports": [],
242 "DowngradeEnabled": true,
243 "FilterNoRebootRequired": true,
244 "Id": 23,
245 "Is64Bit": true,
246 "Name": "my_baseline",
247 "RepositoryId": 123,
248 "RepositoryName": "catalog123",
249 "RepositoryType": "HTTP",
250 "Targets": [
251 {
252 "Id": 10083,
253 "Type": {
254 "Id": 1000,
255 "Name": "DEVICE"
256 }
257 },
258 {
259 "Id": 10076,
260 "Type": {
261 "Id": 1000,
262 "Name": "DEVICE"
263 }
264 }
265 ],
266 "TaskId": 11235,
267 "TaskStatusId": 2060
268 }
269 job_id:
270 description: Job ID of the baseline task.
271 returned: When baseline job is in running state
272 type: int
273 sample: 10123
274 baseline_id:
275 description: ID of the deleted baseline.
276 returned: When I(state) is C(absent)
277 type: int
278 sample: 10123
279 error_info:
280 type: dict
281 description: Details of http error.
282 returned: on http error
283 sample: {
284 "error": {
285 "@Message.ExtendedInfo": [
286 {
287 "Message": "Unable to retrieve baseline list either because the device ID(s) entered are invalid",
288 "Resolution": "Make sure the entered device ID(s) are valid and retry the operation.",
289 "Severity": "Critical"
290 }
291 ],
292 "code": "Base.1.0.GeneralError",
293 "message": "A general error has occurred. See ExtendedInfo for more information."
294 }
295 }
296 '''
297
298 BASELINE_URI = "UpdateService/Baselines"
299 ID_BASELINE_URI = "UpdateService/Baselines({Id})"
300 DELETE_BASELINE_URI = "UpdateService/Actions/UpdateService.RemoveBaselines"
301 CATALOG_URI = "UpdateService/Catalogs"
302 BASELINE_JOB_RUNNING = "Firmware baseline '{name}' with ID {id} is running. Please retry after job completion."
303 BASELINE_DEL_SUCCESS = "Successfully deleted the firmware baseline."
304 NO_CHANGES_MSG = "No changes found to be applied."
305 CHANGES_FOUND = "Changes found to be applied."
306 INVALID_BASELINE_ID = "Invalid baseline ID provided."
307 BASELINE_TRIGGERED = "Successfully triggered the firmware baseline task."
308 NO_CATALOG_MESSAGE = "Catalog name not provided for baseline creation."
309 NO_TARGETS_MESSAGE = "Targets not specified for baseline creation."
310 CATALOG_STATUS_MESSAGE = "Unable to create the firmware baseline as the catalog is in {status} status."
311 BASELINE_UPDATED = "Successfully {op} the firmware baseline."
312 SETTLING_TIME = 3
313 JOB_POLL_INTERVAL = 10
314 GROUP_ID = 6000
315
316
317 import json
318 import time
319 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
320 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
321 from ansible.module_utils.urls import ConnectionError, SSLValidationError
322 from ansible.module_utils.common.dict_transformations import recursive_diff
323
324
325 def get_baseline_from_name(rest_obj, baseline):
326 resp = rest_obj.get_all_items_with_pagination(BASELINE_URI)
327 baselines_list = resp.get("value")
328 bsln = baseline
329 for d in baselines_list:
330 if d['Name'] == baseline.get('Name'):
331 bsln = d
332 break
333 nlist = list(bsln)
334 for k in nlist:
335 if str(k).lower().startswith('@odata'):
336 bsln.pop(k)
337 return bsln
338
339
340 def check_existing_baseline(module, rest_obj):
341 baseline_id = module.params.get("baseline_id")
342 srch_key = "Name"
343 srch_val = module.params.get("baseline_name")
344 if baseline_id:
345 srch_key = "Id"
346 srch_val = module.params.get("baseline_id")
347 baseline_cfgs = []
348 resp = rest_obj.get_all_items_with_pagination(BASELINE_URI)
349 baselines = resp.get("value")
350 for d in baselines:
351 if d[srch_key] == srch_val:
352 baseline_cfgs.append(d)
353 if baseline_id:
354 break
355 return baseline_cfgs
356
357
358 def get_catrepo_ids(module, cat_name, rest_obj):
359 if cat_name is not None:
360 resp_data = rest_obj.get_all_items_with_pagination(CATALOG_URI)
361 values = resp_data["value"]
362 if values:
363 for catalog in values:
364 repo = catalog.get("Repository")
365 if repo.get("Name") == cat_name:
366 if catalog.get('Status') != 'Completed':
367 module.exit_json(msg=CATALOG_STATUS_MESSAGE.format(status=catalog.get('Status')), failed=True)
368 return catalog.get("Id"), repo.get("Id")
369 return None, None
370
371
372 def get_dev_ids(module, rest_obj, param, devkey):
373 paramlist = module.params[param]
374 resp_data = rest_obj.get_all_items_with_pagination("DeviceService/Devices")
375 values = resp_data["value"]
376 targets = []
377 if values:
378 devlist = values
379 device_resp = {device[devkey]: device for device in devlist}
380 for st in paramlist:
381 if st in device_resp:
382 djson = device_resp[st]
383 target = {}
384 device_type = {}
385 device_type['Id'] = djson['Type']
386 device_type['Name'] = "DEVICE"
387 target['Id'] = djson['Id']
388 target['Type'] = device_type
389 targets.append(target)
390 else:
391 module.exit_json(msg="Unable to complete the operation because the entered target"
392 " {0} '{1}' is invalid.".format(devkey, st), failed=True)
393 return targets
394
395
396 def get_group_ids(module, rest_obj):
397 grp_name_list = module.params.get("device_group_names")
398 resp_data = rest_obj.get_all_items_with_pagination("GroupService/Groups")
399 values = resp_data["value"]
400 targets = []
401 if values:
402 grplist = values
403 device_resp = {str(grp['Name']): grp for grp in grplist}
404 for st in grp_name_list:
405 if st in device_resp:
406 djson = device_resp[st]
407 target = {}
408 device_type = {}
409 device_type['Id'] = GROUP_ID
410 device_type['Name'] = "GROUP"
411 target['Id'] = djson['Id']
412 target['Type'] = device_type
413 targets.append(target)
414 else:
415 module.exit_json(msg="Unable to complete the operation because the entered target"
416 " Group Name '{0}' is invalid.".format(st), failed=True)
417 return targets
418
419
420 def get_target_list(module, rest_obj):
421 target_list = None
422 if module.params.get("device_service_tags"):
423 target_list = get_dev_ids(module, rest_obj, "device_service_tags", "DeviceServiceTag")
424 elif module.params.get("device_group_names"):
425 target_list = get_group_ids(module, rest_obj)
426 elif module.params.get("device_ids"):
427 target_list = get_dev_ids(module, rest_obj, "device_ids", "Id")
428 return target_list
429
430
431 def exit_baseline(module, rest_obj, baseline, op):
432 msg = BASELINE_TRIGGERED
433 time.sleep(SETTLING_TIME)
434 try:
435 bsln = get_baseline_from_name(rest_obj, baseline)
436 except Exception:
437 bsln = baseline
438 if module.params.get("job_wait"):
439 job_failed, job_message = rest_obj.job_tracking(
440 baseline.get('TaskId'), job_wait_sec=module.params["job_wait_timeout"], sleep_time=JOB_POLL_INTERVAL)
441 if job_failed is True:
442 module.exit_json(msg=job_message, baseline_status=bsln, failed=True)
443 msg = BASELINE_UPDATED.format(op=op)
444 module.exit_json(msg=msg, baseline_status=bsln, changed=True)
445
446
447 def _get_baseline_payload(module, rest_obj):
448 cat_name = module.params.get("catalog_name")
449 cat_id, repo_id = get_catrepo_ids(module, cat_name, rest_obj)
450 if cat_id is None or repo_id is None:
451 module.exit_json(msg="No Catalog with name {0} found".format(cat_name), failed=True)
452 targets = get_target_list(module, rest_obj)
453 if targets is None:
454 module.exit_json(msg=NO_TARGETS_MESSAGE, failed=True)
455 baseline_name = module.params.get("baseline_name")
456 baseline_payload = {
457 "Name": baseline_name,
458 "CatalogId": cat_id,
459 "RepositoryId": repo_id,
460 "Targets": targets
461 }
462 baseline_payload['Description'] = module.params.get("baseline_description")
463 baseline_payload['FilterNoRebootRequired'] = module.params.get("filter_no_reboot_required")
464 de = module.params.get("downgrade_enabled")
465 baseline_payload['DowngradeEnabled'] = de if de is not None else True
466 sfb = module.params.get("is_64_bit")
467 baseline_payload['Is64Bit'] = sfb if sfb is not None else True
468 return baseline_payload
469
470
471 def create_baseline(module, rest_obj):
472 myparams = module.params
473 if not any([myparams.get("device_ids"), myparams.get("device_service_tags"), myparams.get("device_group_names")]):
474 module.exit_json(msg=NO_TARGETS_MESSAGE, failed=True)
475 if not myparams.get("catalog_name"):
476 module.exit_json(msg=NO_CATALOG_MESSAGE, failed=True)
477 payload = _get_baseline_payload(module, rest_obj)
478 if module.check_mode:
479 module.exit_json(msg=CHANGES_FOUND, changed=True)
480 resp = rest_obj.invoke_request("POST", BASELINE_URI, data=payload)
481 exit_baseline(module, rest_obj, resp.json_data, 'created')
482
483
484 def update_modify_payload(module, rest_obj, modify_payload, current_baseline):
485 paylist = ['Name', "CatalogId", "RepositoryId", 'Description', 'DowngradeEnabled', 'Is64Bit',
486 'FilterNoRebootRequired']
487 diff_tuple = recursive_diff(modify_payload, current_baseline)
488 diff = 0
489 payload = {item: current_baseline.get(item) for item in paylist}
490 try:
491 if diff_tuple and diff_tuple[0]:
492 diff += 1
493 payload.update(diff_tuple[0])
494 payload['Targets'] = current_baseline.get('Targets', [])
495 inp_targets_list = get_target_list(module, rest_obj)
496 if inp_targets_list:
497 inp_target_dict = {item['Id']: item['Type']['Id'] for item in inp_targets_list}
498 cur_target_dict = {item['Id']: item['Type']['Id'] for item in current_baseline.get('Targets', [])}
499 diff_tuple = recursive_diff(inp_target_dict, cur_target_dict)
500 if diff_tuple:
501 diff += 1
502 payload['Targets'] = inp_targets_list
503 if diff == 0:
504 module.exit_json(msg=NO_CHANGES_MSG)
505 payload['Id'] = current_baseline['Id']
506 except (IndexError, TypeError) as err:
507 module.exit_json(msg=str(err), failed=True)
508 return payload
509
510
511 def modify_baseline(module, rest_obj, baseline_list):
512 d = baseline_list[0]
513 if d["TaskStatusId"] == 2050:
514 module.exit_json(msg=BASELINE_JOB_RUNNING.format(name=d["Name"], id=d["Id"]), job_id=d['TaskId'], failed=True)
515 mparam = module.params
516 current_baseline = baseline_list[0]
517 modify_payload = {}
518 if mparam.get('catalog_name'):
519 cat_id, repo_id = get_catrepo_ids(module, mparam.get('catalog_name'), rest_obj)
520 if cat_id is None or repo_id is None:
521 module.exit_json(msg="No Catalog with name {0} found".format(mparam.get('catalog_name')), failed=True)
522 modify_payload["CatalogId"] = cat_id
523 modify_payload["RepositoryId"] = repo_id
524 if mparam.get('new_baseline_name'):
525 modify_payload['Name'] = mparam.get('new_baseline_name')
526 if mparam.get("baseline_description"):
527 modify_payload['Description'] = mparam.get("baseline_description")
528 if module.params.get("downgrade_enabled") is not None:
529 modify_payload['DowngradeEnabled'] = module.params.get("downgrade_enabled")
530 if module.params.get("is_64_bit") is not None:
531 modify_payload['Is64Bit'] = module.params.get("is_64_bit")
532 if module.params.get("filter_no_reboot_required") is not None:
533 modify_payload['FilterNoRebootRequired'] = module.params.get("filter_no_reboot_required")
534 payload = update_modify_payload(module, rest_obj, modify_payload, current_baseline)
535 if module.check_mode:
536 module.exit_json(msg=CHANGES_FOUND, changed=True)
537 resp = rest_obj.invoke_request("PUT", ID_BASELINE_URI.format(Id=str(payload["Id"])), data=payload)
538 exit_baseline(module, rest_obj, resp.json_data, 'modified')
539
540
541 def delete_baseline(module, rest_obj, baseline_list):
542 delete_ids = []
543 d = baseline_list[0]
544 if d["TaskStatusId"] == 2050:
545 module.exit_json(msg=BASELINE_JOB_RUNNING.format(name=d["Name"], id=d["Id"]), job_id=d['TaskId'], failed=True)
546 delete_ids.append(d["Id"])
547 delete_payload = {"BaselineIds": delete_ids}
548 if module.check_mode:
549 module.exit_json(msg=CHANGES_FOUND, changed=True)
550 rest_obj.invoke_request('POST', DELETE_BASELINE_URI, data=delete_payload)
551 module.exit_json(msg=BASELINE_DEL_SUCCESS, changed=True, baseline_id=delete_ids[0])
552
553
554 def main():
555 specs = {
556 "state": {"default": "present", "choices": ['present', 'absent']},
557 "baseline_name": {"type": 'str'},
558 "baseline_id": {"type": 'int'},
559 "baseline_description": {"type": 'str'},
560 "new_baseline_name": {"type": 'str'},
561 "catalog_name": {"type": 'str'},
562 "downgrade_enabled": {"type": 'bool'},
563 "is_64_bit": {"type": 'bool'},
564 "device_ids": {"type": 'list', "elements": 'int'},
565 "device_service_tags": {"type": 'list', "elements": 'str'},
566 "device_group_names": {"type": 'list', "elements": 'str'},
567 "job_wait": {"type": 'bool', "default": True},
568 "job_wait_timeout": {"type": 'int', "default": 600},
569 "filter_no_reboot_required": {"type": 'bool'}
570 }
571
572 module = OmeAnsibleModule(
573 argument_spec=specs,
574 mutually_exclusive=[
575 ('device_ids', 'device_service_tags', 'device_group_names'),
576 ('baseline_name', 'baseline_id')
577 ],
578 required_one_of=[('baseline_name', 'baseline_id')],
579 supports_check_mode=True)
580
581 try:
582 with RestOME(module.params, req_session=True) as rest_obj:
583 baseline_list = check_existing_baseline(module, rest_obj)
584 if module.params.get('state') == 'absent':
585 if baseline_list:
586 delete_baseline(module, rest_obj, baseline_list)
587 module.exit_json(msg=NO_CHANGES_MSG)
588 else:
589 if baseline_list:
590 modify_baseline(module, rest_obj, baseline_list)
591 else:
592 if module.params.get('baseline_id'):
593 module.exit_json(msg=INVALID_BASELINE_ID, failed=True)
594 create_baseline(module, rest_obj)
595 except HTTPError as err:
596 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
597 except URLError as err:
598 module.exit_json(msg=str(err), unreachable=True)
599 except (IOError, ValueError, TypeError, ConnectionError, SSLValidationError, OSError) as err:
600 module.exit_json(msg=str(err), failed=True)
601
602
603 if __name__ == '__main__':
604 main()