Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.10.0
7 # Copyright (C) 2024-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: omevv_firmware
20 short_description: Update the firmware of a specific host in the cluster
21 version_added: "9.10.0"
22 description: This module allows you to update the firmware of a specific host in the cluster.
23 extends_documentation_fragment:
24 - dellemc.openmanage.omevv_auth_options
25 options:
26 check_vSAN_health:
27 description:
28 - Check vSAN health while updating the firmware.
29 - C(true) checks the vSAN health while updating the firmware.
30 - C(false) does not check the vSAN health while updating the firmware.
31 type: bool
32 date_time:
33 description:
34 - Date and time when the job must run. This is applicable when I(run_now) is C(false).
35 - The supported format is YYYY-MM-DDThh:mm:ss<offset>.
36 type: str
37 delete_job_queue:
38 description:
39 - Whether to delete the job queue in iDRAC while updating firmware.
40 - C(true) deletes the job queue in iDRAC while updating firmware.
41 - C(false) does not delete the job queue in iDRAC while updating firmware.
42 type: bool
43 drs_check:
44 description:
45 - Allows you to check if DRS of the cluster is enabled or not.
46 - C(true) checks if Distributed Resource Scheduler (DRS) of the cluster is enabled.
47 - C(false) does not check if DRS of the cluster is enabled.
48 type: bool
49 default: false
50 enter_maintenance_mode_options:
51 description:
52 - VM migration policy during management mode.
53 - C(FULL_DATA_MIGRATION) for full data migration.
54 - C(ENSURE_ACCESSIBILITY) for ensuring accessibility.
55 - C(NO_DATA_MIGRATION) does not migrate any data.
56 type: str
57 choices: [FULL_DATA_MIGRATION, ENSURE_ACCESSIBILITY, NO_DATA_MIGRATION]
58 enter_maintenance_mode_timeout:
59 description:
60 - Time out value during maintenance mode in minutes.
61 type: int
62 default: 60
63 evacuate_VMs:
64 description:
65 - Allows to move the virtual machine (VM) to other host when current host is powered off.
66 - C(true) moves the VM to another host when the current host is powered off.
67 - C(false) does not move the VM to another host when the current host is powered off.
68 type: bool
69 default: false
70 exit_maintenance_mode:
71 description:
72 - Whether to exit management mode after Update.
73 - C(true) exits the management mode after Update.
74 - C(false) does not exit the management mode after Update.
75 type: bool
76 default: false
77 job_description:
78 description:
79 - Update job description.
80 type: str
81 job_name:
82 description:
83 - Update job name.
84 type: str
85 job_wait:
86 description:
87 - Whether to wait till completion of the job. This is applicable when I(power_on) is C(true).
88 - C(true) waits for job completion.
89 - C(false) does not wait for job completion.
90 type: bool
91 default: true
92 job_wait_timeout:
93 description:
94 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
95 - This option is applicable when I(job_wait) is C(true).
96 type: int
97 default: 1200
98 maintenance_mode_count_check:
99 description:
100 - Allows to check if any host in cluster is in management mode.
101 - C(true) checks if any host in cluster is in management mode.
102 - C(false) does not check if any host in cluster is in management mode.
103 type: bool
104 reboot_options:
105 description:
106 - Host reboot option for firmware update.
107 - C(FORCEREBOOT) will force reboot the server.
108 - C(SAFEREBOOT) reboots the server in safe mode.
109 - C(NEXTREBOOT) does not reboot the server.
110 type: str
111 choices: [FORCEREBOOT, SAFEREBOOT, NEXTREBOOT]
112 default: SAFEREBOOT
113 reset_idrac:
114 description:
115 - Whether to reset the iDRAC while performing firmware update.
116 - C(true) resets the iDRAC while performing firmware update.
117 - C(false) does not reset the iDRAC while performing firmware update.
118 type: bool
119 run_now:
120 description:
121 - Whether to run the update job now or later.
122 - C(true) runs the update job instantly.
123 - C(false) runs the update at the specified I(date_time).
124 type: bool
125 required: true
126 targets:
127 description:
128 - The target details for the firmware update operation.
129 - Either I(cluster), I(servicetag) or I(host) is required for the firmware update operation.
130 type: list
131 elements: dict
132 required: true
133 suboptions:
134 cluster:
135 description:
136 - Name of the cluster to which firmware needs to updated.
137 - I(cluster) is mutually exclusive with I(servicetag) and I(host).
138 - This module supports only single cluster update.
139 type: str
140 required: false
141 firmware_components:
142 description:
143 - List of host firmware components to update.
144 - M(dellemc.openmanage.omevv_firmware_compliance_info) module can
145 be used to fetch the supported firmware components.
146 type: list
147 elements: str
148 required: true
149 host:
150 description:
151 - The IP address or hostname of the host.
152 - I(host) is mutually exclusive with I(servicetag) and I(cluster).
153 - M(dellemc.openmanage.omevv_device_info) module can be used to fetch the device
154 information.
155 type: str
156 servicetag:
157 description:
158 - The service tag of the host.
159 - I(servicetag) is mutually exclusive with I(host) and I(cluster).
160 - M(dellemc.openmanage.omevv_device_info) module can be used to fetch the
161 device information.
162 type: str
163 requirements:
164 - "python >= 3.9.6"
165 author:
166 - "Rajshekar P(@rajshekarp87)"
167 attributes:
168 check_mode:
169 description: Can run in check_mode and return changed status prediction without modifying target, if not supported the action will be skipped.
170 support: full
171 diff_mode:
172 description: Will return details on what has changed (or possibly needs changing in check_mode), when in diff mode.
173 support: full
174 notes:
175 - Run this module from a system that has direct access to Dell OpenManage Enterprise.
176 - This module supports IPv4 and IPv6 addresses.
177 """
178
179 EXAMPLES = r"""
180 ---
181 - name: Immediately update the firmware of a single component for a specific host
182 dellemc.openmanage.omevv.omevv_firmware:
183 hostname: "XXX.XXX.XXX.XX"
184 vcenter_uuid: "xxxxx"
185 vcenter_username: "username"
186 vcenter_password: "password"
187 ca_path: "path/to/ca_file"
188 run_now: false
189 date_time: "2024-09-10T20:50:00Z"
190 enter_maintenance_mode_timeout: 60
191 enter_maintenance_mode_options: FULL_DATA_MIGRATION
192 drs_check: true
193 evacuate_VMs: true
194 exit_maintenance_mode: true
195 reboot_options: NEXTREBOOT
196 maintenance_mode_count_check: true
197 check_vSAN_health: true
198 reset_idrac: true
199 delete_job_queue: true
200 targets:
201 - servicetag: SVCTAG1
202 firmware_components:
203 - "DCIM:INSTALLED#802__Diagnostics.Embedded.1:LC.Embedded.1"
204
205 - name: Update the firmware of multiple components at scheduled time for a specific host
206 dellemc.openmanage.omevv.omevv_firmware:
207 hostname: "XXX.XXX.XXX.XY"
208 vcenter_uuid: "xxxxx"
209 vcenter_username: "username"
210 vcenter_password: "password"
211 ca_path: "path/to/ca_file"
212 run_now: false
213 date_time: "2024-09-10T20:50:00+05:30"
214 enter_maintenance_mode_timeout: 60
215 enter_maintenance_mode_options: ENSURE_ACCESSIBILITY
216 drs_check: true
217 evacuate_VMs: true
218 exit_maintenance_mode: true
219 reboot_options: FORCEREBOOT
220 maintenance_mode_count_check: true
221 check_vSAN_health: true
222 reset_idrac: false
223 delete_job_queue: false
224 targets:
225 - host: "XXX.XXX.XXX.XZ"
226 firmware_components:
227 - "DCIM:INSTALLED#iDRAC.Embedded.1-1#IDRACinfo"
228 - "DCIM:INSTALLED#301_C_BOSS.SL.14-1"
229 - "DCIM:INSTALLED#807__TPM.Integrated.1-1"
230
231 - name: Update the firmware of multiple components at scheduled time for a cluster
232 dellemc.openmanage.omevv.omevv_firmware:
233 hostname: "XXX.XXX.XXX.XX"
234 vcenter_uuid: "xxxxx"
235 vcenter_username: "username"
236 vcenter_password: "password"
237 ca_path: "path/to/ca_file"
238 run_now: false
239 date_time: "2024-09-10T20:50:00+05:30"
240 enter_maintenance_mode_timeout: 60
241 enter_maintenance_mode_options: ENSURE_ACCESSIBILITY
242 drs_check: true
243 evacuate_VMs: true
244 exit_maintenance_mode: true
245 reboot_options: SAFEREBOOT
246 maintenance_mode_count_check: true
247 check_vSAN_health: true
248 reset_idrac: false
249 delete_job_queue: false
250 targets:
251 - cluster: cluster_a
252 firmware_components:
253 - "DCIM:INSTALLED#iDRAC.Embedded.1-1#IDRACinfo"
254 - "DCIM:INSTALLED#301_C_BOSS.SL.14-1"
255 - "DCIM:INSTALLED#807__TPM.Integrated.1-1"
256
257 - name: Retrieve firmware compliance report of all hosts in the specific cluster
258 dellemc.openmanage.omevv_firmware_compliance_info:
259 hostname: "XXX.XXX.XXX.XX"
260 vcenter_uuid: "xxxxx"
261 vcenter_username: "username"
262 vcenter_password: "password"
263 ca_path: "path/to/ca_file"
264 clusters:
265 - cluster_name: cluster_a
266 register: compliance_data
267
268 - name: Initialize compliance status results
269 ansible.builtin.set_fact:
270 source_names: []
271 service_tag: ""
272
273 - name: Flatten host compliance reports
274 ansible.builtin.set_fact:
275 host_reports: "{{
276 compliance_data.firmware_compliance_info |
277 map(attribute='hostComplianceReports') |
278 flatten(levels=1) }}"
279
280 - name: Flatten and filter concompliant components
281 ansible.builtin.set_fact:
282 non_compliant_components: >-
283 {{
284 host_reports
285 | map(attribute='componentCompliances')
286 | flatten(levels=1)
287 | selectattr('driftStatus', 'equalto', 'NonCompliant')
288 }}
289
290 - name: Gather components source name and set service tag
291 ansible.builtin.set_fact:
292 source_names: "{{ source_names + [item.sourceName] }}"
293 service_tag: "{{ host_report.serviceTag }}"
294 loop: "{{ non_compliant_components }}"
295 vars:
296 host_report: >-
297 {{
298 host_reports
299 | selectattr('componentCompliances', 'contains', item)
300 | first
301 }}
302
303 - name: Combine the final non compliance report
304 ansible.builtin.set_fact:
305 noncompliance_report:
306 sourceNames: "{{ source_names }}"
307 serviceTag: "{{ service_tag }}"
308
309 - name: Update firmware at the scheduled time for a specific host
310 dellemc.openmanage.omevv.omevv_firmware:
311 hostname: "192.168.0.1"
312 vcenter_uuid: "{{ vcenter_uuid }}"
313 vcenter_username: "username"
314 vcenter_password: "password"
315 ca_path: "path/to/ca_file"
316 run_now: false
317 date_time: "2024-09-10T20:50:00Z"
318 enter_maintenance_mode_timeout: 60
319 enter_maintenance_mode_options: NO_DATA_MIGRATION
320 drs_check: true
321 evacuate_VMs: false
322 exit_maintenance_mode: true
323 reboot_options: SAFEREBOOT
324 maintenance_mode_count_check: true
325 check_vSAN_health: true
326 reset_idrac: true
327 delete_job_queue: true
328 targets:
329 - servicetag: "{{ noncompliance_report.serviceTag }}"
330 firmware_components: "{{ noncompliance_report.sourceNames }}"
331 """
332
333 RETURN = r'''
334 ---
335 msg:
336 type: str
337 description: Status of the firmware update operation.
338 returned: always
339 sample: "Successfully created the OMEVV baseline profile."
340 error_info:
341 description: Details of the module HTTP Error.
342 returned: on HTTP error
343 type: dict
344 sample:
345 {
346 "errorCode": "20058",
347 "message": "Update Job already running for group id 1004 corresponding to cluster OMAM-Cluster-1. Wait for its completion and trigger."
348 }
349 '''
350
351 import json
352 import time
353 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
354 from ansible.module_utils.urls import ConnectionError
355 from ansible_collections.dellemc.openmanage.plugins.module_utils.omevv import RestOMEVV, OMEVVAnsibleModule
356 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import validate_job_wait
357 from ansible_collections.dellemc.openmanage.plugins.module_utils.omevv_utils.omevv_firmware_utils import OMEVVFirmwareUpdate, OMEVVBaselineProfile
358 from ansible_collections.dellemc.openmanage.plugins.module_utils.omevv_utils.omevv_info_utils import OMEVVInfo
359 from datetime import datetime
360
361 SUCCESS_UPDATE_SUBMIT_MSG = "Successfully submitted the firmware updated job."
362 SUCCESS_UPDATE_MSG = "Successfully completed the firmware update."
363 SUCCESS_UPDATE_SCHEDULED_MSG = "Successfully scheduled the firmware update job."
364 FAILED_UPDATE_MSG = "Failed to complete the firmware update."
365 FAILED_UPDATE_TIMEOUT_MSG = "Firmware update job timed out after {0} seconds."
366 INVALID_DATE_TIME_MSG = "Invalid date time. Enter a valid date time in the format of " \
367 "YYYY-MM-DDTHH:MM:SSZ."
368 MAINTENANCE_MODE_TIMEOUT_INVALID_MSG = "The value for the 'enter_maintenance_mode_timeout' " \
369 "parameter must be between 60 and 1440."
370 CLUSTER_HOST_SERVICETAG_MUTUAL_EXCLUSIVE_MSG = "parameters are mutually " \
371 "exclusive: cluster|host|servicetag."
372 CLUSTER_HOST_SERVICETSAG_REQUIRED_MSG = "Either 'cluster' or 'host' or 'servicetag' must " \
373 "be specified."
374 UPDATE_JOB_PRESENT_MSG = "Update job is either running or in a scheduled state for cluster " \
375 "'{cluster_name}'. Wait for its completion and trigger."
376 JOB_NAME_ALREADY_EXISTS_MSG = "Job with name '{job_name}' already exists. Provide different name."
377 CLUSTER_HOST_NOT_FOUND_MSG = "No managed hosts found in the cluster."
378 HOST_NOT_FOUND_MSG = "Host '{managed_host}' not found under managed hosts."
379 CLUSTER_NOT_FOUND_MSG = "Provided cluster name '{cluster_name}' is not valid."
380 CHANGES_FOUND_MSG = "Changes found to be applied."
381 CHANGES_NOT_FOUND_MSG = "No changes found to be applied."
382 TIMEOUT_NEGATIVE_OR_ZERO_MSG = "The value for the 'job_wait_timeout' parameter cannot be " \
383 "negative or zero."
384 UNREACHABLE_MSG = "The URL with the {ip}:{port} cannot be reached."
385 SOURCE_NOT_FOUND_MSG = "The Requested resource cannot be found."
386 TRIGGER_UPDATE_CHECK_URI = "/Consoles/{vcenter_uuid}/CanTriggerUpdate"
387
388
389 class FirmwareUpdate():
390
391 def __init__(self, module, rest_obj):
392 """
393 Initializes the FirmwareUpdate object.
394
395 Args:
396 module (Any): The module to execute.
397 rest_obj (Any): The rest object.
398
399 Returns:
400 None
401 """
402 self.module = module
403 self.obj = rest_obj
404 self.omevv_info_obj = OMEVVInfo(self.obj)
405 self.omevv_update_obj = OMEVVFirmwareUpdate(self.obj)
406 self.omevv_baseline_obj = OMEVVBaselineProfile(self.obj)
407
408 def get_payload_details(self, host_id):
409 """
410 Retrieves the payload details for the firmware update.
411
412 Args:
413 host_id (str): The ID of the host.
414
415 Returns:
416 dict: The payload details for the firmware update.
417 """
418 device_id = host_id
419 parameters = self.module.params
420 target_list = parameters['targets']
421 payload = {"firmware": {"targets": []}}
422 firmware = payload["firmware"]
423
424 payload["firmware"].update(self.set_firmware(firmware, parameters))
425 payload = self.set_schedule(payload, parameters)
426 payload = self.set_job_details(payload, parameters)
427 payload["firmware"].update(self.add_targets(firmware, target_list, device_id))
428
429 return payload
430
431 def set_firmware(self, firmware, parameters):
432 """
433 Adds optional fields to the firmware dictionary based on the
434 parameters.
435
436 Args:
437 firmware (dict): The firmware dictionary.
438 parameters (dict): The parameters dictionary.
439
440 Returns:
441 None
442 """
443 optional_fields = [
444 ('check_vSAN_health', 'checkvSANHealth'),
445 ('delete_job_queue', 'deleteJobsQueue'),
446 ('drs_check', 'drsCheck'),
447 ('enter_maintenance_mode_options', 'enterMaintenanceModeOption'),
448 ('enter_maintenance_mode_timeout', 'enterMaintenanceModetimeout'),
449 ('evacuate_VMs', 'evacuateVMs'),
450 ('exit_maintenance_mode', 'exitMaintenanceMode'),
451 ('maintenance_mode_count_check', 'maintenanceModeCountCheck'),
452 ('reboot_options', 'rebootOptions'),
453 ('reset_idrac', 'resetIDrac'),
454 ]
455
456 for param_key, firmware_key in optional_fields:
457 # if parameters.get(param_key) is not None:
458 firmware[firmware_key] = parameters.get(param_key)
459 return firmware
460
461 def set_schedule(self, payload, parameters):
462 """
463 Sets the schedule for the payload.
464
465 Args:
466 payload (dict): The payload dictionary.
467 parameters (dict): The parameters dictionary.
468
469 Returns:
470 None
471 """
472 payload["schedule"] = {"runNow": parameters.get('run_now')}
473
474 if not payload["schedule"]["runNow"]:
475 payload["schedule"]["dateTime"] = parameters.get('date_time')
476 return payload
477
478 def set_job_details(self, payload, parameters):
479 """
480 Sets the job details in the payload dictionary.
481
482 Args:
483 payload (dict): The payload dictionary.
484 parameters (dict): The parameters dictionary.
485
486 Returns:
487 None
488 """
489 if parameters.get('job_description'):
490 payload["jobDescription"] = parameters.get('job_description')
491 else:
492 payload["jobDescription"] = None
493
494 if parameters.get('job_name'):
495 payload["jobName"] = parameters.get('job_name')
496 else:
497 date_time = datetime.now()
498 job_name = (
499 f"omam_firmware_update_job_{date_time.year}{date_time.month:02}{date_time.day:02}_"
500 f"{date_time.hour:02}{date_time.minute:02}{date_time.second:02}")
501 payload["jobName"] = job_name
502 return payload
503
504 def add_targets(self, firmware, target_list, device_id):
505 """
506 Adds targets to the firmware dictionary.
507
508 Args:
509 firmware (dict): The firmware dictionary.
510 target_list (list): The list of targets.
511 device_id (Union[str, list]): The device ID or list of device IDs.
512
513 Returns:
514 None
515 """
516 for target in target_list:
517 if isinstance(device_id, list):
518 # If device_id is a list, iterate through each id and add to the targets
519 for single_device_id in device_id:
520 actual_target = {
521 "firmwarecomponents": target['firmware_components'],
522 "id": single_device_id
523 }
524 firmware['targets'].append(actual_target)
525 else:
526 # If device_id is a single string, add it directly to the targets
527 actual_target = {
528 "firmwarecomponents": target['firmware_components'],
529 "id": device_id
530 }
531 firmware['targets'].append(actual_target)
532 return firmware
533
534 def host_servicetag_existence(self):
535 """
536 Check the existence of host and servicetag in the targets.
537
538 Args:
539 self (object): The instance of the class.
540
541 Returns:
542 None
543 """
544 for target in self.module.params.get('targets', []):
545 cluster = target.get('cluster')
546 host = target.get('host')
547 servicetag = target.get('servicetag')
548
549 if (host and servicetag) or (host and cluster) or (servicetag and cluster):
550 self.module.exit_json(msg=CLUSTER_HOST_SERVICETAG_MUTUAL_EXCLUSIVE_MSG,
551 failed=True)
552 if not host and not servicetag and not cluster:
553 self.module.exit_json(msg=CLUSTER_HOST_SERVICETSAG_REQUIRED_MSG, failed=True)
554
555 def validate_date_time(self):
556 """
557 Validates the date and time format.
558
559 This function takes the date and time string from the 'date_time' parameter
560 and attempts to parse it using the specified format. If the parsing is
561 successful, the parsed datetime object is returned. If the parsing fails,
562 the function exits with a failure message.
563
564 Returns:
565 datetime: The parsed datetime object.
566 """
567 try:
568 ftime = datetime.strptime(self.module.params.get('date_time'), "%Y-%m-%dT%H:%M:%S%z")
569 except ValueError:
570 self.module.exit_json(msg=INVALID_DATE_TIME_MSG, failed=True)
571 return ftime
572
573 def enter_maintenance_mode_timeout(self):
574 """
575 Validates the timeout value for entering maintenance mode.
576
577 This function checks if the value of the 'enter_maintenance_mode_timeout' parameter is
578 within the valid range (60 to 1440). If the value is outside the valid range, the function
579 exits with a failure message.
580
581 Parameters:
582 self (object): The instance of the class.
583
584 Returns:
585 None
586
587 Raises:
588 SystemExit: If the value of 'enter_maintenance_mode_timeout' is outside the valid range.
589 """
590 enter_maintenance_mode_timeout = self.module.params.get('enter_maintenance_mode_timeout')
591 if enter_maintenance_mode_timeout < 60 or enter_maintenance_mode_timeout > 1440:
592 self.module.exit_json(msg=MAINTENANCE_MODE_TIMEOUT_INVALID_MSG, failed=True)
593
594 def validate_params(self):
595 """
596 Validates the parameters of the class.
597
598 This function checks the existence of the 'host' and 'servicetag' parameters.
599 It also validates the 'job_wait' parameter and the 'date_time' parameter.
600 Additionally, it validates the 'enter_maintenance_mode_timeout' parameter.
601
602 Parameters:
603 self (object): The instance of the class.
604
605 Returns:
606 None
607 """
608
609 # Validate the 'host' and 'servicetag' parameter existence
610 self.host_servicetag_existence()
611
612 # Validate the job_wait parameter
613 if validate_job_wait(self.module):
614 self.module.exit_json(msg=TIMEOUT_NEGATIVE_OR_ZERO_MSG, failed=True)
615
616 # Validate the date_time parameter
617 if self.module.params.get('date_time'):
618 self.validate_date_time()
619
620 # Validate the enter_maintenance_mode_timeout parameter
621 if self.module.params.get('enter_maintenance_mode_timeout'):
622 self.enter_maintenance_mode_timeout()
623
624
625 class UpdateCluster(FirmwareUpdate):
626
627 def execute(self):
628 """
629 Executes the firmware update process.
630
631 This function validates the parameters, retrieves the target cluster and payload,
632 checks if the update job is allowed, and handles the firmware update process.
633
634 Returns:
635 None
636 """
637 cluster_name = None
638 cluster_group_id = None
639 host_service_tags = None
640 new_host_id = None
641 payload = None
642 self.validate_params()
643 vcenter_uuid = self.module.params.get('vcenter_uuid')
644 parameters = self.module.params
645 target = self.get_target(parameters['targets'])
646 cluster_name = target['cluster']
647
648 if target['cluster']:
649 cluster_group_id, payload, new_host_id = self.process_cluster_target(target)
650 else:
651 cluster_name, cluster_group_id, payload, new_host_id = self.process_non_cluster_target(parameters)
652
653 if not isinstance(new_host_id, list):
654 new_host_id = [new_host_id]
655 host_service_tags = [host_service_tags]
656
657 self.is_update_job_allowed(vcenter_uuid, cluster_group_id, cluster_name)
658
659 self.is_job_name_existing(vcenter_uuid, self.module.params.get('job_name'))
660
661 firmware_update_needed, before_dict, after_dict = self.is_firmware_update_needed(
662 vcenter_uuid, cluster_group_id, new_host_id, parameters['targets'], host_service_tags)
663
664 if self.module.check_mode:
665 self.handle_check_mode(firmware_update_needed, before_dict, after_dict)
666
667 if firmware_update_needed:
668 self.handle_firmware_update(vcenter_uuid, cluster_group_id, payload, parameters,
669 before_dict, after_dict)
670
671 else:
672 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG,
673 diff={"before": before_dict,
674 "after": after_dict}, changed=False)
675
676 def process_cluster_target(self, target):
677 """
678 Process the cluster target.
679
680 Args:
681 target (dict): The target cluster.
682
683 Returns:
684 tuple: A tuple containing the cluster group ID, payload, and new host ID.
685 """
686 vcenter_uuid = self.module.params.get('vcenter_uuid')
687 host_ids, host_service_tags = self.get_host_id_either_host_or_service_tag(vcenter_uuid, target)
688 if host_ids is None or not host_ids:
689 self.module.exit_json(msg=CLUSTER_HOST_NOT_FOUND_MSG, skipped=True)
690 cluster_name = target['cluster']
691 cluster_group_id = self.omevv_info_obj.get_group_id_of_cluster(vcenter_uuid,
692 cluster_name)
693 payload = self.get_payload_details(host_id=host_ids)
694 return cluster_group_id, payload, host_ids
695
696 def process_non_cluster_target(self, parameters):
697 """
698 Process the non-cluster target.
699
700 Args:
701 parameters (dict): The parameters dictionary.
702
703 Returns:
704 tuple: A tuple containing the cluster group ID, payload, and new host ID.
705 """
706 vcenter_uuid = self.module.params.get('vcenter_uuid')
707 target = self.get_target(parameters['targets'])
708 host_id, host_service_tags = self.get_host_from_parameters(vcenter_uuid, parameters)
709 if host_id is None:
710 if target['host']:
711 self.module.exit_json(msg=HOST_NOT_FOUND_MSG.format(
712 managed_host=target['host']), skipped=True)
713 else:
714 self.module.exit_json(msg=HOST_NOT_FOUND_MSG.format(
715 managed_host=target['servicetag']), skipped=True)
716 cluster_name = self.omevv_info_obj.get_cluster_name(vcenter_uuid, host_id)
717 cluster_group_id = self.omevv_info_obj.get_group_id_of_cluster(vcenter_uuid,
718 cluster_name)
719 payload = self.get_payload_details(host_id=host_id)
720 return cluster_name, cluster_group_id, payload, host_id
721
722 def get_host_from_parameters(self, vcenter_uuid, parameters, host_ids=None,
723 host_service_tags=None):
724 """
725 Retrieves the host and service tags from the given parameters.
726
727 Args:
728 vcenter_uuid (str): The UUID of the vCenter.
729 parameters (dict): The parameters dictionary.
730 host_ids (list, optional): The list of host IDs. Defaults to None.
731 host_service_tags (list, optional): The list of host service tags. Defaults to None.
732
733 Returns:
734 tuple: A tuple containing the host IDs and host service tags.
735 """
736 target = self.get_target(parameters['targets'])
737 if target['cluster']:
738 return host_ids, host_service_tags
739 else:
740 host_ids, host_service_tags = self.get_host_id_either_host_or_service_tag(vcenter_uuid, target)
741 return host_ids, host_service_tags
742
743 def handle_check_mode(self, firmware_update_needed, before_dict, after_dict):
744 """
745 Handles the check mode for firmware update.
746
747 Args:
748 firmware_update_needed (bool): Indicates if firmware update is needed.
749 before_dict (dict): The dictionary representing the state before the update.
750 after_dict (dict): The dictionary representing the state after the update.
751
752 Returns:
753 None
754 """
755 if firmware_update_needed:
756 if self.module._diff:
757 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True,
758 diff={"before": before_dict, "after": after_dict})
759 else:
760 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
761 else:
762 if self.module._diff:
763 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False,
764 diff={"before": before_dict,
765 "after": after_dict})
766 else:
767 self.module.exit_json(msg=CHANGES_NOT_FOUND_MSG, changed=False)
768
769 def handle_firmware_update(self, vcenter_uuid, cluster_group_id, payload, parameters,
770 before_dict, after_dict):
771 """
772 Executes the firmware update job and handles the response.
773
774 Args:
775 vcenter_uuid (str): The UUID of the vCenter.
776 cluster_group_id (str): The ID of the cluster group.
777 payload (dict): The payload for the firmware update.
778 parameters (dict): The parameters for the firmware update.
779 before_dict (dict): The state of the system before the update.
780 after_dict (dict): The state of the system after the update.
781
782 Returns:
783 None
784 """
785 job_resp = self.execute_update_job(vcenter_uuid, cluster_group_id, payload, parameters,
786 before_dict, after_dict)
787 if self.module.params.get('run_now'):
788 self.module.exit_json(msg=SUCCESS_UPDATE_MSG, changed=True, job_details=job_resp,
789 diff={"before": before_dict, "after": after_dict})
790 else:
791 self.module.exit_json(msg=SUCCESS_UPDATE_SCHEDULED_MSG, changed=True,
792 job_details=job_resp,
793 diff={"before": before_dict, "after": after_dict})
794
795 def get_target(self, target_list):
796 """
797 Returns the first item in the target_list.
798
799 Args:
800 target_list (list): The list of targets.
801
802 Returns:
803 Any: The first item in the target_list.
804 """
805 for target in target_list:
806 return target
807
808 def get_host_id_either_host_or_service_tag(self, vcenter_uuid, target):
809 """
810 Retrieves the host ID and service tag for a given target.
811
812 Args:
813 vcenter_uuid (str): The UUID of the vCenter.
814 target (dict): The target containing the cluster, service tag, and host.
815
816 Returns:
817 tuple: A tuple containing the host ID and service tag.
818 """
819 cluster_name = target['cluster']
820 service_tag = target['servicetag']
821 host = target['host']
822
823 if service_tag:
824 host_id, host_service_tag = self.omevv_info_obj.get_host_id_either_host_or_service_tag(
825 vcenter_uuid, hostname=None, servicetag=service_tag)
826 return host_id, host_service_tag
827 elif host:
828 host_id, host_service_tag = self.omevv_info_obj.get_host_id_either_host_or_service_tag(
829 vcenter_uuid, hostname=host, servicetag=None)
830 return host_id, host_service_tag
831 else:
832 cluster_group_id = self.omevv_info_obj.get_group_id_of_cluster(vcenter_uuid,
833 cluster_name)
834 if cluster_group_id == -1:
835 self.module.exit_json(msg=CLUSTER_NOT_FOUND_MSG.format(cluster_name=cluster_name),
836 skipped=True)
837 else:
838 host_ids, host_service_tags = self.omevv_info_obj.get_cluster_managed_host_details(
839 vcenter_uuid, cluster_group_id)
840 return host_ids, host_service_tags
841
842 def is_firmware_update_needed(self, vcenter_uuid, cluster_group_id, host_ids,
843 target, host_service_tags):
844 """
845 Determines if a firmware update is needed.
846
847 Args:
848 vcenter_uuid (str): The UUID of the vCenter.
849 cluster_group_id (int): The ID of the cluster group.
850 host_ids (List[int]): The list of host IDs.
851 target (List[Dict[str, str]]): The list of targets.
852 host_service_tags (List[str]): The list of host service tags.
853
854 Returns:
855 Tuple[bool, Dict[str, Dict[str, str]], Dict[str, Dict[str, str]], Dict[str, Dict[str, str]], Dict[str, Dict[str, str]]]:
856 A tuple containing the following:
857 - firmware_update_needed (bool): True if a firmware update is needed, False otherwise.
858 - main_before_no_change_dict (Dict[str, Dict[str, str]]): The dictionary of before no change firmware versions.
859 - main_after_no_change_dict (Dict[str, Dict[str, str]]): The dictionary of after no change firmware versions.
860 - main_before_dict (Dict[str, Dict[str, str]]): The dictionary of before firmware versions.
861 - main_after_dict (Dict[str, Dict[str, str]]): The dictionary of after firmware versions.
862 """
863 firmware_update_needed = False
864 # Ensure host_ids is a list for uniform processing
865 if isinstance(host_ids, int):
866 host_ids = [host_ids]
867 if isinstance(host_service_tags, str):
868 host_service_tags = [host_service_tags]
869
870 main_before_dict = {}
871 main_after_dict = {}
872 for idx, one_host_id in enumerate(host_ids):
873 update_needed, before_dict, after_dict, current_host_st = self.check_firmware_update(
874 vcenter_uuid, cluster_group_id, one_host_id, target)
875 main_before_dict[current_host_st] = before_dict
876 main_after_dict[current_host_st] = after_dict
877
878 firmware_update_needed = firmware_update_needed or update_needed
879
880 return firmware_update_needed, main_before_dict, main_after_dict
881
882 def check_firmware_update(self, vcenter_uuid, cluster_group_id, host_id, target):
883 """
884 Check if firmware update is needed for a host.
885
886 Args:
887 vcenter_uuid (str): The UUID of the vCenter.
888 cluster_group_id (str): The ID of the cluster group.
889 host_id (str): The ID of the host.
890 target (list): The list of targets.
891
892 Returns:
893 tuple: A tuple containing the following:
894 - firmware_update_needed (bool): A boolean indicating if firmware update is needed.
895 - before_dict (dict): A dictionary containing the firmware version before the update.
896 - after_dict (dict): A dictionary containing the firmware version after the update.
897 - current_host_st (str): The service tag of the current host.
898 """
899 current_host_st = None
900 before_dict, after_dict = {}, {}
901 if 'cluster' in target[0] and target[0]['cluster']:
902 cluster_firmware_drift_info = self.omevv_info_obj.get_firmware_drift_info_for_single_host(
903 vcenter_uuid, cluster_group_id, host_id)
904 current_firmware_comp_reports = cluster_firmware_drift_info.get("hostComplianceReports")
905 current_host_st = current_firmware_comp_reports[0].get("serviceTag")
906 current_firmware_components = current_firmware_comp_reports[0].get('componentCompliances', [])
907 else:
908 firmware_drift_info = self.omevv_info_obj.get_firmware_drift_info_for_single_host(
909 vcenter_uuid, cluster_group_id, host_id)
910 current_firmware_comp_reports = firmware_drift_info.get("hostComplianceReports")
911 current_host_st = current_firmware_comp_reports[0].get("serviceTag")
912 current_firmware_components = firmware_drift_info.get(
913 'hostComplianceReports', [])[0].get('componentCompliances', [])
914
915 required_firmware_components = target[0]['firmware_components']
916
917 for component in required_firmware_components:
918 for current_component in current_firmware_components:
919 if current_component['sourceName'] == component:
920 before_dict[current_component["sourceName"]] = {
921 "firmwareversion": current_component["currentValue"]}
922 after_dict[current_component["sourceName"]] = {
923 "firmwareversion": current_component["baselineValue"]}
924 firmware_update_needed = (before_dict != after_dict)
925
926 return firmware_update_needed, before_dict, after_dict, current_host_st
927
928 def is_update_job_allowed(self, vcenter_uuid, cluster_group_id, cluster_name):
929 """
930 Check if an update job is allowed.
931
932 Args:
933 vcenter_uuid (str): The UUID of the vCenter.
934 cluster_group_id (str): The ID of the cluster group.
935 cluster_name (str): The name of the cluster.
936
937 Returns:
938 bool: True if the update job is allowed, False otherwise.
939 """
940 try:
941 self.omevv_update_obj.check_existing_update_job(vcenter_uuid, cluster_group_id)
942 except Exception:
943 self.module.exit_json(msg=UPDATE_JOB_PRESENT_MSG.format(cluster_name=cluster_name),
944 skipped=True)
945
946 def is_job_name_existing(self, vcenter_uuid, job_name):
947 """
948 Check if a job name already exists.
949
950 Args:
951 vcenter_uuid (str): The UUID of the vCenter.
952 job_name (str): The name of the job.
953
954 Returns:
955 bool: True if the job name exists, False otherwise.
956 """
957 job_exist_status = self.omevv_update_obj.check_existing_job_name(vcenter_uuid, job_name)
958 if job_exist_status is True:
959 self.module.exit_json(msg=JOB_NAME_ALREADY_EXISTS_MSG.format(job_name=job_name),
960 skipped=True)
961
962 def execute_update_job(self, vcenter_uuid, cluster_group_id, payload, parameters,
963 before_dict, after_dict):
964 """
965 Executes the firmware update job for a cluster.
966
967 Args:
968 vcenter_uuid (str): The UUID of the vCenter.
969 cluster_group_id (str): The ID of the cluster group.
970 payload (dict): The payload for the firmware update.
971 parameters (dict): The parameters for the firmware update.
972 before_dict (dict): The state of the system before the update.
973 after_dict (dict): The state of the system after the update.
974
975 Returns:
976 dict: The response from the firmware update job.
977 """
978 tmp_payload = {
979 "schedule": {
980 "runNow": payload["schedule"]["runNow"]
981 },
982 "firmware": {
983 "enterMaintenanceModetimeout": payload["firmware"]["enterMaintenanceModetimeout"],
984 "drsCheck": payload["firmware"]['drsCheck'],
985 "evacuateVMs": payload["firmware"]['evacuateVMs'],
986 "exitMaintenanceMode": payload["firmware"]['exitMaintenanceMode'],
987 "rebootOptions": payload["firmware"]['rebootOptions'],
988 "enterMaintenanceModeOption": payload["firmware"]['enterMaintenanceModeOption'],
989 "maintenanceModeCountCheck": payload["firmware"]['maintenanceModeCountCheck'],
990 "checkvSANHealth": payload["firmware"]['checkvSANHealth'],
991 "resetIDrac": payload["firmware"]['resetIDrac'],
992 "deleteJobsQueue": payload["firmware"]['deleteJobsQueue'],
993 "targets": payload["firmware"]['targets']
994 }
995 }
996 if payload["schedule"]["runNow"] is False:
997 tmp_payload["schedule"]["dateTime"] = payload["schedule"]["dateTime"]
998 final_payload = {}
999 final_payload.update({"firmware": {}})
1000 for key, value in tmp_payload["firmware"].items():
1001 if value is not None:
1002 final_payload["firmware"].update({key: value})
1003 final_payload["jobName"] = payload["jobName"]
1004 if payload["jobDescription"] is None:
1005 final_payload["jobDescription"] = ""
1006 else:
1007 final_payload["jobDescription"] = payload["jobDescription"]
1008 final_payload["schedule"] = payload["schedule"]
1009 resp, error_msg = self.omevv_update_obj.update_cluster(vcenter_uuid,
1010 cluster_group_id, **final_payload)
1011 if resp.success:
1012 job_resp, err_msg = self.omevv_update_obj.firmware_update_job_track(vcenter_uuid,
1013 resp.json_data)
1014 self.handle_job_response(parameters, vcenter_uuid, resp, job_resp, err_msg,
1015 before_dict, after_dict)
1016 else:
1017 self.module.exit_json(msg=FAILED_UPDATE_MSG, failed=True, error_info=error_msg)
1018 return job_resp
1019
1020 def handle_job_response(self, parameters, vcenter_uuid, resp, job_resp, err_msg,
1021 before_dict, after_dict):
1022 """
1023 Handle the response from the firmware update job.
1024
1025 Args:
1026 parameters (dict): The parameters for the firmware update.
1027 vcenter_uuid (str): The UUID of the vCenter.
1028 resp (Response): The response from the firmware update.
1029 job_resp (dict): The response from the firmware update job.
1030 err_msg (str): The error message from the firmware update.
1031 before_dict (dict): The state of the system before the update.
1032 after_dict (dict): The state of the system after the update.
1033
1034 Returns:
1035 None
1036 """
1037 run_now = parameters.get('run_now')
1038 if not run_now:
1039 self.module.exit_json(msg=SUCCESS_UPDATE_SCHEDULED_MSG, changed=True,
1040 job_details=job_resp,
1041 diff={"before": before_dict, "after": after_dict})
1042 else:
1043 job_wait = self.module.params.get('job_wait')
1044 if job_wait:
1045 self.wait_for_job_completion(vcenter_uuid, resp, job_resp, err_msg,
1046 before_dict, after_dict)
1047 else:
1048 self.module.exit_json(msg=SUCCESS_UPDATE_SUBMIT_MSG, changed=True,
1049 job_details=job_resp,
1050 diff={"before": before_dict, "after": after_dict})
1051
1052 def wait_for_job_completion(self, vcenter_uuid, resp, job_resp, err_msg,
1053 before_dict, after_dict):
1054 """
1055 Waits for the firmware update job to complete.
1056
1057 Args:
1058 vcenter_uuid (str): The UUID of the vCenter.
1059 resp (Response): The response from the firmware update.
1060 job_resp (dict): The response from the firmware update job.
1061 err_msg (str): The error message from the firmware update.
1062 before_dict (dict): The state of the system before the update.
1063 after_dict (dict): The state of the system after the update.
1064
1065 Returns:
1066 None
1067
1068 Raises:
1069 None
1070 """
1071 job_wait_timeout = self.module.params.get('job_wait_timeout')
1072 count = job_wait_timeout // 5
1073 while job_resp["state"] not in ["COMPLETED", "FAILED"] and count > 0:
1074 time.sleep(5)
1075 job_resp, err_msg = self.omevv_update_obj.firmware_update_job_track(vcenter_uuid,
1076 resp.json_data)
1077 count -= 1
1078
1079 if count <= 0:
1080 self.module.exit_json(msg=FAILED_UPDATE_TIMEOUT_MSG.format(job_wait_timeout),
1081 failed=True, job_details=job_resp)
1082
1083 if job_resp["state"] == "COMPLETED" and job_resp["lastExecutionHistory"]["statusSummary"] == "SUCCESSFUL":
1084 self.module.exit_json(msg=SUCCESS_UPDATE_MSG, changed=True, job_details=job_resp,
1085 diff={"before": before_dict, "after": after_dict})
1086 else:
1087 self.module.exit_json(msg=FAILED_UPDATE_MSG, failed=True, error_info=err_msg)
1088
1089
1090 def main():
1091 """
1092 The main function of the module. It sets up the argument spec and initializes the OMEVVAnsibleModule.
1093 It then creates an instance of the UpdateCluster class and calls its execute method.
1094 If any exceptions occur, it handles them and exits the module with the appropriate response.
1095
1096 Args:
1097 None
1098
1099 Returns:
1100 None
1101 """
1102 argument_spec = {
1103 "check_vSAN_health": {"type": 'bool'},
1104 "date_time": {"type": 'str'},
1105 "delete_job_queue": {"type": 'bool'},
1106 "drs_check": {"type": 'bool', "default": False},
1107 "enter_maintenance_mode_options": {
1108 "type": 'str',
1109 "choices": [
1110 'FULL_DATA_MIGRATION',
1111 'ENSURE_ACCESSIBILITY',
1112 'NO_DATA_MIGRATION'
1113 ]
1114 },
1115 "enter_maintenance_mode_timeout": {"type": 'int', "default": 60},
1116 "evacuate_VMs": {"type": 'bool', "default": False},
1117 "exit_maintenance_mode": {"type": "bool", "default": False},
1118 "job_description": {"type": 'str'},
1119 "job_name": {"type": 'str'},
1120 "job_wait": {"type": 'bool', "default": True},
1121 "job_wait_timeout": {"type": 'int', "default": 1200},
1122 "maintenance_mode_count_check": {"type": 'bool'},
1123 "reboot_options": {
1124 "type": 'str',
1125 "choices": [
1126 'FORCEREBOOT',
1127 'SAFEREBOOT',
1128 'NEXTREBOOT'
1129 ],
1130 "default": 'SAFEREBOOT'
1131 },
1132 "reset_idrac": {"type": 'bool'},
1133 "run_now": {"type": 'bool', "required": True},
1134 "targets": {
1135 "type": 'list',
1136 "elements": 'dict',
1137 "required": True,
1138 "options": {
1139 "firmware_components": {
1140 "type": 'list',
1141 "elements": 'str',
1142 "required": True
1143 },
1144 "cluster": {"type": 'str'},
1145 "host": {"type": 'str'},
1146 "servicetag": {"type": 'str'}
1147 }
1148 }
1149 }
1150
1151 module = OMEVVAnsibleModule(
1152 argument_spec=argument_spec,
1153 required_if=[
1154 ["run_now", False, ("date_time",)]
1155 ],
1156 supports_check_mode=True
1157 )
1158
1159 try:
1160 with RestOMEVV(module.params) as rest_obj:
1161 omevv_obj = UpdateCluster(module, rest_obj)
1162 omevv_obj.execute()
1163 except HTTPError as httperr:
1164 response_data = {"msg": str(httperr), "failed": True}
1165 error_info = {}
1166 try:
1167 error_info = json.load(httperr)
1168 except ValueError:
1169 error_info["message"] = str(httperr)
1170 error_info["type"] = "HTTPError"
1171
1172 if httperr.code == 500:
1173 response_data["msg"] = error_info.get("message", str(error_info))
1174 elif httperr.code == 404:
1175 response_data["msg"] = SOURCE_NOT_FOUND_MSG
1176 else:
1177 response_data.update({
1178 "msg": error_info.get("message", str(error_info)),
1179 "error_info": error_info
1180 })
1181 module.exit_json(**response_data)
1182
1183 except URLError as urlerr:
1184 response_data = {
1185 "msg": f"The URL with IP {module.params.get('hostname')} and port {module.params.get('port')} cannot be reached.",
1186 "unreachable": True,
1187 "error_info": {"message": str(urlerr), "type": "URLError"}
1188 }
1189 module.exit_json(**response_data)
1190
1191 except (IOError, ValueError, TypeError, ConnectionError,
1192 AttributeError, IndexError, KeyError, OSError) as generr:
1193 module.exit_json(msg=str(generr), failed=True)
1194
1195
1196 if __name__ == '__main__':
1197 main()