Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_firmware.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) 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
19 short_description: Update firmware on PowerEdge devices and its components through OpenManage Enterprise
20 version_added: "2.0.0"
21 description: This module updates the firmware of PowerEdge devices and all its components through OpenManage Enterprise.
22 extends_documentation_fragment:
23 - dellemc.openmanage.ome_auth_options
24 options:
25 device_service_tag:
26 description:
27 - List of service tags of the targeted devices.
28 - Either I(device_id) or I(device_service_tag) can be used individually or together.
29 - This option is mutually exclusive with I(device_group_names) and I(devices).
30 type: list
31 elements: str
32 device_id:
33 description:
34 - List of ids of the targeted device.
35 - Either I(device_id) or I(device_service_tag) can be used individually or together.
36 - This option is mutually exclusive with I(device_group_names) and I(devices).
37 type: list
38 elements: int
39 device_group_names:
40 description:
41 - Enter the name of the device group that contains the devices on which firmware needs to be updated.
42 - This option is mutually exclusive with I(device_id) and I(device_service_tag).
43 type: list
44 elements: str
45 dup_file:
46 description:
47 - "The path of the Dell Update Package (DUP) file that contains the firmware or drivers required to update the
48 target system device or individual device components."
49 - This is mutually exclusive with I(baseline_name), I(components), and I(devices).
50 type: path
51 baseline_name:
52 description:
53 - Enter the baseline name to update the firmware of all devices or list of devices that are not complaint.
54 - This option is mutually exclusive with I(dup_file) and I(device_group_names).
55 type: str
56 components:
57 description:
58 - List of components to be updated.
59 - If not provided, all components applicable are considered.
60 - This option is case sensitive.
61 - This is applicable to I(device_service_tag), I(device_id), and I(baseline_name).
62 type: list
63 default: []
64 elements: str
65 devices:
66 description:
67 - This option allows to select components on each device for firmware update.
68 - This option is mutually exclusive with I(dup_file), I(device_group_names), I(device_id), and I(device_service_tag).
69 type: list
70 elements: dict
71 suboptions:
72 id:
73 type: int
74 description:
75 - The id of the target device to be updated.
76 - This option is mutually exclusive with I(service_tag).
77 service_tag:
78 type: str
79 description:
80 - The service tag of the target device to be updated.
81 - This option is mutually exclusive with I(id).
82 components:
83 description: The target components to be updated. If not specified, all applicable device components are considered.
84 type: list
85 default: []
86 elements: str
87 schedule:
88 type: str
89 description:
90 - Select the schedule for the firmware update.
91 - if C(StageForNextReboot) is chosen, the firmware will be staged and updated during the next reboot
92 of the target device.
93 - if C(RebootNow) will apply the firmware updates immediately.
94 choices:
95 - RebootNow
96 - StageForNextReboot
97 default: RebootNow
98 reboot_type:
99 version_added: '8.3.0'
100 type: str
101 description:
102 - This option provides the choices to reboot the server immediately after the firmware update.
103 - This is applicable when I(schedule) is C(RebootNow).
104 - C(GracefulRebootForce) performs a graceful reboot with forced shutdown.
105 - C(GracefulReboot) performs a graceful reboot without forced shutdown.
106 - C(PowerCycle) performs a power cycle for a hard reset on the device.
107 choices:
108 - GracefulReboot
109 - GracefulRebootForce
110 - PowerCycle
111 default: GracefulRebootForce
112 requirements:
113 - "python >= 3.9.6"
114 author:
115 - "Felix Stephen (@felixs88)"
116 - "Jagadeesh N V (@jagadeeshnv)"
117 - "Abhishek Sinha (@ABHISHEK-SINHA10)"
118 notes:
119 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
120 - This module supports C(check_mode).
121 '''
122
123 EXAMPLES = r'''
124 ---
125 - name: Update firmware from DUP file using device ids
126 dellemc.openmanage.ome_firmware:
127 hostname: "192.168.0.1"
128 username: "username"
129 password: "password"
130 ca_path: "/path/to/ca_cert.pem"
131 device_id:
132 - 11111
133 - 22222
134 dup_file: "/path/Chassis-System-Management_Firmware_6N9WN_WN64_1.00.01_A00.EXE"
135
136 - name: Update firmware from a DUP file using a device service tags
137 dellemc.openmanage.ome_firmware:
138 hostname: "192.168.0.1"
139 username: "username"
140 password: "password"
141 ca_path: "/path/to/ca_cert.pem"
142 device_service_tag:
143 - KLBR111
144 - KLBR222
145 dup_file: "/path/Network_Firmware_NTRW0_WN64_14.07.07_A00-00_01.EXE"
146
147 - name: Update firmware from a DUP file using a device group names
148 dellemc.openmanage.ome_firmware:
149 hostname: "192.168.0.1"
150 username: "username"
151 password: "password"
152 ca_path: "/path/to/ca_cert.pem"
153 device_group_names:
154 - servers
155 dup_file: "/path/BIOS_87V69_WN64_2.4.7.EXE"
156
157 - name: Update firmware using baseline name
158 dellemc.openmanage.ome_firmware:
159 hostname: "192.168.0.1"
160 username: "username"
161 password: "password"
162 ca_path: "/path/to/ca_cert.pem"
163 baseline_name: baseline_devices
164
165 - name: Stage firmware for the next reboot using baseline name
166 dellemc.openmanage.ome_firmware:
167 hostname: "192.168.0.1"
168 username: "username"
169 password: "password"
170 ca_path: "/path/to/ca_cert.pem"
171 baseline_name: baseline_devices
172 schedule: StageForNextReboot
173
174 - name: "Update firmware using baseline name and components."
175 dellemc.openmanage.ome_firmware:
176 hostname: "192.168.0.1"
177 username: "username"
178 password: "password"
179 ca_path: "/path/to/ca_cert.pem"
180 baseline_name: baseline_devices
181 components:
182 - BIOS
183
184 - name: Update firmware of device components from a DUP file using a device ids in a baseline
185 dellemc.openmanage.ome_firmware:
186 hostname: "192.168.0.1"
187 username: "username"
188 password: "password"
189 ca_path: "/path/to/ca_cert.pem"
190 baseline_name: baseline_devices
191 device_id:
192 - 11111
193 - 22222
194 components:
195 - iDRAC with Lifecycle Controller
196
197 - name: Update firmware of device components from a baseline using a device service tags under a baseline
198 dellemc.openmanage.ome_firmware:
199 hostname: "192.168.0.1"
200 username: "username"
201 password: "password"
202 ca_path: "/path/to/ca_cert.pem"
203 baseline_name: baseline_devices
204 device_service_tag:
205 - KLBR111
206 - KLBR222
207 components:
208 - IOM-SAS
209
210 - name: Update firmware using baseline name with a device id and required components
211 dellemc.openmanage.ome_firmware:
212 hostname: "192.168.0.1"
213 username: "username"
214 password: "password"
215 ca_path: "/path/to/ca_cert.pem"
216 baseline_name: baseline_devices
217 devices:
218 - id: 12345
219 components:
220 - Lifecycle Controller
221 - id: 12346
222 components:
223 - Enterprise UEFI Diagnostics
224 - BIOS
225
226 - name: "Update firmware using baseline name with a device service tag and required components."
227 dellemc.openmanage.ome_firmware:
228 hostname: "192.168.0.1"
229 username: "username"
230 password: "password"
231 ca_path: "/path/to/ca_cert.pem"
232 baseline_name: baseline_devices
233 devices:
234 - service_tag: ABCDE12
235 components:
236 - PERC H740P Adapter
237 - BIOS
238 - service_tag: GHIJK34
239 components:
240 - OS Drivers Pack
241
242 - name: "Update firmware using baseline name with a device service tag or device id and required components."
243 dellemc.openmanage.ome_firmware:
244 hostname: "192.168.0.1"
245 username: "username"
246 password: "password"
247 ca_path: "/path/to/ca_cert.pem"
248 baseline_name: baseline_devices
249 devices:
250 - service_tag: ABCDE12
251 components:
252 - BOSS-S1 Adapter
253 - PowerEdge Server BIOS
254 - id: 12345
255 components:
256 - iDRAC with Lifecycle Controller
257
258 - name: "Update firmware using baseline name and components and perform Powercycle."
259 dellemc.openmanage.ome_firmware:
260 hostname: "192.168.0.1"
261 username: "username"
262 password: "password"
263 ca_path: "/path/to/ca_cert.pem"
264 baseline_name: baseline_devices
265 components:
266 - BIOS
267 reboot_type: PowerCycle
268 '''
269
270 RETURN = r'''
271 ---
272 msg:
273 type: str
274 description: "Overall firmware update status."
275 returned: always
276 sample: Successfully submitted the firmware update job.
277 update_status:
278 type: dict
279 description: The firmware update job and progress details from the OME.
280 returned: success
281 sample: {
282 'LastRun': None,
283 'CreatedBy': 'user',
284 'Schedule': 'startnow',
285 'LastRunStatus': {
286 'Id': 1111,
287 'Name': 'NotRun'
288 },
289 'Builtin': False,
290 'Editable': True,
291 'NextRun': None,
292 'JobStatus': {
293 'Id': 1111,
294 'Name': 'New'
295 },
296 'JobName': 'Firmware Update Task',
297 'Visible': True,
298 'State': 'Enabled',
299 'JobDescription': 'dup test',
300 'Params': [{
301 'Value': 'true',
302 'Key': 'signVerify',
303 'JobId': 11111}, {
304 'Value': 'false',
305 'Key': 'stagingValue',
306 'JobId': 11112}, {
307 'Value': 'false',
308 'Key': 'complianceUpdate',
309 'JobId': 11113}, {
310 'Value': 'INSTALL_FIRMWARE',
311 'Key': 'operationName',
312 'JobId': 11114}],
313 'Targets': [{
314 'TargetType': {
315 'Id': 1000,
316 'Name': 'DEVICE'},
317 'Data': 'DCIM:INSTALLED#701__NIC.Mezzanine.1A-1-1=1234567654321',
318 'Id': 11115,
319 'JobId': 11116}],
320 'StartTime': None,
321 'UpdatedBy': None,
322 'EndTime': None,
323 'Id': 11117,
324 'JobType': {
325 'Internal': False,
326 'Id': 5,
327 'Name': 'Update_Task'}
328 }
329 error_info:
330 description: Details of the HTTP Error.
331 returned: on HTTP error
332 type: dict
333 sample: {
334 "error": {
335 "code": "Base.1.0.GeneralError",
336 "message": "A general error has occurred. See ExtendedInfo for more information.",
337 "@Message.ExtendedInfo": [
338 {
339 "MessageId": "GEN1234",
340 "RelatedProperties": [],
341 "Message": "Unable to process the request because an error occurred.",
342 "MessageArgs": [],
343 "Severity": "Critical",
344 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
345 }
346 ]
347 }
348 }
349 '''
350
351
352 import json
353 from ssl import SSLError
354 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
355 from ansible.module_utils.urls import ConnectionError
356 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
357
358
359 COMPLIANCE_URI = "UpdateService/Baselines({0})/DeviceComplianceReports"
360 BASELINE_URI = "UpdateService/Baselines"
361 FW_JOB_DESC = "Firmware update task initiated from OpenManage Ansible Module collections"
362 NO_CHANGES_MSG = "No changes found to be applied. Either there are no updates present or components specified are not" \
363 " found in the baseline."
364 COMPLIANCE_READ_FAIL = "Failed to read compliance report."
365 DUP_REQ_MSG = "Parameter 'dup_file' to be provided along with 'device_id'|'device_service_tag'|'device_group_names'"
366 APPLICABLE_DUP = "Unable to get applicable components DUP."
367 CHANGES_FOUND = "Changes found to be applied."
368
369
370 def spawn_update_job(rest_obj, job_payload):
371 """Spawns an update job and tracks it to completion."""
372 job_uri, job_details = "JobService/Jobs", {}
373 job_resp = rest_obj.invoke_request("POST", job_uri, data=job_payload)
374 if job_resp.status_code == 201:
375 job_details = job_resp.json_data
376 return job_details
377
378
379 def job_payload_for_update(rest_obj, module, target_data, baseline=None):
380 """Formulate the payload to initiate a firmware update job."""
381 resp = rest_obj.get_job_type_id("Update_Task")
382 if resp is None:
383 module.exit_json(msg="Unable to fetch the job type Id.", failed=True)
384 stage_dict = {"StageForNextReboot": 'true', "RebootNow": 'false'}
385 schedule = module.params["schedule"]
386 params = [{"Key": "operationName", "Value": "INSTALL_FIRMWARE"},
387 {"Key": "stagingValue", "Value": stage_dict[schedule]},
388 {"Key": "signVerify", "Value": "true"}]
389 # reboot applicable only if staging false
390 if schedule == "RebootNow":
391 reboot_dict = {"PowerCycle": "1",
392 "GracefulReboot": "2",
393 "GracefulRebootForce": "3"}
394 reboot_type = module.params["reboot_type"]
395 params.append({"Key": "rebootType", "Value": reboot_dict[reboot_type]})
396 payload = {
397 "Id": 0, "JobName": "Firmware Update Task",
398 "JobDescription": FW_JOB_DESC, "Schedule": "startnow",
399 "State": "Enabled", "JobType": {"Id": resp, "Name": "Update_Task"},
400 "Targets": target_data,
401 "Params": params
402 }
403
404 if baseline is not None:
405 payload["Params"].append({"Key": "complianceReportId", "Value": "{0}".format(baseline["baseline_id"])})
406 payload["Params"].append({"Key": "repositoryId", "Value": "{0}".format(baseline["repo_id"])})
407 payload["Params"].append({"Key": "catalogId", "Value": "{0}".format(baseline["catalog_id"])})
408 payload["Params"].append({"Key": "complianceUpdate", "Value": "true"})
409 else:
410 payload["Params"].append({"JobId": 0, "Key": "complianceUpdate", "Value": "false"})
411 return payload
412
413
414 def get_applicable_components(rest_obj, dup_payload, module):
415 """Get the target array to be used in spawning jobs for update."""
416 target_data = []
417 dup_url = "UpdateService/Actions/UpdateService.GetSingleDupReport"
418 headers = {"Content-Type": "application/json", "Accept": "application/json"}
419 dup_resp = rest_obj.invoke_request("POST", dup_url, data=dup_payload,
420 headers=headers, api_timeout=60)
421 if dup_resp.status_code == 200:
422 dup_data = dup_resp.json_data
423 file_token = str(dup_payload['SingleUpdateReportFileToken'])
424 for device in dup_data:
425 for component in device['DeviceReport']['Components']:
426 temp_map = {}
427 temp_map['Id'] = device['DeviceId']
428 temp_map['Data'] = "{0}={1}".format(component['ComponentSourceName'], file_token)
429 temp_map['TargetType'] = {}
430 temp_map['TargetType']['Id'] = int(device['DeviceReport']['DeviceTypeId'])
431 temp_map['TargetType']['Name'] = str(device['DeviceReport']['DeviceTypeName'])
432 target_data.append(temp_map)
433 else:
434 module.exit_json(msg=APPLICABLE_DUP, failed=True)
435 return target_data
436
437
438 def get_dup_applicability_payload(file_token, device_ids=None, group_ids=None, baseline_ids=None):
439 """Returns the DUP applicability JSON payload."""
440 dup_applicability_payload = {'SingleUpdateReportBaseline': [],
441 'SingleUpdateReportGroup': [],
442 'SingleUpdateReportTargets': [],
443 'SingleUpdateReportFileToken': file_token}
444 if device_ids is not None:
445 dup_applicability_payload.update({"SingleUpdateReportTargets": list(map(int, device_ids))})
446 elif group_ids is not None:
447 dup_applicability_payload.update({"SingleUpdateReportGroup": list(map(int, group_ids))})
448 elif baseline_ids is not None:
449 dup_applicability_payload.update({"SingleUpdateReportBaseline": list(map(int, baseline_ids))})
450 return dup_applicability_payload
451
452
453 def upload_dup_file(rest_obj, module):
454 """Upload DUP file to OME and get a file token."""
455 upload_uri = "UpdateService/Actions/UpdateService.UploadFile"
456 headers = {"Content-Type": "application/octet-stream", "Accept": "application/octet-stream"}
457 upload_success, token = False, None
458 dup_file = module.params['dup_file']
459 with open(dup_file, 'rb') as payload:
460 payload = payload.read()
461 response = rest_obj.invoke_request("POST", upload_uri, data=payload, headers=headers,
462 api_timeout=100, dump=False)
463 if response.status_code == 200:
464 upload_success = True
465 token = str(response.json_data)
466 else:
467 module.exit_json(msg="Unable to upload {0} to {1}".format(dup_file, module.params['hostname']), failed=True)
468 return upload_success, token
469
470
471 def get_device_ids(rest_obj, module, device_id_tags):
472 """Getting the list of device ids filtered from the device inventory."""
473 device_id = []
474 resp = rest_obj.get_all_report_details("DeviceService/Devices")
475 if resp.get("report_list"):
476 device_resp = dict([(str(device['Id']), device['DeviceServiceTag']) for device in resp["report_list"]])
477 device_tags = map(str, device_id_tags)
478 invalid_tags = []
479 for tag in device_tags:
480 if tag in device_resp.keys():
481 device_id.append(tag)
482 elif tag in device_resp.values():
483 ids = list(device_resp.keys())[list(device_resp.values()).index(tag)]
484 device_id.append(ids)
485 else:
486 invalid_tags.append(tag)
487 if invalid_tags:
488 module.exit_json(
489 msg="Unable to complete the operation because the entered target device service"
490 " tag(s) or device id(s) '{0}' are invalid.".format(",".join(set(invalid_tags))), failed=True)
491 else:
492 module.exit_json(msg="Failed to fetch the device facts.", failed=True)
493 return device_id, device_resp
494
495
496 def get_group_ids(rest_obj, module):
497 """Getting the list of group ids filtered from the groups."""
498 resp = rest_obj.get_all_report_details("GroupService/Groups")
499 group_name = module.params.get('device_group_names')
500 if resp["report_list"]:
501 grp_ids = [grp['Id'] for grp in resp["report_list"] for grpname in group_name if grp['Name'] == grpname]
502 if len(set(group_name)) != len(set(grp_ids)):
503 module.exit_json(
504 msg="Unable to complete the operation because the entered target device group name(s)"
505 " '{0}' are invalid.".format(",".join(set(group_name))), failed=True)
506 return grp_ids
507
508
509 def get_baseline_ids(rest_obj, module):
510 """Getting the list of group ids filtered from the groups."""
511 resp = rest_obj.get_all_report_details(BASELINE_URI)
512 baseline, baseline_details = module.params.get('baseline_name'), {}
513 if resp["report_list"]:
514 for bse in resp["report_list"]:
515 if bse['Name'] == baseline:
516 baseline_details["baseline_id"] = bse["Id"]
517 baseline_details["repo_id"] = bse["RepositoryId"]
518 baseline_details["catalog_id"] = bse["CatalogId"]
519 if not baseline_details:
520 module.exit_json(
521 msg="Unable to complete the operation because the entered target baseline name"
522 " '{0}' is invalid.".format(baseline), failed=True)
523 else:
524 module.exit_json(msg="Unable to complete the operation because the entered "
525 "target baseline name does not exist.", failed=True)
526 return baseline_details
527
528
529 def single_dup_update(rest_obj, module):
530 target_data, device_ids, group_ids, baseline_ids = None, None, None, None
531 if module.params.get("device_group_names") is not None:
532 group_ids = get_group_ids(rest_obj, module)
533 else:
534 device_id_tags = _validate_device_attributes(module)
535 device_ids, id_tag_map = get_device_ids(rest_obj, module, device_id_tags)
536 if module.check_mode:
537 module.exit_json(msg=CHANGES_FOUND, changed=True)
538 upload_status, token = upload_dup_file(rest_obj, module)
539 if upload_status:
540 report_payload = get_dup_applicability_payload(token, device_ids=device_ids, group_ids=group_ids,
541 baseline_ids=baseline_ids)
542 if report_payload:
543 target_data = get_applicable_components(rest_obj, report_payload, module)
544 return target_data
545
546
547 def baseline_based_update(rest_obj, module, baseline, dev_comp_map):
548 compliance_uri = COMPLIANCE_URI.format(baseline["baseline_id"])
549 resp = rest_obj.get_all_report_details(compliance_uri)
550 compliance_report_list = []
551 update_actions = ["UPGRADE", "DOWNGRADE"]
552 if resp["report_list"]:
553 comps = []
554 if not dev_comp_map:
555 comps = module.params.get('components')
556 dev_comp_map = dict([(str(dev["DeviceId"]), comps) for dev in resp["report_list"]])
557 for dvc in resp["report_list"]:
558 dev_id = dvc["DeviceId"]
559 if str(dev_id) in dev_comp_map:
560 comps = dev_comp_map.get(str(dev_id), [])
561 compliance_report = dvc.get("ComponentComplianceReports")
562 if compliance_report is not None:
563 data_dict = {}
564 comp_list = []
565 if not comps:
566 comp_list = list(icomp["SourceName"] for icomp in compliance_report
567 if icomp["UpdateAction"] in update_actions)
568 else:
569 comp_list = list(icomp["SourceName"] for icomp in compliance_report
570 if ((icomp["UpdateAction"] in update_actions) and
571 (icomp.get('Name').strip() in comps))) # regex filtering ++
572 if comp_list:
573 data_dict["Id"] = dev_id
574 data_dict["Data"] = str(";").join(comp_list)
575 data_dict["TargetType"] = {"Id": dvc['DeviceTypeId'], "Name": dvc["DeviceTypeName"]}
576 compliance_report_list.append(data_dict)
577 else:
578 module.exit_json(msg=COMPLIANCE_READ_FAIL, changed=True)
579 if not compliance_report_list:
580 module.exit_json(msg=NO_CHANGES_MSG)
581 if module.check_mode:
582 module.exit_json(msg=CHANGES_FOUND, changed=True)
583 return compliance_report_list
584
585
586 def _validate_device_attributes(module):
587 device_id_tags = []
588 service_tag = module.params.get('device_service_tag')
589 device_id = module.params.get('device_id')
590 devices = module.params.get('devices')
591 if devices:
592 for dev in devices:
593 if dev.get('id'):
594 device_id_tags.append(dev.get('id'))
595 else:
596 device_id_tags.append(dev.get('service_tag'))
597 if device_id is not None:
598 device_id_tags.extend(device_id)
599 if service_tag is not None:
600 device_id_tags.extend(service_tag)
601 return device_id_tags
602
603
604 def get_device_component_map(rest_obj, module):
605 device_id_tags = _validate_device_attributes(module)
606 device_ids, id_tag_map = get_device_ids(rest_obj, module, device_id_tags)
607 comps = module.params.get('components')
608 dev_comp_map = {}
609 if device_ids:
610 dev_comp_map = dict([(dev, comps) for dev in device_ids])
611 devices = module.params.get('devices')
612 if devices:
613 for dev in devices:
614 if dev.get('id'):
615 dev_comp_map[str(dev.get('id'))] = dev.get('components')
616 else:
617 id = list(id_tag_map.keys())[list(id_tag_map.values()).index(dev.get('service_tag'))]
618 dev_comp_map[str(id)] = dev.get('components')
619 return dev_comp_map
620
621
622 def validate_inputs(module):
623 param = module.params
624 if param.get("dup_file"):
625 if not any([param.get("device_id"), param.get("device_service_tag"), param.get("device_group_names")]):
626 module.exit_json(msg=DUP_REQ_MSG, failed=True)
627
628
629 def main():
630 specs = {
631 "device_service_tag": {"type": "list", "elements": 'str'},
632 "device_id": {"type": "list", "elements": 'int'},
633 "dup_file": {"type": "path"},
634 "device_group_names": {"type": "list", "elements": 'str'},
635 "components": {"type": "list", "elements": 'str', "default": []},
636 "baseline_name": {"type": "str"},
637 "schedule": {"type": 'str', "choices": ['RebootNow', 'StageForNextReboot'], "default": 'RebootNow'},
638 "reboot_type": {"type": 'str',
639 "choices": ['PowerCycle', 'GracefulReboot', 'GracefulRebootForce'],
640 "default": 'GracefulRebootForce'},
641 "devices": {
642 "type": 'list', "elements": 'dict',
643 "options": {
644 "id": {'type': 'int'},
645 "service_tag": {"type": 'str'},
646 "components": {"type": "list", "elements": 'str', "default": []},
647 },
648 "mutually_exclusive": [('id', 'service_tag')],
649 "required_one_of": [('id', 'service_tag')]
650 },
651 }
652
653 module = OmeAnsibleModule(
654 argument_spec=specs,
655 required_one_of=[["dup_file", "baseline_name"]],
656 mutually_exclusive=[
657 ["baseline_name", "dup_file"],
658 ["device_group_names", "device_id", "devices"],
659 ["device_group_names", "device_service_tag", "devices"],
660 ["baseline_name", "device_group_names"],
661 ["dup_file", "components", "devices"]],
662 supports_check_mode=True
663 )
664 validate_inputs(module)
665 update_status, baseline_details = {}, None
666 try:
667 with RestOME(module.params, req_session=True) as rest_obj:
668 if module.params.get("baseline_name"):
669 baseline_details = get_baseline_ids(rest_obj, module)
670 device_comp_map = get_device_component_map(rest_obj, module)
671 target_data = baseline_based_update(rest_obj, module, baseline_details, device_comp_map)
672 else:
673 target_data = single_dup_update(rest_obj, module)
674 job_payload = job_payload_for_update(rest_obj, module, target_data, baseline=baseline_details)
675 update_status = spawn_update_job(rest_obj, job_payload)
676 except HTTPError as err:
677 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
678 except URLError as err:
679 module.exit_json(msg=str(err), unreachable=True)
680 except (IOError, ValueError, SSLError, TypeError, ConnectionError, AttributeError, OSError) as err:
681 module.exit_json(msg=str(err), failed=True)
682 module.exit_json(msg="Successfully submitted the firmware update job.", update_status=update_status, changed=True)
683
684
685 if __name__ == "__main__":
686 main()