Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.3.0
7 # Copyright (C) 2023-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_network_attributes
20 short_description: Configures the iDRAC network attributes
21 version_added: "8.4.0"
22 description:
23 - This module allows you to configure the port and partition network attributes on the network interface cards.
24 extends_documentation_fragment:
25 - dellemc.openmanage.idrac_x_auth_options
26 options:
27 network_adapter_id:
28 type: str
29 required: true
30 description:
31 - FQDD of the network adapter device that represents the physical network adapter capable of connecting to a computer network.
32 - An example of FQDD of the network adapter is 'NIC.Mezzanine.1A'
33 network_device_function_id:
34 type: str
35 required: true
36 description:
37 - FQDD of the network adapter device function that represents a logical interface exposed by the network adapter.
38 - An example of FQDD of the network adapter device function is 'NIC.Mezzanine.1A-1-1'
39 network_attributes:
40 type: dict
41 description:
42 - "Dictionary of network attributes and value. To view the list of attributes and its structure, see the below API
43 U(https://I(idrac_ip)/redfish/v1/Systems/System.Embedded.1/NetworkAdapters/<network_adapter_id>/NetworkDeviceFunctions/
44 <network_device_function_id>/Settings) and U(https://<idrac_ip>/redfish/v1/Schemas/NetworkDeviceFunction.v1_8_0.json)."
45 - I(network_attributes) is mutually exclusive with I(oem_network_attributes).
46 oem_network_attributes:
47 type: dict
48 description:
49 - "The attributes must be part of the Integrated Dell Remote Access Controller Attribute Registry.
50 To view the list of attributes in Attribute Registry for iDRAC9 and newer versions. For more information,
51 see, U(https://I(idrac_ip)/redfish/v1/Chassis/System.Embedded.1/NetworkAdapters/<network_adapter_id>/NetworkDeviceFunctions/
52 <network_device_function_id>/Oem/Dell/DellNetworkAttributes/<network_device_function_id>)
53 and U(https://I(idrac_ip)/redfish/v1/Registries/NetworkAttributesRegistry_<network_device_function_id>/
54 NetworkAttributesRegistry_network_port_id.json)."
55 - For iDRAC8 based servers, derive the network attribute name from Server Configuration Profile.
56 - I(oem_network_attributes) is mutually exclusive with I(network_attributes).
57 resource_id:
58 type: str
59 description:
60 - Id of the resource.
61 - If the value for resource ID is not provided, the module picks the first resource ID available from the list of system resources returned by the iDRAC.
62 clear_pending:
63 type: bool
64 default: false
65 description:
66 - This parameter allows you to clear all the pending OEM network attributes changes.
67 - C(false) does not perform any operation.
68 - C(true) discards any pending changes to network attributes, or if a job is in scheduled state, removes the job.
69 - I(apply_time) value will be ignored and will not have any impact for I(clear_pending) operation.
70 - This operation is not supported for iDRAC8.
71 apply_time:
72 type: str
73 required: true
74 description:
75 - Apply time of the I(network_attributes) and I(oem_network_attributes).
76 - This is applicable only to I(network_attributes) and I(oem_network_attributes).
77 - C(Immediate) allows the user to immediately reboot the host and apply the changes. I(job_wait)
78 is applicable. This is applicable for I(oem_network_attributes) and I(job_wait).
79 - C(OnReset) allows the user to apply the changes on the next reboot of the host server.
80 - C(AtMaintenanceWindowStart) allows the user to apply at the start of a maintenance window as specified
81 in I(maintenance_window). A reboot job is scheduled.
82 - C(InMaintenanceWindowOnReset) allows to apply after a manual reset but within the maintenance window as
83 specified in I(maintenance_window).
84 - This is not applicable for iDRAC8 and value will be ignored and will not have any impact for configuring I(oem_network_attributes).
85 - For iDRAC10, only C(OnReset) is supported.
86 choices: [Immediate, OnReset, AtMaintenanceWindowStart, InMaintenanceWindowOnReset]
87 maintenance_window:
88 type: dict
89 description:
90 - This option allows you to schedule the maintenance window.
91 - This is required when I(apply_time) is C(AtMaintenanceWindowStart) or C(InMaintenanceWindowOnReset).
92 suboptions:
93 start_time:
94 type: str
95 required: true
96 description:
97 - The start time for the maintenance window to be scheduled.
98 - "The format is YYYY-MM-DDThh:mm:ss<offset>"
99 - "<offset> is the time offset from UTC that the current timezone set in
100 iDRAC in the format: +05:30 for IST."
101 duration:
102 type: int
103 required: true
104 description:
105 - The duration in seconds for the maintenance window.
106 job_wait:
107 type: bool
108 default: true
109 description:
110 - Provides the option to wait for job completion.
111 - This is applicable when I(apply_time) is C(Immediate) for I(oem_network_attributes).
112 job_wait_timeout:
113 type: int
114 default: 1200
115 description:
116 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
117 - This option is applicable when I(job_wait) is C(true).
118 requirements:
119 - "python >= 3.9.6"
120 author:
121 - "Abhishek Sinha(@ABHISHEK-SINHA10)"
122 - "Kritika Bhateja (@Kritika-Bhateja-03)"
123 notes:
124 - Run this module from a system that has direct access to Dell iDRAC.
125 - This module supports both IPv4 and IPv6 address.
126 - This module supports C(check_mode).
127 """
128
129 EXAMPLES = """
130 ---
131 - name: Configure OEM network attributes
132 dellemc.openmanage.idrac_network_attributes:
133 idrac_ip: "192.168.0.1"
134 idrac_user: "user_name"
135 idrac_password: "user_password"
136 network_adapter_id: "NIC.Integrated.1"
137 network_device_function_id: "NIC.Integrated.1-1-1"
138 apply_time: "Immediate"
139 oem_network_attributes:
140 BannerMessageTimeout: "4"
141
142 - name: Configure OEM network attributes to apply on reset
143 dellemc.openmanage.idrac_network_attributes:
144 idrac_ip: "192.168.0.1"
145 idrac_user: "user_name"
146 idrac_password: "user_password"
147 network_adapter_id: NIC.Integrated.1
148 network_device_function_id: "NIC.Integrated.1-1-1"
149 oem_network_attributes:
150 BannerMessageTimeout: "4"
151 apply_time: OnReset
152
153 - name: Configure OEM network attributes to apply at maintainance window
154 dellemc.openmanage.idrac_network_attributes:
155 idrac_ip: "192.168.0.1"
156 idrac_user: "user_name"
157 idrac_password: "user_password"
158 network_adapter_id: NIC.Integrated.1
159 network_device_function_id: "NIC.Integrated.1-1-1"
160 oem_network_attributes:
161 BannerMessageTimeout: "4"
162 apply_time: AtMaintenanceWindowStart
163 maintenance_window:
164 start_time: "2022-09-30T05:15:40-05:00"
165 duration: 600
166
167 - name: Clearing the pending attributes
168 dellemc.openmanage.idrac_network_attributes:
169 idrac_ip: "192.168.0.1"
170 idrac_user: "user_name"
171 idrac_password: "user_password"
172 network_adapter_id: NIC.Integrated.1
173 network_device_function_id: "NIC.Integrated.1-1-1"
174 apply_time: "Immediate"
175 clear_pending: true
176
177 - name: Clearing the OEM pending attributes and apply the OEM network attributes
178 dellemc.openmanage.idrac_network_attributes:
179 idrac_ip: "192.168.0.1"
180 idrac_user: "user_name"
181 idrac_password: "user_password"
182 network_adapter_id: NIC.Integrated.1
183 network_device_function_id: "NIC.Integrated.1-1-1"
184 apply_time: "Immediate"
185 clear_pending: true
186 oem_network_attributes:
187 BannerMessageTimeout: "4"
188
189 - name: Configure OEM network attributes and wait for the job
190 dellemc.openmanage.idrac_network_attributes:
191 idrac_ip: "192.168.0.1"
192 idrac_user: "user_name"
193 idrac_password: "user_password"
194 network_adapter_id: NIC.Integrated.1
195 network_device_function_id: "NIC.Integrated.1-1-1"
196 apply_time: "Immediate"
197 oem_network_attributes:
198 LnkSpeed: "10MbpsHalf"
199 WakeOnLan: "Enabled"
200 VLanMode: "Enabled"
201 job_wait: true
202 job_wait_timeout: 2000
203
204 - name: Configure redfish network attributes to update fiber channel on reset
205 dellemc.openmanage.idrac_network_attributes:
206 idrac_ip: "192.168.0.1"
207 idrac_user: "user_name"
208 idrac_password: "user_password"
209 network_adapter_id: NIC.Integrated.1
210 network_device_function_id: "NIC.Integrated.1-1-1"
211 apply_time: OnReset
212 network_attributes:
213 Ethernet:
214 VLAN:
215 VLANEnable: true
216
217 - name: Configure redfish network attributes to apply on reset
218 dellemc.openmanage.idrac_network_attributes:
219 idrac_ip: "192.168.0.1"
220 idrac_user: "user_name"
221 idrac_password: "user_password"
222 network_adapter_id: NIC.Integrated.1
223 network_device_function_id: "NIC.Integrated.1-1-1"
224 network_attributes:
225 Ethernet:
226 VLAN:
227 VLANEnable: true
228 apply_time: OnReset
229
230 - name: Configure redfish network attributes of iscsi to apply at maintainance window start
231 dellemc.openmanage.idrac_network_attributes:
232 idrac_ip: "192.168.0.1"
233 idrac_user: "user_name"
234 idrac_password: "user_password"
235 network_adapter_id: NIC.Integrated.1
236 network_device_function_id: "NIC.Integrated.1-1-1"
237 network_attributes:
238 iSCSIBoot:
239 InitiatorIPAddress: 1.0.0.1
240 apply_time: AtMaintenanceWindowStart
241 maintenance_window:
242 start_time: "2022-09-30T05:15:40-05:00"
243 duration: 600
244
245 - name: Configure redfish network attributes to apply at maintainance window on reset
246 dellemc.openmanage.idrac_network_attributes:
247 idrac_ip: "192.168.0.1"
248 idrac_user: "user_name"
249 idrac_password: "user_password"
250 network_adapter_id: NIC.Integrated.1
251 network_device_function_id: "NIC.Integrated.1-1-1"
252 network_attributes:
253 Ethernet:
254 VLAN:
255 VLANEnable: false
256 VLANId: 1
257 apply_time: AtMaintenanceWindowStart
258 maintenance_window:
259 start_time: "2022-09-30T05:15:40-05:00"
260 duration: 600
261 """
262
263 RETURN = r'''
264 ---
265 msg:
266 description: Status of the attribute update operation.
267 returned: when network attributes is applied
268 type: str
269 sample: "Successfully updated the network attributes."
270 invalid_attributes:
271 description: Dictionary of invalid attributes provided that cannot be applied.
272 returned: On invalid attributes or values
273 type: dict
274 sample: {
275 "IscsiInitiatorIpAddr": "Attribute is not valid.",
276 "IscsiInitiatorSubnet": "Attribute is not valid."
277 }
278 job_status:
279 description: Returns the output for status of the job.
280 returned: always
281 type: dict
282 sample: {
283 "ActualRunningStartTime": null,
284 "ActualRunningStopTime": null,
285 "CompletionTime": null,
286 "Description": "Job Instance",
287 "EndTime": "TIME_NA",
288 "Id": "JID_XXXXXXXXX",
289 "JobState": "Scheduled",
290 "JobType": "NICConfiguration",
291 "Message": "Task successfully scheduled.",
292 "MessageArgs": [],
293 "MessageId": "JCP001",
294 "Name": "Configure: NIC.Integrated.1-1-1",
295 "PercentComplete": 0,
296 "StartTime": "2023-08-07T06:21:24",
297 "TargetSettingsURI": null
298 }
299 error_info:
300 description: Details of the HTTP Error.
301 returned: on HTTP error
302 type: dict
303 sample: {
304 "error": {
305 "code": "Base.1.0.GeneralError",
306 "message": "A general error has occurred. See ExtendedInfo for more information.",
307 "@Message.ExtendedInfo": [
308 {
309 "MessageId": "GEN1234",
310 "RelatedProperties": [],
311 "Message": "Unable to process the request because an error occurred.",
312 "MessageArgs": [],
313 "Severity": "Critical",
314 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
315 }
316 ]
317 }
318 }
319 '''
320
321 import json
322 import time
323 from urllib.error import HTTPError, URLError
324 from ansible.module_utils.compat.version import LooseVersion
325 from ansible.module_utils.urls import ConnectionError, SSLValidationError
326 from ansible_collections.dellemc.openmanage.plugins.module_utils.idrac_redfish import iDRACRedfishAPI, IdracAnsibleModule
327 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import (
328 delete_job, get_current_time, get_dynamic_uri,
329 get_scheduled_job_resp, remove_key, validate_and_get_first_resource_id_uri,
330 idrac_redfish_job_tracking, xml_data_conversion)
331
332
333 REGISTRY_URI = '/redfish/v1/Registries'
334 SYSTEMS_URI = "/redfish/v1/Systems"
335 iDRAC_JOB_URI = "/redfish/v1/Managers/iDRAC.Embedded.1/Jobs/{job_id}"
336 iDRAC_JOB_URI_10 = "/redfish/v1/Managers/iDRAC.Embedded.1/Oem/Dell/Jobs/{job_id}"
337
338 SUCCESS_MSG = "Successfully updated the network attributes."
339 SUCCESS_CLEAR_PENDING_ATTR_MSG = "Successfully cleared the pending network attributes."
340 SCHEDULE_MSG = "Successfully scheduled the job for network attributes update."
341 TIMEOUT_NEGATIVE_OR_ZERO_MSG = "The value for the `job_wait_timeout` parameter cannot be negative or zero."
342 MAINTENACE_OFFSET_DIFF_MSG = "The maintenance time must be post-fixed with local offset to {0}."
343 MAINTENACE_OFFSET_BEHIND_MSG = "The specified maintenance time window occurs in the past, provide a future time to schedule the maintenance window."
344 APPLY_TIME_NOT_SUPPORTED_MSG = "Apply time {0} is not supported."
345 INVALID_ATTR_MSG = "Unable to update the network attributes because invalid values are entered. " + \
346 "Enter the valid values for the network attributes and retry the operation."
347 VALID_AND_INVALID_ATTR_MSG = "Successfully updated the network attributes for valid values. " + \
348 "Unable to update other attributes because invalid values are entered. Enter the valid values and retry the operation."
349 NO_CHANGES_FOUND_MSG = "No changes found to be applied."
350 CHANGES_FOUND_MSG = "Changes found to be applied."
351 INVALID_ID_MSG = "Unable to complete the operation because " + \
352 "the value `{0}` for the input `{1}` parameter is invalid."
353 JOB_RUNNING_CLEAR_PENDING_ATTR = "{0} Config job is running. Wait for the job to complete. Currently can not clear pending attributes."
354 ATTRIBUTE_NOT_EXIST_CHECK_IDEMPOTENCY_MODE = 'Attribute is not valid.'
355 CLEAR_PENDING_NOT_SUPPORTED_WITHOUT_ATTR_IDRAC8 = "Clear pending is not supported."
356 WAIT_TIMEOUT_MSG = "The job is not complete after {0} seconds."
357 HARDWARE_8 = "iDRAC 8"
358 ODATA_ID = "(.*?)@odata"
359
360
361 class IDRACNetworkAttributes:
362
363 def __init__(self, idrac, module):
364 self.module = module
365 self.idrac = idrac
366 self.redfish_uri = None
367 self.oem_uri = None
368
369 def validate_idrac10_and_above(self):
370 gen_details = self.idrac.get_server_generation
371 hw_model = gen_details[2]
372 return hw_model == 'iDRAC 10'
373
374 def get_job_uri(self):
375 idrac10_or_above = self.validate_idrac10_and_above()
376 if idrac10_or_above:
377 return iDRAC_JOB_URI_10
378 return iDRAC_JOB_URI
379
380 def __perform_validation_for_network_adapter_id(self):
381 odata = '@odata.id'
382 network_adapter_id = self.module.params.get('network_adapter_id')
383 network_adapter_id_uri, found_adapter = '', False
384 uri, error_msg = validate_and_get_first_resource_id_uri(
385 self.module, self.idrac, SYSTEMS_URI)
386 if error_msg:
387 self.module.exit_json(msg=error_msg, failed=True)
388 network_adapters = get_dynamic_uri(
389 self.idrac, uri, 'NetworkInterfaces')[odata]
390 network_adapter_list = get_dynamic_uri(
391 self.idrac, network_adapters, 'Members')
392 for each_adapter in network_adapter_list:
393 if network_adapter_id in each_adapter.get(odata):
394 found_adapter = True
395 network_adapter_id_uri = each_adapter.get(odata)
396 break
397 if not found_adapter:
398 self.module.exit_json(failed=True, msg=INVALID_ID_MSG.format(network_adapter_id,
399 'network_adapter_id'))
400 return network_adapter_id_uri
401
402 def __perform_validation_for_network_device_function_id(self):
403 odata = '@odata.id'
404 network_device_function_id_uri, found_device = '', False
405 network_device_function_id = self.module.params.get(
406 'network_device_function_id')
407 network_adapter_id_uri = self.__perform_validation_for_network_adapter_id()
408 network_devices = get_dynamic_uri(
409 self.idrac, network_adapter_id_uri, 'NetworkDeviceFunctions')[odata]
410 network_device_list = get_dynamic_uri(
411 self.idrac, network_devices, 'Members')
412 for each_device in network_device_list:
413 if network_device_function_id in each_device.get(odata):
414 found_device = True
415 network_device_function_id_uri = each_device.get(odata)
416 break
417 if not found_device:
418 self.module.exit_json(failed=True, msg=INVALID_ID_MSG.format(network_device_function_id,
419 'network_device_function_id'))
420 return network_device_function_id_uri
421
422 def __get_registry_fw_less_than_6_more_than_3(self):
423 reg = {}
424 network_device_function_id = self.module.params.get(
425 'network_device_function_id')
426 registry = get_dynamic_uri(self.idrac, REGISTRY_URI, 'Members')
427 for each_member in registry:
428 if network_device_function_id in each_member.get('@odata.id'):
429 location = get_dynamic_uri(
430 self.idrac, each_member.get('@odata.id'), 'Location')
431 if location:
432 uri = location[0].get('Uri')
433 attr = get_dynamic_uri(
434 self.idrac, uri, 'RegistryEntries').get('Attributes', {})
435 for each_attr in attr:
436 reg.update(
437 {each_attr['AttributeName']: each_attr['CurrentValue']})
438 break
439 return reg
440
441 def __validate_time(self, mtime):
442 curr_time, date_offset = get_current_time(self.idrac)
443 if not mtime.endswith(date_offset):
444 self.module.exit_json(
445 failed=True, msg=MAINTENACE_OFFSET_DIFF_MSG.format(date_offset))
446 if mtime < curr_time:
447 self.module.exit_json(
448 failed=True, msg=MAINTENACE_OFFSET_BEHIND_MSG)
449
450 def __get_redfish_apply_time(self, aplytm, rf_settings):
451 rf_set = {}
452 if rf_settings:
453 if aplytm not in rf_settings:
454 self.module.exit_json(
455 failed=True, msg=APPLY_TIME_NOT_SUPPORTED_MSG.format(aplytm))
456 elif 'Maintenance' in aplytm:
457 rf_set['ApplyTime'] = aplytm
458 m_win = self.module.params.get('maintenance_window')
459 self.__validate_time(m_win.get('start_time'))
460 rf_set['MaintenanceWindowStartTime'] = m_win.get('start_time')
461 rf_set['MaintenanceWindowDurationInSeconds'] = m_win.get(
462 'duration')
463 else:
464 rf_set['ApplyTime'] = aplytm
465 return rf_set
466
467 def __get_registry_fw_less_than_3(self):
468 reg = {}
469 network_device_function_id = self.module.params.get(
470 'network_device_function_id')
471 scp_response = self.idrac.export_scp(export_format="JSON", export_use="Default",
472 target="NIC", job_wait=True)
473 comp = scp_response.json_data.get("SystemConfiguration", {}).get("Components", {})
474 for each in comp:
475 if each.get('FQDD') == network_device_function_id:
476 for each_attr in each.get('Attributes'):
477 reg.update({each_attr['Name']: each_attr['Value']})
478 return reg
479
480 def get_current_server_registry(self):
481 reg = {}
482 oem_network_attributes = self.module.params.get(
483 'oem_network_attributes')
484 network_attributes = self.module.params.get('network_attributes')
485 gen_details = self.idrac.get_server_generation
486 firm_ver, hw_model = gen_details[1], gen_details[2]
487 idrac_9_flag = LooseVersion(firm_ver) >= '6.0' and hw_model == "iDRAC 9"
488 if oem_network_attributes:
489 if idrac_9_flag or hw_model == "iDRAC 10":
490 reg = get_dynamic_uri(self.idrac, self.oem_uri, 'Attributes')
491 elif '3.0' < LooseVersion(firm_ver) < '6.0' and hw_model == "iDRAC 9":
492 reg = self.__get_registry_fw_less_than_6_more_than_3()
493 else:
494 reg = self.__get_registry_fw_less_than_3()
495 if network_attributes: # For Redfish
496 resp = get_dynamic_uri(self.idrac, self.redfish_uri)
497 reg.update({'Ethernet': resp.get('Ethernet', {})})
498 reg.update({'FibreChannel': resp.get('FibreChannel', {})})
499 reg.update({'iSCSIBoot': resp.get('iSCSIBoot', {})})
500 return reg
501
502 def extract_error_msg(self, resp):
503 error_info = {}
504 if resp.body:
505 error = resp.json_data.get('error', {})
506 for each_dict_err in error.get("@Message.ExtendedInfo", []):
507 key = each_dict_err.get('MessageArgs')[0]
508 msg = each_dict_err.get('Message')
509 if key not in error_info:
510 error_info.update({key: msg})
511 return error_info
512
513 def get_diff_between_current_and_module_input(self, module_attr, server_attr):
514 diff, invalid = 0, {}
515 if module_attr is None:
516 module_attr = {}
517 for each_attr in module_attr:
518 if each_attr in server_attr:
519 data_type = type(server_attr[each_attr])
520 if not isinstance(module_attr[each_attr], data_type):
521 diff += 1
522 elif isinstance(module_attr[each_attr], dict) and isinstance(server_attr[each_attr], dict):
523 tmp_diff, tmp_invalid = self.get_diff_between_current_and_module_input(
524 module_attr[each_attr], server_attr[each_attr])
525 diff += tmp_diff
526 invalid.update(tmp_invalid)
527 elif module_attr[each_attr] != server_attr[each_attr]:
528 diff += 1
529 elif each_attr not in server_attr:
530 invalid.update(
531 {each_attr: ATTRIBUTE_NOT_EXIST_CHECK_IDEMPOTENCY_MODE})
532 return diff, invalid
533
534 def validate_job_timeout(self):
535 if self.module.params.get("job_wait") and self.module.params.get("job_wait_timeout") <= 0:
536 self.module.exit_json(
537 msg=TIMEOUT_NEGATIVE_OR_ZERO_MSG, failed=True)
538
539 def apply_time(self, setting_uri):
540 resp = get_dynamic_uri(self.idrac, setting_uri, "@Redfish.Settings")
541 rf_settings = resp.get("SupportedApplyTimes", [])
542 apply_time = self.module.params.get('apply_time', {})
543 rf_set = self.__get_redfish_apply_time(apply_time, rf_settings)
544 return rf_set
545
546 def set_dynamic_base_uri_and_validate_ids(self):
547 network_device_function_id_uri = self.__perform_validation_for_network_device_function_id()
548 resp = get_dynamic_uri(self.idrac, network_device_function_id_uri)
549 self.oem_uri = resp.get('Links', {}).get('Oem', {}).get(
550 'Dell', {}).get('DellNetworkAttributes', {}).get('@odata.id', {})
551 self.redfish_uri = network_device_function_id_uri
552
553
554 class OEMNetworkAttributes(IDRACNetworkAttributes):
555 def __init__(self, idrac, module):
556 super().__init__(idrac, module)
557
558 def check_idrac8(self, firm_ver, hw_model, oem_network_attributes):
559 if LooseVersion(firm_ver) < '3.0' and hw_model == HARDWARE_8:
560 if oem_network_attributes:
561 return None
562 self.module.exit_json(
563 msg=CLEAR_PENDING_NOT_SUPPORTED_WITHOUT_ATTR_IDRAC8)
564
565 def clear_pending_job_track(self, job_state, job_id, oem_network_attributes, job_resp):
566 if job_id:
567 if job_state in ["Running"]:
568 job_resp = remove_key(job_resp, regex_pattern=ODATA_ID)
569 self.module.exit_json(
570 failed=True,
571 msg=JOB_RUNNING_CLEAR_PENDING_ATTR.format('NICConfiguration'),
572 job_status=job_resp
573 )
574 elif job_state in ["Starting", "Scheduled", "Scheduling"]:
575 if self.module.check_mode and not oem_network_attributes:
576 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
577 if not self.module.check_mode:
578 delete_job(self.idrac, job_id)
579
580 def clear_pending(self):
581 gen_details = self.idrac.get_server_generation
582 firm_ver, hw_model = gen_details[1], gen_details[2]
583 oem_network_attributes = self.module.params.get(
584 'oem_network_attributes')
585 self.check_idrac8(firm_ver, hw_model, oem_network_attributes)
586 resp = get_dynamic_uri(self.idrac, self.oem_uri, '@Redfish.Settings')
587 settings_uri = resp.get('SettingsObject').get('@odata.id')
588 settings_uri_resp = get_dynamic_uri(self.idrac, settings_uri)
589 pending_attributes = settings_uri_resp.get('Attributes')
590 clear_pending_uri = settings_uri_resp.get('Actions').get(
591 '#DellManager.ClearPending').get('target')
592 if not pending_attributes and not oem_network_attributes:
593 self.module.exit_json(msg=NO_CHANGES_FOUND_MSG)
594 job_resp = get_scheduled_job_resp(self.idrac, 'NICConfiguration')
595 job_id, job_state = job_resp.get('Id'), job_resp.get('JobState')
596 self.clear_pending_job_track(job_state, job_id, oem_network_attributes, job_resp)
597 if self.module.check_mode and not oem_network_attributes:
598 self.module.exit_json(msg=CHANGES_FOUND_MSG, changed=True)
599 time.sleep(5)
600 settings_uri_resp = get_dynamic_uri(self.idrac, settings_uri)
601 pending_attributes = settings_uri_resp.get('Attributes')
602 if pending_attributes and not self.module.check_mode:
603 self.idrac.invoke_request(
604 clear_pending_uri, "POST", data="{}", dump=False)
605 if not oem_network_attributes:
606 self.module.exit_json(
607 msg=SUCCESS_CLEAR_PENDING_ATTR_MSG, changed=True)
608
609 def perform_operation(self):
610 oem_network_attributes = self.module.params.get(
611 'oem_network_attributes')
612 network_device_function_id = self.module.params.get(
613 'network_device_function_id')
614 apply_time = self.module.params.get('apply_time')
615 job_wait = self.module.params.get('job_wait')
616 invalid_attr = {}
617 gen_details = self.idrac.get_server_generation
618 firm_ver, hw_model = gen_details[1], gen_details[2]
619 if LooseVersion(firm_ver) < '3.0' and hw_model == HARDWARE_8:
620 root = """<SystemConfiguration>{0}</SystemConfiguration>"""
621 scp_payload = root.format(xml_data_conversion(
622 oem_network_attributes, network_device_function_id))
623 resp = self.idrac.import_scp(
624 import_buffer=scp_payload, target="NIC", job_wait=False)
625 else:
626 payload = {'Attributes': oem_network_attributes}
627 apply_time_setting = self.apply_time(self.oem_uri)
628 if apply_time_setting:
629 payload.update(
630 {"@Redfish.SettingsApplyTime": apply_time_setting})
631 patch_uri = get_dynamic_uri(self.idrac, self.oem_uri).get(
632 '@Redfish.Settings').get('SettingsObject').get('@odata.id')
633 resp = self.idrac.invoke_request(
634 method='PATCH', uri=patch_uri, data=payload)
635 job_wait = job_wait if apply_time == "Immediate" else False
636 invalid_attr = self.extract_error_msg(resp)
637 return resp, invalid_attr, job_wait
638
639
640 class NetworkAttributes(IDRACNetworkAttributes):
641 def __init__(self, idrac, module):
642 super().__init__(idrac, module)
643
644 def perform_operation(self):
645 updatable_fields = ['Ethernet', 'iSCSIBoot', 'FibreChannel']
646 network_attributes = self.module.params.get('network_attributes')
647 apply_time = self.module.params.get('apply_time')
648 job_wait = self.module.params.get('job_wait')
649 payload, invalid_attr = {}, {}
650 for each_attr in network_attributes:
651 if each_attr in updatable_fields:
652 payload.update({each_attr: network_attributes[each_attr]})
653 apply_time_setting = self.apply_time(self.redfish_uri)
654 if apply_time_setting:
655 payload.update({"@Redfish.SettingsApplyTime": apply_time_setting})
656 resp = get_dynamic_uri(self.idrac, self.redfish_uri)
657 patch_uri = resp.get(
658 "@Redfish.Settings", {}).get("SettingsObject", {}).get("@odata.id", {})
659 resp = self.idrac.invoke_request(
660 method='PATCH', uri=patch_uri, data=payload)
661 invalid_attr = self.extract_error_msg(resp)
662 job_wait = job_wait if apply_time == "Immediate" else False
663 return resp, invalid_attr, job_wait
664
665
666 def check_status_on_idrac8(idrac, module, obj, job_dict, msg):
667 gen_details = idrac.get_server_generation
668 firm_ver, hw_model = gen_details[1], gen_details[2]
669 if LooseVersion(firm_ver) < '3.0' and isinstance(obj, OEMNetworkAttributes) and hw_model == HARDWARE_8:
670 message_id = job_dict.get("MessageId")
671 if message_id == "SYS053":
672 module.exit_json(msg=msg, changed=True, job_status=job_dict)
673 elif message_id == "SYS055":
674 module.exit_json(
675 msg=VALID_AND_INVALID_ATTR_MSG, changed=True, job_status=job_dict)
676 elif message_id == "SYS067":
677 module.fail_json(msg=INVALID_ATTR_MSG,
678 job_status=job_dict)
679 else:
680 module.fail_json(msg=job_dict.get("Message"))
681
682
683 def job_tracking_in_diff(idrac, module, obj, job_resp, invalid_attr, job_wait, job_wait_timeout):
684 job_dict = {}
685 if (job_tracking_uri := job_resp.headers.get("Location")):
686 job_id = job_tracking_uri.split("/")[-1]
687 job_uri = obj.get_job_uri().format(job_id=job_id)
688 if job_wait:
689 job_failed, msg, job_dict, wait_time = idrac_redfish_job_tracking(
690 idrac,
691 job_uri,
692 max_job_wait_sec=job_wait_timeout,
693 sleep_interval_secs=1
694 )
695 job_dict = remove_key(job_dict,
696 regex_pattern=ODATA_ID)
697 if int(wait_time) >= int(job_wait_timeout):
698 module.exit_json(msg=WAIT_TIMEOUT_MSG.format(
699 job_wait_timeout), changed=True, job_status=job_dict)
700 if job_failed:
701 module.fail_json(
702 msg=job_dict.get("Message"), invalid_attributes=invalid_attr, job_status=job_dict)
703 else:
704 job_resp = idrac.invoke_request(job_uri, 'GET')
705 job_dict = job_resp.json_data
706 job_dict = remove_key(job_dict,
707 regex_pattern=ODATA_ID)
708 if job_dict.get('JobState') == "Completed":
709 msg = SUCCESS_MSG if not invalid_attr else VALID_AND_INVALID_ATTR_MSG
710 check_status_on_idrac8(idrac, module, obj, job_dict, msg)
711 else:
712 msg = SCHEDULE_MSG
713 module.exit_json(msg=msg,
714 invalid_attributes=invalid_attr,
715 job_status=job_dict,
716 changed=True)
717
718
719 def perform_operation_for_main(idrac, module, obj, diff, _invalid_attr):
720 job_wait_timeout = module.params.get('job_wait_timeout')
721 if diff:
722 if module.check_mode:
723 module.exit_json(msg=CHANGES_FOUND_MSG, changed=True,
724 invalid_attributes=_invalid_attr)
725 else:
726 job_resp, invalid_attr, job_wait = obj.perform_operation()
727 job_tracking_in_diff(idrac,
728 module,
729 obj,
730 job_resp, invalid_attr, job_wait,
731 job_wait_timeout)
732 else:
733 if module.check_mode:
734 module.exit_json(msg=NO_CHANGES_FOUND_MSG,
735 invalid_attributes=_invalid_attr)
736 # When user has given only invalid attribute, diff will 0 and _invalid_attr will have dictionary,
737 elif _invalid_attr: # Expecting HTTP Error from server.
738 job_resp, invalid_attr, job_wait = obj.perform_operation()
739 module.exit_json(msg=NO_CHANGES_FOUND_MSG,
740 invalid_attributes=_invalid_attr)
741
742
743 def main():
744 try:
745 specs = {
746 "network_adapter_id": {"type": 'str', "required": True},
747 "network_device_function_id": {"type": 'str', "required": True},
748 "network_attributes": {"type": 'dict'},
749 "oem_network_attributes": {"type": 'dict'},
750 "resource_id": {"type": 'str'},
751 "clear_pending": {"type": 'bool', "default": False},
752 "apply_time": {"type": 'str', "required": True,
753 "choices": ['Immediate', 'OnReset', 'AtMaintenanceWindowStart', 'InMaintenanceWindowOnReset']},
754 "maintenance_window": {"type": 'dict',
755 "options": {"start_time": {"type": 'str', "required": True},
756 "duration": {"type": 'int', "required": True}}},
757 "job_wait": {"type": "bool", "default": True},
758 "job_wait_timeout": {"type": "int", "default": 1200}
759 }
760
761 module = IdracAnsibleModule(argument_spec=specs,
762 mutually_exclusive=[('network_attributes', 'oem_network_attributes')],
763 required_if=[["apply_time", "AtMaintenanceWindowStart", ("maintenance_window",)],
764 ["apply_time", "InMaintenanceWindowOnReset", ("maintenance_window",)]],
765 supports_check_mode=True)
766 with iDRACRedfishAPI(module.params, req_session=True) as idrac:
767 if module_attribute := module.params.get('network_attributes'):
768 network_attr_obj = NetworkAttributes(idrac, module)
769 else:
770 module_attribute = module.params.get('oem_network_attributes')
771 network_attr_obj = OEMNetworkAttributes(idrac, module)
772 network_attr_obj.set_dynamic_base_uri_and_validate_ids()
773 network_attr_obj.validate_job_timeout()
774 if module.params.get('clear_pending') and 'clear_pending' in dir(network_attr_obj):
775 network_attr_obj.clear_pending()
776 server_reg = network_attr_obj.get_current_server_registry()
777 diff, invalid_attr = network_attr_obj.get_diff_between_current_and_module_input(
778 module_attribute, server_reg)
779 perform_operation_for_main(idrac,
780 module, network_attr_obj, diff, invalid_attr)
781 except HTTPError as err:
782 filter_err = remove_key(json.load(err), regex_pattern=ODATA_ID)
783 module.exit_json(msg=str(err), error_info=filter_err, failed=True)
784 except URLError as err:
785 module.exit_json(msg=str(err), unreachable=True)
786 except (SSLValidationError, ConnectionError, TypeError, ValueError, OSError) as err:
787 module.exit_json(msg=str(err), failed=True)
788
789
790 if __name__ == '__main__':
791 main()