Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.12.2
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: idrac_system_erase
20 short_description: Erase system and storage components of the server
21 version_added: "9.7.0"
22 description:
23 - This module allows you to erase system components such as iDRAC, BIOS, DIAG,
24 and so forth. You can also erase storage components such as PERC NV cache,
25 non-volatile memory, cryptographic erase of physical disks, and so on of the server
26 extends_documentation_fragment:
27 - dellemc.openmanage.idrac_x_auth_options
28 options:
29 component:
30 description:
31 - List of system and storage components that can be deleted.
32 - The following are the supported components.
33 AllApps
34 BIOS
35 CryptographicErasePD
36 DIAG
37 DPU
38 DrvPack
39 IDRAC
40 LCData
41 NonVolatileMemory
42 OverwritePD
43 PERCNVCache
44 ReinstallFW
45 vFlash
46 type: list
47 elements: str
48 required: true
49 power_on:
50 description:
51 - This parameter allows you to power on the server after the erase operation is completed. This is applicable when I(job_wait) is C(true).
52 - C(true) power on the server.
53 - C(false) does not power on the server.
54 type: bool
55 default: false
56 job_wait:
57 description:
58 - Whether to wait till completion of the job. This is applicable when I(power_on) is C(true).
59 - C(true) waits for job completion.
60 - C(false) does not wait for job completion.
61 type: bool
62 default: true
63 job_wait_timeout:
64 description:
65 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
66 - This option is applicable when I(job_wait) is C(true).
67 type: int
68 default: 1200
69 resource_id:
70 description:
71 - Manager ID of the iDRAC.
72 type: str
73 requirements:
74 - "python >= 3.9.6"
75 author:
76 - "Rajshekar P(@rajshekarp87)"
77 - "Saksham Nautiyal (@Saksham-Nautiyal)"
78 attributes:
79 check_mode:
80 description: Runs task to validate without performing action on the target machine.
81 support: full
82 diff_mode:
83 description: Runs the task to report the changes made or to be made.
84 support: none
85 notes:
86 - Run this module from a system that has direct access to Dell iDRAC.
87 - This module supports only iDRAC9 and above.
88 - This module supports IPv4 and IPv6 addresses.
89 """
90
91 EXAMPLES = r"""
92 ---
93 - name: Erase a single component and power on the server
94 dellemc.openmanage.idrac_system_erase:
95 idrac_ip: 198.162.0.1
96 idrac_user: username
97 idrac_password: passw0rd
98 ca_path: "/path/to/ca_cert.pem"
99 component: ["BIOS"]
100 power_on: true
101
102 - name: Erase multiple components and do not power on the server after the erase operation is completed
103 dellemc.openmanage.idrac_system_erase:
104 idrac_ip: 198.162.0.1
105 idrac_user: username
106 idrac_password: passw0rd
107 ca_path: "/path/to/ca_cert.pem"
108 component: ["BIOS", "DIAG", "PERCNVCache"]
109
110 - name: Erase multiple components and do not wait for the job completion
111 dellemc.openmanage.idrac_system_erase:
112 idrac_ip: 198.162.0.1
113 idrac_user: username
114 idrac_password: passw0rd
115 ca_path: "/path/to/ca_cert.pem"
116 component: ["IDRAC", "DPU", "LCData"]
117 job_wait: false
118 """
119
120 RETURN = r'''
121 ---
122 msg:
123 description: Status of the component system erase operation.
124 returned: always
125 type: str
126 sample: "Successfully completed the system erase operation."
127 job_details:
128 description: Returns the output for status of the job.
129 returned: For system erase operation
130 type: dict
131 sample: {
132 "ActualRunningStartTime": null,
133 "ActualRunningStopTime": null,
134 "CompletionTime": "2024-08-06T19:55:01",
135 "Description": "Job Instance",
136 "EndTime": "TIME_NA",
137 "Id": "JID_229917427823",
138 "JobState": "Completed",
139 "JobType": "SystemErase",
140 "Message": "Job completed successfully.",
141 "MessageArgs": [],
142 "[email protected]": 0,
143 "MessageId": "SYS018",
144 "Name": "System_Erase",
145 "PercentComplete": 100,
146 "StartTime": "2024-08-06T19:49:02",
147 "TargetSettingsURI": null
148 }
149 error_info:
150 description: Details of the HTTP Error.
151 returned: On HTTP error
152 type: dict
153 sample: {
154 "error": {
155 "@Message.ExtendedInfo": [
156 {
157 "Message": "Unable to complete the operation because the value NonVolatileMemor entered for the property Component is not in the list
158 of acceptable values.",
159 "MessageArgs": [
160 "NonVolatileMemor",
161 "Component"
162 ],
163 "[email protected]": 2,
164 "MessageId": "IDRAC.2.9.SYS426",
165 "RelatedProperties": [],
166 "[email protected]": 0,
167 "Resolution": "Enter a valid value from the enumeration list that Redfish service supports and retry the operation.For information
168 about valid values, see the iDRAC User's Guide available on the support site.",
169 "Severity": "Warning"
170 },
171 {
172 "Message": "The value 'NonVolatileMemor' for the property Component is not in the list of acceptable values.",
173 "MessageArgs": [
174 "NonVolatileMemor",
175 "Component"
176 ],
177 "[email protected]": 2,
178 "MessageId": "Base.1.12.PropertyValueNotInList",
179 "RelatedProperties": [],
180 "[email protected]": 0,
181 "Resolution": "Choose a value from the enumeration list that the implementation can support and resubmit the request if the operation
182 failed.",
183 "Severity": "Warning"
184 }
185 ],
186 "code": "Base.1.12.GeneralError",
187 "message": "A general error has occurred. See ExtendedInfo for more information"
188 }
189 }
190 '''
191
192
193 import json
194 from urllib.error import HTTPError, URLError
195 from ansible_collections.dellemc.openmanage.plugins.module_utils.idrac_redfish import iDRACRedfishAPI, IdracAnsibleModule
196 from ansible.module_utils.urls import ConnectionError, SSLValidationError
197 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import (
198 get_dynamic_uri, trigger_restart_operation, validate_and_get_first_resource_id_uri, remove_key, idrac_redfish_job_tracking)
199
200
201 MANAGERS_URI = "/redfish/v1/Managers"
202 IDRAC_JOB_URI = "{res_uri}/Oem/Dell/Jobs/{job_id}"
203 ODATA = "@odata.id"
204 ODATA_REGEX = "(.*?)@odata"
205
206 OEM = "Oem"
207 MANUFACTURER = "Dell"
208 LC_SERVICE = "DellLCService"
209 ACTIONS = "Actions"
210 SYSTEM_ERASE = "DellLCService.SystemErase"
211 SYSTEM_ERASE_FETCH = "#DellLCService.SystemErase"
212 COMPONENT_ALLOWABLE_VALUES = "[email protected]"
213 JOB_FILTER = "/Oem/Dell/Jobs?$expand=*($levels=1)"
214
215 ERASE_SUCCESS_COMPLETION_MSG = "Successfully completed the system erase operation."
216 ERASE_SUCCESS_SCHEDULED_MSG = "Successfully submitted the job for system erase operation."
217 ERASE_SUCCESS_POWER_ON_MSG = "Successfully completed the system erase operation and powered on " \
218 "the server."
219 NO_COMPONENT_MATCH = "Unable to complete the operation because the value entered for the " \
220 "'component' is not in the list of acceptable values."
221 TIMEOUT_NEGATIVE_OR_ZERO_MSG = "The value for the 'job_wait_timeout' parameter cannot be " \
222 "negative or zero."
223 WAIT_TIMEOUT_MSG = "The job is not complete after {0} seconds."
224 INVALID_COMPONENT_WARN_MSG = "Erase operation is not performed on these components - " \
225 "{unmatching_components_str_format} as they are either invalid or " \
226 "inapplicable."
227 FAILURE_MSG = "Unable to complete the system erase operation."
228 CHANGES_FOUND_MSG = "Changes found to be applied."
229 NO_CHANGES_FOUND_MSG = "No changes found to be applied."
230
231
232 class SystemErase():
233 def __init__(self, idrac, module):
234 """
235 Initializes the class instance with the provided idrac and module parameters.
236
237 :param idrac: The idrac parameter.
238 :type idrac: Any
239 :param module: The module parameter.
240 :type module: Any
241 """
242 self.idrac = idrac
243 self.module = module
244
245 def execute(self):
246 """
247 Executes the function with the given module.
248
249 :param module: The module to execute.
250 :type module: Any
251 :return: None
252 """
253
254 def get_system_erase_url(self):
255 """
256 Retrieves the URL for the system erase operation.
257
258 Returns:
259 str: The URL for the system erase operation.
260 """
261 url = self.get_url()
262 resp = get_dynamic_uri(self.idrac, url)
263 system_erase_url = (
264 resp.get('Links', {})
265 .get(OEM, {})
266 .get(MANUFACTURER, {})
267 .get(LC_SERVICE, {})
268 .get(ODATA, {})
269 )
270 return system_erase_url
271
272 def get_url(self):
273 """
274 Retrieves the URL for the resource.
275
276 Returns:
277 str: The URL for the resource.
278
279 Raises:
280 AnsibleExitJson: If the resource ID is not found.
281 """
282 res_id = self.module.params.get('resource_id')
283 if res_id:
284 uri = MANAGERS_URI + "/" + res_id
285 else:
286 uri, error_msg = validate_and_get_first_resource_id_uri(
287 self.module, self.idrac, MANAGERS_URI)
288 if error_msg:
289 self.module.exit_json(msg=error_msg, failed=True)
290 return uri
291
292 def get_job_status(self, erase_component_response):
293 """
294 Retrieves the status of a job.
295
296 Args:
297 erase_component_response (object): The response object for the erase component
298 operation.
299
300 Returns:
301 dict: The job details.
302
303 Raises:
304 AnsibleExitJson: If the job tracking times out.
305 """
306 job_wait_timeout = self.module.params.get('job_wait_timeout')
307 res_uri = validate_and_get_first_resource_id_uri(self.module, self.idrac, MANAGERS_URI)
308 job_tracking_uri = erase_component_response.headers.get("Location")
309 job_id = job_tracking_uri.split("/")[-1]
310 job_uri = IDRAC_JOB_URI.format(job_id=job_id, res_uri=res_uri[0])
311 job_failed, msg, job_dict, wait_time = idrac_redfish_job_tracking(
312 self.idrac, job_uri, max_job_wait_sec=job_wait_timeout)
313 job_dict = remove_key(job_dict, regex_pattern=ODATA_REGEX)
314 if int(wait_time) >= int(job_wait_timeout):
315 self.module.exit_json(msg=WAIT_TIMEOUT_MSG.format(
316 job_wait_timeout), changed=True, job_status=job_dict)
317 if job_failed:
318 self.module.exit_json(
319 msg=job_dict.get('Message'),
320 failed=True,
321 job_details=job_dict)
322 return job_dict
323
324 def get_job_details(self, erase_component_response):
325 """
326 Retrieves the details of a job.
327
328 Args:
329 erase_component_response (object): The response object for the erase component
330 operation.
331
332 Returns:
333 dict: The job details.
334
335 Raises:
336 None.
337 """
338 res_uri = validate_and_get_first_resource_id_uri(self.module, self.idrac, MANAGERS_URI)
339 job_tracking_uri = erase_component_response.headers.get("Location")
340 job_id = job_tracking_uri.split("/")[-1]
341 job_uri = IDRAC_JOB_URI.format(job_id=job_id, res_uri=res_uri[0])
342 job_response = self.idrac.invoke_request(job_uri, 'GET')
343 job_details = job_response.json_data
344 job_details = remove_key(job_details, regex_pattern=ODATA_REGEX)
345 return job_details
346
347 def check_system_erase_job(self):
348 """
349 Retrieves the state of the most recent SystemErase job.
350
351 Returns:
352 str: The state of the most recent SystemErase job. Possible values are:
353 - "New"
354 - "Scheduling"
355 - "Running"
356 - "Completed"
357 - "Failed"
358 - "Unknown" if no SystemErase job is found.
359 """
360 url = self.get_url()
361 job_details_url = url + f"/{JOB_FILTER}"
362 job_resp = self.idrac.invoke_request(job_details_url, "GET")
363 job_list = job_resp.json_data.get('Members', [])
364 job_list_reversed = list(reversed(job_list))
365 jb_state = 'Unknown'
366 for jb in job_list_reversed:
367 if jb.get("JobType") == "SystemErase" and jb.get("JobState") in [
368 "New", "Scheduling", "Running", "Completed", "Failed"]:
369 jb_state = jb.get("JobState")
370 break
371 return jb_state
372
373 def validate_job_wait(self):
374 """
375 Validates job_wait and job_wait_timeout parameters.
376 """
377 if self.module.params.get('job_wait') and self.module.params.get('job_wait_timeout') <= 0:
378 self.module.exit_json(
379 msg=TIMEOUT_NEGATIVE_OR_ZERO_MSG, failed=True)
380
381 def check_allowable_value(self, component):
382 """
383 Check if the given component values are in the allowable values.
384
385 Args:
386 component (list): A list of component values.
387
388 Returns:
389 tuple: A tuple containing two lists. The first list contains the matching values, and
390 the second list contains the unmatching values.
391
392 Raises:
393 None.
394 """
395 sytem_erase_url = self.get_system_erase_url()
396 system_erase_response = self.idrac.invoke_request(sytem_erase_url, "GET")
397 allowable_values = system_erase_response.json_data[ACTIONS][SYSTEM_ERASE_FETCH][
398 COMPONENT_ALLOWABLE_VALUES]
399 actual_values = component
400 matching_values = []
401 unmatching_values = []
402 for value in actual_values:
403 if value in allowable_values:
404 matching_values.append(value)
405 else:
406 unmatching_values.append(value)
407 if len(matching_values) == 0 and not self.module.check_mode:
408 self.module.exit_json(msg=NO_COMPONENT_MATCH, skipped=True)
409 if len(unmatching_values) > 0 and self.module.check_mode:
410 if len(matching_values) > 0 :
411 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
412 else:
413 self.module.exit_json(msg=NO_CHANGES_FOUND_MSG, changed=False)
414 return matching_values, unmatching_values
415
416 def warn_unmatching_components(self, unmatching_components):
417 """
418 Warn the user about unmatching components.
419
420 Args:
421 unmatching_components (list): A list of unmatching components.
422
423 Returns:
424 None
425 """
426 if len(unmatching_components) > 0:
427 unmatching_components_str_format = ", '".join(
428 item + "'" for item in unmatching_components)
429 self.module.warn(INVALID_COMPONENT_WARN_MSG.format(
430 unmatching_components_str_format=unmatching_components_str_format))
431
432
433 class EraseComponent(SystemErase):
434 """
435 Class to erase component and perform all the operations
436 """
437 STATUS_SUCCESS = [202]
438 JOB_STATUS = ["New", "Scheduling", "Running"]
439
440 def execute(self):
441 """
442 Executes the system erase operation.
443
444 This function checks if the job_wait parameter is set and validates the job wait.
445 It also checks if the module is in check mode and checks the state of the system erase job.
446 If the job state is in the JOB_STATUS list, it exits with a message indicating no changes
447 found.
448 If the job state is not in the JOB_STATUS list, it exits with a message indicating changes
449 found.
450
451 The function then creates a payload dictionary and assigns the matching components to
452 the 'Component' key.
453 It retrieves the system erase URL and sends a POST request to initiate the erase operation.
454 The response status code is checked and if it is in the STATUS_SUCCESS list, it proceeds to
455 handle the job.
456 If the job_wait parameter is set and the power_on parameter is also set, it retrieves the
457 job status, performs the power on operation, warns about unmatching components, and exits
458 with a message indicating the erase operation was successful and the job details.
459 If the job_wait parameter is set but the power_on parameter is not set, it retrieves the
460 job status, warns about unmatching components, and exits with a message indicating the
461 erase operation was successful and the job details.
462 If the job_wait parameter is not set, it retrieves the job details, warns about unmatching
463 components, and exits with a message indicating the erase operation was scheduled and the
464 job details.
465 If the response status code is not in the STATUS_SUCCESS list, it retrieves the job status
466 and exits with a message indicating the operation failed.
467
468 Returns:
469 None
470 """
471 if self.module.params.get('job_wait'):
472 self.validate_job_wait()
473 component_list = self.module.params.get('component')
474 matching_components, unmatching_components = self.check_allowable_value(component_list)
475 if self.module.check_mode:
476 job_state = self.check_system_erase_job()
477 if job_state in self.JOB_STATUS:
478 self.module.exit_json(msg=NO_CHANGES_FOUND_MSG, changed=False)
479 else:
480 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
481 payload = {}
482 payload["Component"] = matching_components
483 system_erase_url = self.get_system_erase_url()
484 erase_component_response = self.idrac.invoke_request(
485 system_erase_url + f"/{ACTIONS}/{SYSTEM_ERASE}", "POST", data=payload)
486 status = erase_component_response.status_code
487 if status in self.STATUS_SUCCESS:
488 if self.module.params.get('job_wait'):
489 if self.module.params.get('power_on'):
490 job_dict = self.get_job_status(erase_component_response)
491 trigger_restart_operation(self.idrac, restart_type="On")
492 self.warn_unmatching_components(unmatching_components)
493 self.module.exit_json(msg=ERASE_SUCCESS_POWER_ON_MSG, changed=True,
494 job_details=job_dict)
495 else:
496 job_dict = self.get_job_status(erase_component_response)
497 self.warn_unmatching_components(unmatching_components)
498 self.module.exit_json(msg=ERASE_SUCCESS_COMPLETION_MSG, changed=True,
499 job_details=job_dict)
500 else:
501 job_dict = self.get_job_details(erase_component_response)
502 self.warn_unmatching_components(unmatching_components)
503 self.module.exit_json(msg=ERASE_SUCCESS_SCHEDULED_MSG, changed=False,
504 job_details=job_dict)
505 else:
506 job_dict = self.get_job_status(erase_component_response)
507 self.module.exit_json(msg=FAILURE_MSG, failed=True, job_details=job_dict)
508
509
510 def main():
511 """
512 Executes the main function of the program.
513
514 This function initializes the necessary modules and arguments, and then
515 creates an instance of the iDRACRedfishAPI class. It then creates an
516 instance of the EraseComponent class and calls its execute method.
517
518 If any exceptions are raised during the execution of the code, the
519 appropriate error message is returned.
520
521 Parameters:
522 None
523
524 Returns:
525 None
526 """
527 specs = get_argument_spec()
528 module = IdracAnsibleModule(
529 argument_spec=specs,
530 supports_check_mode=True
531 )
532 try:
533 with iDRACRedfishAPI(module.params) as idrac:
534 system_erase_obj = EraseComponent(idrac, module)
535 system_erase_obj.execute()
536 except HTTPError as err:
537 filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX)
538 module.exit_json(msg=str(err), error_info=filter_err, failed=True)
539 except URLError as err:
540 module.exit_json(msg=str(err), unreachable=True)
541 except (SSLValidationError, ConnectionError, TypeError, ValueError, OSError) as err:
542 module.exit_json(msg=str(err), failed=True)
543
544
545 def get_argument_spec():
546 """
547 Returns a dictionary specifying the argument specification for the function.
548
549 Parameters:
550 None
551
552 Returns:
553 dict: A dictionary containing the argument specification.
554 The dictionary has the following keys:
555 - "component": A dictionary specifying the type and required status of the
556 "component" argument.
557 - "power_on": A dictionary specifying the type and default value of the "power_on"
558 argument.
559 - "job_wait": A dictionary specifying the type and default value of the "job_wait"
560 argument.
561 - "job_wait_timeout": A dictionary specifying the type and default value of the
562 "job_wait_timeout" argument.
563 - "resource_id": A dictionary specifying the type of the "resource_id" argument.
564 """
565 return {
566 "component": {"type": 'list', "elements": 'str', "required": True},
567 "power_on": {"type": 'bool', "default": False},
568 "job_wait": {"type": 'bool', "default": True},
569 "job_wait_timeout": {"type": 'int', "default": 1200},
570 "resource_id": {"type": 'str'}
571 }
572
573
574 if __name__ == '__main__':
575 main()