Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 7.6.0
7 # Copyright (C) 2018-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 = """
18 ---
19 module: idrac_bios
20 short_description: Modify and clear BIOS attributes, reset BIOS settings and configure boot sources
21 version_added: "2.1.0"
22 description:
23 - This module allows to modify the BIOS attributes. Also clears pending BIOS attributes and resets BIOS to default settings.
24 - Boot sources can be enabled or disabled. Boot sequence can be configured.
25 extends_documentation_fragment:
26 - dellemc.openmanage.idrac_auth_options
27 options:
28 share_name:
29 type: str
30 description: (deprecated)Network share or a local path.
31 share_user:
32 type: str
33 description: "(deprecated)Network share user name. Use the format 'user@domain' or domain//user if user
34 is part of a domain. This option is mandatory for CIFS share."
35 share_password:
36 type: str
37 description: (deprecated)Network share user password. This option is mandatory for CIFS share.
38 aliases: ['share_pwd']
39 share_mnt:
40 type: str
41 description: "(deprecated)Local mount path of the network share with read-write permission for ansible user.
42 This option is mandatory for network shares."
43 apply_time:
44 type: str
45 description:
46 - Apply time of the I(attributes).
47 - This is applicable only to I(attributes).
48 - "C(Immediate) Allows the user to immediately reboot the host and apply the changes. I(job_wait)
49 is applicable."
50 - C(OnReset) Allows the user to apply the changes on the next reboot of the host server.
51 - "C(AtMaintenanceWindowStart) Allows the user to apply at the start of a maintenance window as specified
52 in I(maintenance_window). A reboot job will be scheduled."
53 - "C(InMaintenanceWindowOnReset) Allows to apply after a manual reset but within the maintenance window as
54 specified in I(maintenance_window)."
55 choices: [Immediate, OnReset, AtMaintenanceWindowStart, InMaintenanceWindowOnReset]
56 default: Immediate
57 maintenance_window:
58 type: dict
59 description:
60 - Option to schedule the maintenance window.
61 - This is required when I(apply_time) is C(AtMaintenanceWindowStart) or C(InMaintenanceWindowOnReset).
62 suboptions:
63 start_time:
64 type: str
65 description:
66 - The start time for the maintenance window to be scheduled.
67 - "The format is YYYY-MM-DDThh:mm:ss<offset>"
68 - "<offset> is the time offset from UTC that the current timezone set in
69 iDRAC in the format: +05:30 for IST."
70 required: true
71 duration:
72 type: int
73 description:
74 - The duration in seconds for the maintenance window.
75 required: true
76 attributes:
77 type: dict
78 description:
79 - "Dictionary of BIOS attributes and value pair. Attributes should be
80 part of the Redfish Dell BIOS Attribute Registry. Use
81 U(https://I(idrac_ip)/redfish/v1/Systems/System.Embedded.1/Bios) to view the Redfish URI."
82 - This is mutually exclusive with I(boot_sources), I(clear_pending), and I(reset_bios).
83 boot_sources:
84 type: list
85 elements: raw
86 description:
87 - (deprecated)List of boot devices to set the boot sources settings.
88 - I(boot_sources) is mutually exclusive with I(attributes), I(clear_pending), and I(reset_bios).
89 - I(job_wait) is not applicable. The module waits till the completion of this task.
90 - This feature is deprecated, please use M(dellemc.openmanage.idrac_boot) for configuring boot sources.
91 clear_pending:
92 type: bool
93 description:
94 - Allows the user to clear all pending BIOS attributes changes.
95 - C(true) will discard any pending changes to bios attributes or remove job if in scheduled state.
96 - This operation will not create any job.
97 - C(false) will not perform any operation.
98 - This is mutually exclusive with I(boot_sources), I(attributes), and I(reset_bios).
99 - C(Note) Any BIOS job scheduled due to boot sources configuration will not be cleared.
100 reset_bios:
101 type: bool
102 description:
103 - Resets the BIOS to default settings and triggers a reboot of host system.
104 - This is applied to the host after the restart.
105 - This operation will not create any job.
106 - C(false) will not perform any operation.
107 - This is mutually exclusive with I(boot_sources), I(attributes), and I(clear_pending).
108 - When C(true), this action will always report as changes found to be applicable.
109 reset_type:
110 type: str
111 description:
112 - C(force_restart) Forcefully reboot the host system.
113 - C(graceful_restart) Gracefully reboot the host system.
114 - This is applicable for I(reset_bios), and I(attributes) when I(apply_time) is C(Immediate).
115 choices: [graceful_restart, force_restart]
116 default: graceful_restart
117 job_wait:
118 type: bool
119 description:
120 - Provides the option to wait for job completion.
121 - This is applicable for I(attributes) when I(apply_time) is C(Immediate).
122 default: true
123 job_wait_timeout:
124 type: int
125 description:
126 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
127 - This option is applicable when I(job_wait) is C(true).
128 default: 1200
129 requirements:
130 - "omsdk >= 1.2.490"
131 - "python >= 3.9.6"
132 author:
133 - "Felix Stephen (@felixs88)"
134 - "Anooja Vardhineni (@anooja-vardhineni)"
135 - "Jagadeesh N V (@jagadeeshnv)"
136 - "Shivam Sharma (@shivam-sharma)"
137 notes:
138 - omsdk is required to be installed only for I(boot_sources) operation.
139 - This module requires 'Administrator' privilege for I(idrac_user).
140 - Run this module from a system that has direct access to Dell iDRAC.
141 - This module supports both IPv4 and IPv6 address for I(idrac_ip).
142 - This module supports C(check_mode).
143 """
144
145 EXAMPLES = """
146 ---
147 - name: Configure generic attributes of the BIOS
148 dellemc.openmanage.idrac_bios:
149 idrac_ip: "192.168.0.1"
150 idrac_user: "user_name"
151 idrac_password: "user_password"
152 ca_path: "/path/to/ca_cert.pem"
153 attributes:
154 BootMode: "Bios"
155 OneTimeBootMode: "Enabled"
156 BootSeqRetry: "Enabled"
157
158 - name: Configure PXE generic attributes
159 dellemc.openmanage.idrac_bios:
160 idrac_ip: "192.168.0.1"
161 idrac_user: "user_name"
162 idrac_password: "user_password"
163 ca_path: "/path/to/ca_cert.pem"
164 attributes:
165 PxeDev1EnDis: "Enabled"
166 PxeDev1Protocol: "IPV4"
167 PxeDev1VlanEnDis: "Enabled"
168 PxeDev1VlanId: 1
169 PxeDev1Interface: "NIC.Embedded.1-1-1"
170 PxeDev1VlanPriority: 2
171
172 - name: Configure BIOS attributes at Maintenance window
173 dellemc.openmanage.idrac_bios:
174 idrac_ip: "192.168.0.1"
175 idrac_user: "user_name"
176 idrac_password: "user_password"
177 ca_path: "/path/to/ca_cert.pem"
178 apply_time: AtMaintenanceWindowStart
179 maintenance_window:
180 start_time: "2022-09-30T05:15:40-05:00"
181 duration: 600
182 attributes:
183 BootMode: "Bios"
184 OneTimeBootMode: "Enabled"
185 BootSeqRetry: "Enabled"
186
187 - name: Clear pending BIOS attributes
188 dellemc.openmanage.idrac_bios:
189 idrac_ip: "192.168.0.1"
190 idrac_user: "user_name"
191 idrac_password: "user_password"
192 ca_path: "/path/to/ca_cert.pem"
193 clear_pending: true
194
195 - name: Reset BIOS attributes to default settings.
196 dellemc.openmanage.idrac_bios:
197 idrac_ip: "192.168.0.1"
198 idrac_user: "user_name"
199 idrac_password: "user_password"
200 validate_certs: false
201 reset_bios: true
202
203 - name: Configure boot sources
204 dellemc.openmanage.idrac_bios:
205 idrac_ip: "192.168.0.1"
206 idrac_user: "user_name"
207 idrac_password: "user_password"
208 ca_path: "/path/to/ca_cert.pem"
209 boot_sources:
210 - Name: "NIC.Integrated.1-2-3"
211 Enabled: true
212 Index: 0
213
214 - name: Configure multiple boot sources
215 dellemc.openmanage.idrac_bios:
216 idrac_ip: "192.168.0.1"
217 idrac_user: "user_name"
218 idrac_password: "user_password"
219 ca_path: "/path/to/ca_cert.pem"
220 boot_sources:
221 - Name: "NIC.Integrated.1-1-1"
222 Enabled: true
223 Index: 0
224 - Name: "NIC.Integrated.2-2-2"
225 Enabled: true
226 Index: 1
227 - Name: "NIC.Integrated.3-3-3"
228 Enabled: true
229 Index: 2
230
231 - name: Configure boot sources - Enabling
232 dellemc.openmanage.idrac_bios:
233 idrac_ip: "192.168.0.1"
234 idrac_user: "user_name"
235 idrac_password: "user_password"
236 ca_path: "/path/to/ca_cert.pem"
237 boot_sources:
238 - Name: "NIC.Integrated.1-1-1"
239 Enabled: true
240
241 - name: Configure boot sources - Index
242 dellemc.openmanage.idrac_bios:
243 idrac_ip: "192.168.0.1"
244 idrac_user: "user_name"
245 idrac_password: "user_password"
246 ca_path: "/path/to/ca_cert.pem"
247 boot_sources:
248 - Name: "NIC.Integrated.1-1-1"
249 Index: 0
250 """
251
252 RETURN = """
253 ---
254 status_msg:
255 description: Overall status of the bios operation.
256 returned: success
257 type: str
258 sample: Successfully cleared pending BIOS attributes.
259 msg:
260 description: Status of the job for I(boot_sources) or status of the action performed on bios.
261 returned: success
262 type: dict
263 sample: {
264 "CompletionTime": "2020-04-20T18:50:20",
265 "Description": "Job Instance",
266 "EndTime": null,
267 "Id": "JID_873888162305",
268 "JobState": "Completed",
269 "JobType": "ImportConfiguration",
270 "Message": "Successfully imported and applied Server Configuration Profile.",
271 "MessageArgs": [],
272 "MessageId": "SYS053",
273 "Name": "Import Configuration",
274 "PercentComplete": 100,
275 "StartTime": "TIME_NOW",
276 "Status": "Success",
277 "TargetSettingsURI": null,
278 "retval": true
279 }
280 invalid_attributes:
281 type: dict
282 description: Dict of invalid attributes provided.
283 returned: on invalid attributes or values.
284 sample: {
285 "PxeDev1VlanId": "Not a valid integer.",
286 "AcPwrRcvryUserDelay": "Integer out of valid range.",
287 "BootSeqRetry": "Invalid value for Enumeration.",
288 "Proc1Brand": "Read only Attribute cannot be modified.",
289 "AssetTag": "Attribute does not exist."
290 }
291 error_info:
292 description: Details of the HTTP Error.
293 returned: on HTTP error
294 type: dict
295 sample: {
296 "error": {
297 "code": "Base.1.0.GeneralError",
298 "message": "A general error has occurred. See ExtendedInfo for more information.",
299 "@Message.ExtendedInfo": [
300 {
301 "MessageId": "GEN1234",
302 "RelatedProperties": [],
303 "Message": "Unable to process the request because an error occurred.",
304 "MessageArgs": [],
305 "Severity": "Critical",
306 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
307 }
308 ]
309 }
310 }
311 """
312
313 SYSTEM_URI = "/redfish/v1/Systems/System.Embedded.1"
314 MANAGER_URI = "/redfish/v1/Managers/iDRAC.Embedded.1"
315 BIOS_URI = "/redfish/v1/Systems/System.Embedded.1/Bios"
316 BIOS_REGISTRY = "/redfish/v1/Systems/System.Embedded.1/Bios/BiosRegistry"
317 CLEAR_PENDING_URI = "/redfish/v1/Systems/System.Embedded.1/Bios/Settings/Actions/Oem/DellManager.ClearPending"
318 RESET_BIOS_DEFAULT = "/redfish/v1/Systems/System.Embedded.1/Bios/Actions/Bios.ResetBios"
319 BIOS_SETTINGS = "/redfish/v1/Systems/System.Embedded.1/Bios/Settings"
320 POWER_HOST_URI = "/redfish/v1/Systems/System.Embedded.1/Actions/ComputerSystem.Reset"
321 IDRAC_JOBS_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs"
322 iDRAC_JOBS_EXP = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs?$expand=*($levels=1)"
323 iDRAC_JOB_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs/{job_id}"
324 LOG_SERVICE_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/LogServices/Lclog"
325 iDRAC9_LC_LOG = "/redfish/v1/Managers/iDRAC.Embedded.1/LogServices/Lclog/Entries"
326 iDRAC8_LC_LOG = "/redfish/v1/Managers/iDRAC.Embedded.1/Logs/Lclog"
327 LC_LOG_FILTER = "?$filter=MessageId%20eq%20'UEFI0157'"
328 CPU_RST_FILTER = "?$filter=MessageId%20eq%20'SYS1003'"
329 BIOS_JOB_RUNNING = "BIOS Config job is running. Wait for the job to complete."
330 NO_CHANGES_MSG = "No changes found to be applied."
331 CHANGES_MSG = "Changes found to be applied."
332 SUCCESS_CLEAR = "Successfully cleared the pending BIOS attributes."
333 SUCCESS_COMPLETE = "Successfully applied the BIOS attributes update."
334 SCHEDULED_SUCCESS = "Successfully scheduled the job for the BIOS attributes update."
335 COMMITTED_SUCCESS = "Successfully committed changes. The job is in pending state. The changes will be applied {0}"
336 RESET_TRIGGERRED = "Reset BIOS action triggered successfully."
337 HOST_RESTART_FAILED = "Unable to restart the host. Check the host status and restart the host manually."
338 BIOS_RESET_TRIGGERED = "The BIOS reset action has been triggered successfully. The host reboot is complete."
339 BIOS_RESET_COMPLETE = "BIOS reset to defaults has been completed successfully."
340 BIOS_RESET_PENDING = "Pending attributes to be applied. " \
341 "Clear or apply the pending changes before resetting the BIOS."
342 FORCE_BIOS_DELETE = "The BIOS configuration job is scheduled. Use 'force' to delete the job."
343 INVALID_ATTRIBUTES_MSG = "The values specified for the attributes are invalid."
344 UNSUPPORTED_APPLY_TIME = "Apply time {0} is not supported."
345 MAINTENANCE_OFFSET = "The maintenance time must be post-fixed with local offset to {0}."
346 MAINTENANCE_TIME = "The specified maintenance time window occurs in the past, " \
347 "provide a future time to schedule the maintenance window."
348 NEGATIVE_TIMEOUT_MESSAGE = "The parameter job_wait_timeout value cannot be negative or zero."
349 POWER_CHECK_RETRIES = 30
350 POWER_CHECK_INTERVAL = 10
351 ODATA_REGEX = "(.*?)@odata"
352 AUTH_ERROR_MSG = "Unable to communicate with iDRAC {0}. This may be due to one of the following: " \
353 "Incorrect username or password, unreachable iDRAC IP or a failure in TLS/SSL handshake."
354
355
356 import json
357 import time
358 from ansible.module_utils.common.dict_transformations import recursive_diff
359 from ansible.module_utils.six.moves.urllib.error import HTTPError, URLError
360 from ansible.module_utils.urls import ConnectionError, SSLValidationError
361 from ansible_collections.dellemc.openmanage.plugins.module_utils.dellemc_idrac import iDRACConnection, idrac_auth_params
362 from ansible_collections.dellemc.openmanage.plugins.module_utils.idrac_redfish import iDRACRedfishAPI
363 from ansible.module_utils.basic import AnsibleModule
364 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import idrac_redfish_job_tracking, remove_key, \
365 strip_substr_dict
366
367
368 def run_server_bios_config(idrac, module):
369 msg = {}
370 idrac.use_redfish = True
371 _validate_params(module.params['boot_sources'])
372 if module.check_mode:
373 idrac.config_mgr.is_change_applicable()
374 msg = idrac.config_mgr.configure_boot_sources(input_boot_devices=module.params['boot_sources'])
375 return msg
376
377
378 def _validate_params(params):
379 """
380 Validate list of dict params.
381 :param params: Ansible list of dict
382 :return: bool or error.
383 """
384 fields = [
385 {"name": "Name", "type": str, "required": True},
386 {"name": "Index", "type": int, "required": False, "min": 0},
387 {"name": "Enabled", "type": bool, "required": False}
388 ]
389 default = ['Name', 'Index', 'Enabled']
390 for attr in params:
391 if not isinstance(attr, dict):
392 msg = "attribute values must be of type: dict. {0} ({1}) provided.".format(attr, type(attr))
393 return msg
394 elif all(k in default for k in attr.keys()):
395 msg = check_params(attr, fields)
396 return msg
397 else:
398 msg = "attribute keys must be one of the {0}.".format(default)
399 return msg
400 msg = _validate_name_index_duplication(params)
401 return msg
402
403
404 def _validate_name_index_duplication(params):
405 """
406 Validate for duplicate names and indices.
407 :param params: Ansible list of dict
408 :return: bool or error.
409 """
410 msg = ""
411 for i in range(len(params) - 1):
412 for j in range(i + 1, len(params)):
413 if params[i]['Name'] == params[j]['Name']:
414 msg = "duplicate name {0}".format(params[i]['Name'])
415 return msg
416 return msg
417
418
419 def check_params(each, fields):
420 """
421 Each dictionary parameters validation as per the rule defined in fields.
422 :param each: validating each dictionary
423 :param fields: list of dictionary which has the set of rules.
424 :return: tuple which has err and message
425 """
426 msg = ""
427 for f in fields:
428 if f['name'] not in each and f["required"] is False:
429 continue
430 if not f["name"] in each and f["required"] is True:
431 msg = "{0} is required and must be of type: {1}".format(f['name'], f['type'])
432 elif not isinstance(each[f["name"]], f["type"]):
433 msg = "{0} must be of type: {1}. {2} ({3}) provided.".format(
434 f['name'], f['type'], each[f['name']], type(each[f['name']]))
435 elif f['name'] in each and isinstance(each[f['name']], int) and 'min' in f:
436 if each[f['name']] < f['min']:
437 msg = "{0} must be greater than or equal to: {1}".format(f['name'], f['min'])
438 return msg
439
440
441 def check_scheduled_bios_job(redfish_obj):
442 job_resp = redfish_obj.invoke_request(iDRAC_JOBS_EXP, "GET")
443 job_list = job_resp.json_data.get('Members', [])
444 sch_jb = None
445 jb_state = 'Unknown'
446 for jb in job_list:
447 if jb.get("JobType") == "BIOSConfiguration" and jb.get("JobState") in ["Scheduled", "Running", "Starting"]:
448 sch_jb = jb['Id']
449 jb_state = jb.get("JobState")
450 break
451 return sch_jb, jb_state
452
453
454 def delete_scheduled_bios_job(redfish_obj, job_id):
455 resp = redfish_obj.invoke_request(iDRAC_JOB_URI.format(job_id=job_id), "DELETE")
456 return resp
457
458
459 def get_pending_attributes(redfish_obj):
460 try:
461 resp = redfish_obj.invoke_request(BIOS_SETTINGS, "GET")
462 attr = resp.json_data.get("Attributes")
463 except Exception:
464 attr = {}
465 return attr
466
467
468 def get_power_state(redfish_obj):
469 retries = 3
470 pstate = "Unknown"
471 while retries > 0:
472 try:
473 resp = redfish_obj.invoke_request(SYSTEM_URI, "GET")
474 pstate = resp.json_data.get("PowerState")
475 break
476 except Exception:
477 retries = retries - 1
478 return pstate
479
480
481 def power_act_host(redfish_obj, p_state):
482 try:
483 redfish_obj.invoke_request(POWER_HOST_URI, "POST", data={'ResetType': p_state})
484 p_act = True
485 except HTTPError:
486 p_act = False
487 return p_act
488
489
490 def track_power_state(redfish_obj, desired_state, retries=POWER_CHECK_RETRIES, interval=POWER_CHECK_INTERVAL):
491 count = retries
492 while count:
493 ps = get_power_state(redfish_obj)
494 if ps in desired_state:
495 achieved = True
496 break
497 else:
498 time.sleep(interval)
499 count = count - 1
500 else:
501 achieved = False
502 return achieved
503
504
505 def reset_host(module, redfish_obj):
506 reset_type = module.params.get('reset_type')
507 p_state = 'On'
508 ps = get_power_state(redfish_obj)
509 on_state = ["On"]
510 if ps in on_state:
511 p_state = 'GracefulShutdown'
512 if 'force' in reset_type:
513 p_state = 'ForceOff'
514 p_act = power_act_host(redfish_obj, p_state)
515 if not p_act:
516 module.exit_json(failed=True, status_msg=HOST_RESTART_FAILED)
517 state_achieved = track_power_state(redfish_obj, ["Off"]) # 30x10= 300 secs
518 p_state = "On"
519 if not state_achieved:
520 time.sleep(10)
521 p_state = "ForceRestart"
522 p_act = power_act_host(redfish_obj, p_state)
523 if not p_act:
524 module.exit_json(failed=True, status_msg=HOST_RESTART_FAILED)
525 state_achieved = track_power_state(redfish_obj, on_state) # 30x10= 300 secs
526 return state_achieved
527
528
529 def get_current_time(redfish_obj):
530 try:
531 resp = redfish_obj.invoke_request(MANAGER_URI, "GET")
532 curr_time = resp.json_data.get("DateTime")
533 date_offset = resp.json_data.get("DateTimeLocalOffset")
534 except Exception:
535 return None, None
536 return curr_time, date_offset
537
538
539 def track_log_entry(redfish_obj):
540 msg = None
541 filter_list = [LC_LOG_FILTER, CPU_RST_FILTER]
542 intrvl = 15
543 retries = 360 // intrvl
544 time.sleep(intrvl)
545 try:
546 resp = redfish_obj.invoke_request(LOG_SERVICE_URI, "GET")
547 uri = resp.json_data.get('Entries').get('@odata.id')
548 fltr_uris = []
549 for fltr in filter_list:
550 fltr_uris.append("{0}{1}".format(uri, fltr))
551 flen = len(fltr_uris)
552 fln = 1
553 pvt = retries // 3 # check for the SYS1003 after 2/3rds of retries
554 curr_time = resp.json_data.get('DateTime')
555 while retries:
556 resp = redfish_obj.invoke_request(fltr_uris[retries % fln], "GET")
557 logs_list = resp.json_data.get("Members")
558 for log in logs_list:
559 if log.get('Created') > curr_time:
560 msg = BIOS_RESET_COMPLETE
561 break
562 if msg:
563 break
564 retries = retries - 1
565 time.sleep(intrvl)
566 if retries < pvt:
567 fln = flen
568 else:
569 # msg = "{0}{1}".format(BIOS_RESET_TRIGGERED, "LOOPOVER")
570 msg = BIOS_RESET_TRIGGERED
571 except Exception:
572 # msg = "{0}{1}".format(BIOS_RESET_TRIGGERED, str(ex))
573 msg = BIOS_RESET_TRIGGERED
574 return msg
575
576
577 def reset_bios(module, redfish_obj):
578 attr = get_pending_attributes(redfish_obj)
579 if attr:
580 module.exit_json(status_msg=BIOS_RESET_PENDING, failed=True)
581 if module.check_mode:
582 module.exit_json(status_msg=CHANGES_MSG, changed=True)
583 redfish_obj.invoke_request(RESET_BIOS_DEFAULT, "POST", data={}, dump=True)
584 reset_success = reset_host(module, redfish_obj)
585 if not reset_success:
586 module.exit_json(failed=True, status_msg="{0} {1}".format(RESET_TRIGGERRED, HOST_RESTART_FAILED))
587 log_msg = track_log_entry(redfish_obj)
588 module.exit_json(status_msg=log_msg, changed=True)
589
590
591 def clear_pending_bios(module, redfish_obj):
592 attr = get_pending_attributes(redfish_obj)
593 if not attr:
594 module.exit_json(status_msg=NO_CHANGES_MSG)
595 job_id, job_state = check_scheduled_bios_job(redfish_obj)
596 if job_id:
597 if job_state in ["Running", "Starting"]:
598 module.exit_json(failed=True, status_msg=BIOS_JOB_RUNNING, job_id=job_id)
599 elif job_state in ["Scheduled", "Scheduling"]:
600 # if module.params.get("force", True) == False:
601 # module.exit_json(status_msg=FORCE_BIOS_DELETE, job_id=job_id, failed=True)
602 if module.check_mode:
603 module.exit_json(status_msg=CHANGES_MSG, changed=True)
604 delete_scheduled_bios_job(redfish_obj, job_id)
605 module.exit_json(status_msg=SUCCESS_CLEAR, changed=True)
606 if module.check_mode:
607 module.exit_json(status_msg=CHANGES_MSG, changed=True)
608 redfish_obj.invoke_request(CLEAR_PENDING_URI, "POST", data="{}", dump=False)
609 module.exit_json(status_msg=SUCCESS_CLEAR, changed=True)
610
611
612 def get_attributes_registry(idrac):
613 reggy = {}
614 try:
615 resp = idrac.invoke_request(BIOS_REGISTRY, "GET")
616 attr_list = resp.json_data.get("RegistryEntries").get("Attributes")
617 reggy = dict((x["AttributeName"], x) for x in attr_list)
618 except Exception:
619 reggy = {}
620 return reggy
621
622
623 def check_bios_attributes_enum(val_dict, invalid, k, v):
624 enum_type = val_dict.get("Type")
625 if enum_type == "Enumeration":
626 found = False
627 for val in val_dict.get("Value", []):
628 if v == val.get("ValueName"):
629 found = True
630 break
631 if not found:
632 invalid[k] = "Invalid value for enumeration."
633
634
635 def check_bios_attributes_int(val_dict, invalid, k, v):
636 field_type = val_dict.get("Type")
637 if field_type == "Integer":
638 try:
639 i = int(v)
640 except Exception:
641 invalid[k] = "Invalid integer."
642 else:
643 if not (val_dict.get("LowerBound") <= i <= val_dict.get("UpperBound")):
644 invalid[k] = "Integer not in a valid range."
645
646
647 def validate_vs_registry(registry, attr_dict):
648 invalid = {}
649 for k, v in attr_dict.items():
650 if k in registry:
651 val_dict = registry.get(k)
652 check_bios_attributes_enum(val_dict, invalid, k, v)
653 check_bios_attributes_int(val_dict, invalid, k, v)
654 else:
655 invalid[k] = "The attribute does not exist."
656
657 # Removing invalid keys from the payload
658 if invalid:
659 for k, v in invalid.items():
660 del attr_dict[k]
661 return invalid
662
663
664 def get_current_attributes(redfish_obj):
665 try:
666 resp = redfish_obj.invoke_request(BIOS_URI, "GET")
667 setting = resp.json_data
668 except Exception:
669 setting = {}
670 return setting
671
672
673 def validate_time(module, redfish_obj, mtime):
674 curr_time, date_offset = get_current_time(redfish_obj)
675 if not mtime.endswith(date_offset):
676 module.exit_json(failed=True, status_msg=MAINTENANCE_OFFSET.format(date_offset))
677 if mtime < curr_time:
678 module.exit_json(failed=True, status_msg=MAINTENANCE_TIME)
679
680
681 def get_redfish_apply_time(module, redfish_obj, aplytm, rf_settings):
682 rf_set = {}
683 reboot_req = False
684 if rf_settings:
685 if 'Maintenance' in aplytm:
686 if aplytm not in rf_settings:
687 module.exit_json(failed=True, status_msg=UNSUPPORTED_APPLY_TIME.format(aplytm))
688 else:
689 rf_set['ApplyTime'] = aplytm
690 m_win = module.params.get('maintenance_window')
691 validate_time(module, redfish_obj, m_win.get('start_time'))
692 rf_set['MaintenanceWindowStartTime'] = m_win.get('start_time')
693 rf_set['MaintenanceWindowDurationInSeconds'] = m_win.get('duration')
694 else: # assuming OnReset is always
695 if aplytm == "Immediate":
696 if aplytm not in rf_settings:
697 reboot_req = True
698 aplytm = 'OnReset'
699 rf_set['ApplyTime'] = aplytm
700 return rf_set, reboot_req
701
702
703 def trigger_bios_job(redfish_obj):
704 job_id = None
705 payload = {"TargetSettingsURI": BIOS_SETTINGS}
706 resp = redfish_obj.invoke_request(IDRAC_JOBS_URI, "POST", data=payload)
707 job_id = resp.headers["Location"].split("/")[-1]
708 return job_id
709
710
711 def apply_attributes(module, redfish_obj, pending, rf_settings):
712 payload = {"Attributes": pending}
713 aplytm = module.params.get('apply_time')
714 rf_set, reboot_required = get_redfish_apply_time(module, redfish_obj, aplytm, rf_settings)
715 if rf_set:
716 payload["@Redfish.SettingsApplyTime"] = rf_set
717 resp = redfish_obj.invoke_request(BIOS_SETTINGS, "PATCH", data=payload)
718 if rf_set:
719 redfish_obj.invoke_request(resp.headers["Location"], "GET")
720 job_id = resp.headers["Location"].split("/")[-1]
721 else:
722 if aplytm == "Immediate":
723 reboot_required = True
724 job_id = trigger_bios_job(redfish_obj)
725 return job_id, reboot_required
726
727
728 def check_pending_jobs(module, redfish_obj, pending):
729 if pending:
730 job_id, job_state = check_scheduled_bios_job(redfish_obj)
731 if job_id:
732 if job_state in ["Running", "Starting"]:
733 module.exit_json(status_msg=BIOS_JOB_RUNNING, job_id=job_id, failed=True)
734 elif job_state in ["Scheduled", "Scheduling"]:
735 # changes staged in pending attributes
736 # if module.params.get("force", True) == False:
737 # module.exit_json(status_msg=FORCE_BIOS_DELETE, job_id=job_id, failed=True)
738 delete_scheduled_bios_job(redfish_obj, job_id)
739
740
741 def wait_for_job_completion(module, redfish_obj, reboot_required, job_id, invalid):
742 if reboot_required and job_id:
743 reset_success = reset_host(module, redfish_obj)
744 if not reset_success:
745 module.exit_json(status_msg="Attributes committed but reboot has failed {0}".format(HOST_RESTART_FAILED),
746 failed=True)
747 if module.params.get("job_wait"):
748 job_details = idrac_redfish_job_tracking(
749 redfish_obj, iDRAC_JOB_URI.format(job_id=job_id),
750 max_job_wait_sec=module.params.get('job_wait_timeout'))
751 job_failed = job_details[0]
752 msg = job_details[1]
753 job_dict = job_details[2]
754 if job_failed:
755 module.exit_json(failed=True, status_msg=msg, job_id=job_id)
756 module.exit_json(status_msg=SUCCESS_COMPLETE, job_id=job_id, msg=strip_substr_dict(job_dict), invalid_attributes=invalid, changed=True)
757 else:
758 module.exit_json(status_msg=SCHEDULED_SUCCESS, job_id=job_id, invalid_attributes=invalid, changed=True)
759
760
761 def attributes_config(module, redfish_obj):
762 curr_resp = get_current_attributes(redfish_obj)
763 curr_attr = curr_resp.get("Attributes", {})
764 inp_attr = module.params.get("attributes")
765 diff_tuple = recursive_diff(inp_attr, curr_attr)
766 attr = {}
767 if diff_tuple:
768 if diff_tuple[0]:
769 attr = diff_tuple[0]
770 invalid = {}
771 attr_registry = get_attributes_registry(redfish_obj)
772 if attr_registry:
773 invalid.update(validate_vs_registry(attr_registry, attr))
774 if not attr:
775 module.exit_json(status_msg=NO_CHANGES_MSG)
776 if module.check_mode:
777 module.exit_json(status_msg=CHANGES_MSG, changed=True)
778 pending = get_pending_attributes(redfish_obj)
779 pending.update(attr)
780 check_pending_jobs(module, redfish_obj, pending)
781 rf_settings = curr_resp.get("@Redfish.Settings", {}).get("SupportedApplyTimes", [])
782 job_id, reboot_required = apply_attributes(module, redfish_obj, pending, rf_settings)
783 wait_for_job_completion(module, redfish_obj, reboot_required, job_id, invalid)
784 module.exit_json(status_msg=COMMITTED_SUCCESS.format(module.params.get('apply_time')),
785 job_id=job_id, invalid_attributes=invalid, changed=True)
786
787
788 def validate_negative_job_time_out(module):
789 if module.params.get("job_wait_timeout") <= 0:
790 module.fail_json(msg=NEGATIVE_TIMEOUT_MESSAGE)
791
792
793 def main():
794 specs = {
795 "share_name": {"type": 'str'},
796 "share_user": {"type": 'str'},
797 "share_password": {"type": 'str', "aliases": ['share_pwd'], "no_log": True},
798 "share_mnt": {"type": 'str'},
799 "attributes": {"type": 'dict'},
800 "boot_sources": {"type": 'list', 'elements': 'raw'},
801 "apply_time": {"type": 'str', "default": 'Immediate',
802 "choices": ['Immediate', 'OnReset', 'AtMaintenanceWindowStart', 'InMaintenanceWindowOnReset']},
803 "maintenance_window": {"type": 'dict',
804 "options": {"start_time": {"type": 'str', "required": True},
805 "duration": {"type": 'int', "required": True}}},
806 "clear_pending": {"type": 'bool'},
807 "reset_bios": {"type": 'bool'},
808 "reset_type": {"type": 'str', "choices": ['graceful_restart', 'force_restart'], "default": 'graceful_restart'},
809 "job_wait": {"type": 'bool', "default": True},
810 "job_wait_timeout": {"type": 'int', "default": 1200}
811 }
812 specs.update(idrac_auth_params)
813 module = AnsibleModule(
814 argument_spec=specs,
815 mutually_exclusive=[('boot_sources', 'attributes', 'clear_pending', 'reset_bios')],
816 required_one_of=[('boot_sources', 'attributes', 'clear_pending', 'reset_bios')],
817 required_if=[["apply_time", "AtMaintenanceWindowStart", ("maintenance_window",)],
818 ["apply_time", "InMaintenanceWindowOnReset", ("maintenance_window",)]],
819 supports_check_mode=True)
820 validate_negative_job_time_out(module)
821 try:
822 msg = {}
823 if module.params.get("boot_sources") is not None:
824 with iDRACConnection(module.params) as idrac:
825 msg = run_server_bios_config(idrac, module)
826 changed, failed = False, False
827 if msg.get('Status') == "Success":
828 changed = True
829 if msg.get('Message') == "No changes found to commit!":
830 changed = False
831 elif msg.get('Status') == "Failed":
832 failed = True
833 module.exit_json(msg=msg, changed=changed, failed=failed)
834 else:
835 with iDRACRedfishAPI(module.params, req_session=True) as redfish_obj:
836 _handle_redfish_api(module, redfish_obj)
837 module.exit_json(status_msg=NO_CHANGES_MSG)
838 except HTTPError as err:
839 filter_err = remove_key(json.load(err), regex_pattern=ODATA_REGEX)
840 module.exit_json(msg=str(err), error_info=filter_err, failed=True)
841 except URLError:
842 module.exit_json(msg=AUTH_ERROR_MSG.format(module.params["idrac_ip"]), unreachable=True)
843 except (ImportError, ValueError, RuntimeError, SSLValidationError,
844 ConnectionError, KeyError, TypeError, IndexError) as e:
845 module.exit_json(msg=str(e), failed=True)
846
847
848 def _handle_redfish_api(module, redfish_obj):
849 if module.params.get("clear_pending"):
850 clear_pending_bios(module, redfish_obj)
851 if module.params.get("reset_bios"):
852 reset_bios(module, redfish_obj)
853 if module.params.get('attributes'):
854 attributes_config(module, redfish_obj)
855
856
857 if __name__ == '__main__':
858 main()