Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 10.0.1
7 # Copyright (C) 2022-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: ome_server_interface_profiles
20 short_description: Configure server interface profiles
21 version_added: "5.1.0"
22 description: This module allows to configure server interface profiles on OpenManage Enterprise Modular.
23 extends_documentation_fragment:
24 - dellemc.openmanage.omem_auth_options
25 options:
26 device_id:
27 description:
28 - Device id of the Server under chassis fabric.
29 - I(device_id) and I(device_service_tag) is mutually exclusive.
30 type: list
31 elements: int
32 device_service_tag:
33 description:
34 - Service tag of the Server under chassis fabric.
35 - I(device_service_tag) and I(device_id) is mutually exclusive.
36 type: list
37 elements: str
38 nic_teaming:
39 description:
40 - NIC teaming options.
41 - C(NoTeaming) the NICs are not bonded and provide no load balancing or redundancy.
42 - C(LACP) use LACP for NIC teaming.
43 - C(Other) use other technology for NIC teaming.
44 choices: ['LACP', 'NoTeaming', 'Other']
45 type: str
46 nic_configuration:
47 description: NIC configuration for the Servers to be applied.
48 type: list
49 elements: dict
50 suboptions:
51 nic_identifier:
52 description:
53 - ID of the NIC or port number.
54 - C(Note) This will not be validated.
55 type: str
56 required: true
57 team:
58 description:
59 - Group two or more ports. The ports must be connected to the same pair of Ethernet switches.
60 - I(team) is applicable only if I(nic_teaming) is C(LACP).
61 type: bool
62 untagged_network:
63 description:
64 - The maximum or minimum VLAN id of the network to be untagged.
65 - The I(untagged_network) can be retrieved using the M(dellemc.openmanage.ome_network_vlan_info)
66 - If I(untagged_network) needs to be unset this needs to be sent as C(0)
67 - C(Note) The network cannot be added as a untagged network if it is already assigned to a tagged network.
68 type: int
69 tagged_networks:
70 description:
71 - List of tagged networks
72 - Network cannot be added as a tagged network if it is already assigned to untagged network
73 type: dict
74 suboptions:
75 state:
76 description:
77 - Indicates if a list of networks needs to be added or deleted.
78 - C(present) to add the network to the tagged list
79 - C(absent) to delete the Network from the tagged list
80 choices: [present, absent]
81 type: str
82 default: present
83 names:
84 description:
85 - List of network name to be marked as tagged networks
86 - The I(names) can be retrieved using the M(dellemc.openmanage.ome_network_vlan_info)
87 type: list
88 elements: str
89 required: true
90 job_wait:
91 description:
92 - Provides the option to wait for job completion.
93 type: bool
94 default: true
95 job_wait_timeout:
96 description:
97 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
98 - This option is applicable when I(job_wait) is C(true).
99 type: int
100 default: 120
101 requirements:
102 - "python >= 3.9.6"
103 author:
104 - "Jagadeesh N V (@jagadeeshnv)"
105 - Akash Shendge (@shenda1)
106 notes:
107 - This module supports C(check_mode).
108 - Run this module from a system that has direct access to Dell OpenManage Enterprise Modular.
109 '''
110
111 EXAMPLES = r'''
112 ---
113 - name: Modify Server Interface Profile for the server using the service tag
114 dellemc.openmanage.ome_server_interface_profiles:
115 hostname: "192.168.0.1"
116 username: "username"
117 password: "password"
118 ca_path: "/path/to/ca_cert.pem"
119 device_service_tag:
120 - SVCTAG1
121 - SVCTAG2
122 nic_teaming: LACP
123 nic_configuration:
124 - nic_identifier: NIC.Mezzanine.1A-1-1
125 team: false
126 untagged_network: 2
127 tagged_networks:
128 names:
129 - vlan1
130 - nic_identifier: NIC.Mezzanine.1A-2-1
131 team: true
132 untagged_network: 3
133 tagged_networks:
134 names:
135 - range120-125
136
137 - name: Modify Server Interface Profile for the server using the device id
138 dellemc.openmanage.ome_server_interface_profiles:
139 hostname: "192.168.0.1"
140 username: "username"
141 password: "password"
142 ca_path: "/path/to/ca_cert.pem"
143 device_id:
144 - 34523
145 - 48999
146 nic_teaming: NoTeaming
147 nic_configuration:
148 - nic_identifier: NIC.Mezzanine.1A-1-1
149 team: false
150 untagged_network: 2
151 tagged_networks:
152 names:
153 - vlan2
154 - nic_identifier: NIC.Mezzanine.1A-2-1
155 team: true
156 untagged_network: 3
157 tagged_networks:
158 names:
159 - range120-125
160 '''
161
162 RETURN = r'''
163 ---
164 msg:
165 description: Status of the overall server interface operation.
166 returned: always
167 type: str
168 sample: Successfully triggered apply server profiles job.
169 job_id:
170 description: Job ID of the task to apply the server interface profiles.
171 returned: on applying the Interface profiles
172 type: int
173 sample: 14123
174 error_info:
175 description: Details of the HTTP Error.
176 returned: on HTTP error
177 type: dict
178 sample: {
179 "error": {
180 "code": "Base.1.0.GeneralError",
181 "message": "A general error has occurred. See ExtendedInfo for more information.",
182 "@Message.ExtendedInfo": [
183 {
184 "MessageId": "GEN1234",
185 "RelatedProperties": [],
186 "Message": "Unable to process the request because an error occurred.",
187 "MessageArgs": [],
188 "Severity": "Critical",
189 "Resolution": "Retry the operation. If the issue persists, contact your system administrator."
190 }
191 ]
192 }
193 }
194 '''
195
196 import json
197 from ssl import SSLError
198 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
199 from ansible.module_utils.urls import ConnectionError, SSLValidationError
200 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
201 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import \
202 get_rest_items, strip_substr_dict, job_tracking, apply_diff_key
203
204 SERVER_PROFILE = "NetworkService/ServerProfiles('{service_tag}')"
205 SERVER_INTERFACE = "NetworkService/ServerProfiles('{service_tag}')/ServerInterfaceProfiles"
206 VLANS = "NetworkConfigurationService/Networks"
207 DEVICE_URI = "DeviceService/Devices"
208 APPLY_SERVER_PROFILES = "NetworkService/Actions/NetworkService.ApplyServersInterfaceProfiles"
209 JOB_URI = "JobService/Jobs({job_id})"
210 LAST_EXEC = "JobService/Jobs({job_id})/LastExecutionDetail"
211 APPLY_TRIGGERED = "Successfully initiated the apply server profiles job."
212 NO_STAG = "No profile found for service tag {service_tag}."
213 CHANGES_MSG = "Changes found to be applied."
214 NO_CHANGES_MSG = "No changes found to be applied."
215 VLAN_NOT_FOUND = "The VLAN with a name {vlan_name} not found."
216 DUPLICATE_NIC_IDENTIFIED = "Duplicate NIC identfiers provided."
217 INVALID_UNTAGGED = "The untagged VLAN {id} provided for the NIC ID {nic_id} is not valid."
218 NW_OVERLAP = "Network profiles of {service_tag} provided for tagged or untagged VLANs of {nic_id} overlaps."
219 INVALID_DEV_ST = "Unable to complete the operation because the entered target device service tag(s) '{0}' are invalid."
220 INVALID_DEV_ID = "Unable to complete the operation because the entered target device ids '{0}' are invalid."
221
222
223 def get_valid_service_tags(module, rest_obj):
224 service_tags = []
225 nic_configs = module.params.get('nic_configuration')
226 if nic_configs:
227 nic_ids = [(nic.get('nic_identifier')) for nic in nic_configs]
228 if len(nic_ids) > len(set(nic_ids)):
229 module.exit_json(failed=True, msg=DUPLICATE_NIC_IDENTIFIED)
230 dev_map = get_rest_items(rest_obj, uri=DEVICE_URI)
231 if module.params.get('device_service_tag'):
232 cmp_set = set(module.params.get('device_service_tag')) - set(dict(dev_map).values())
233 if cmp_set:
234 module.exit_json(failed=True, msg=INVALID_DEV_ST.format(",".join(cmp_set)))
235 service_tags = list(set(module.params.get('device_service_tag')))
236 if module.params.get('device_id'):
237 cmp_set = set(module.params.get('device_id')) - set(dict(dev_map).keys())
238 if cmp_set:
239 module.exit_json(failed=True, msg=INVALID_DEV_ID.format(",".join(map(str, cmp_set))))
240 service_tags = [(dev_map.get(id)) for id in set(module.params.get('device_id'))]
241 return service_tags
242
243
244 def _get_profile(module, rest_obj, stag):
245 prof = {}
246 try:
247 resp = rest_obj.invoke_request("GET", SERVER_PROFILE.format(service_tag=stag))
248 prof = resp.json_data
249 except HTTPError:
250 module.exit_json(failed=True, msg=NO_STAG.format(service_tag=stag))
251 return prof
252
253
254 def _get_interface(module, rest_obj, stag):
255 intrfc_dict = {}
256 try:
257 intrfc = rest_obj.invoke_request("GET", SERVER_INTERFACE.format(service_tag=stag))
258 intrfc_list = intrfc.json_data.get("value")
259 intrfc_dict = dict((sip['Id'], {"NativeVLAN": sip['NativeVLAN'],
260 "NicBonded": sip["NicBonded"],
261 "Networks": set([(ntw['Id']) for ntw in sip['Networks']])
262 }) for sip in intrfc_list)
263 except HTTPError:
264 module.exit_json(failed=True, msg=NO_STAG.format(service_tag=stag))
265 return intrfc_dict
266
267
268 def get_server_profiles(module, rest_obj, service_tags):
269 profile_dict = {}
270 for stag in service_tags:
271 prof = _get_profile(module, rest_obj, stag)
272 intrfc = _get_interface(module, rest_obj, stag)
273 prof["ServerInterfaceProfiles"] = intrfc
274 prof = strip_substr_dict(prof)
275 profile_dict[stag] = prof
276 return profile_dict
277
278
279 def get_vlan_ids(rest_obj):
280 resp = rest_obj.invoke_request("GET", VLANS)
281 vlans = resp.json_data.get('value')
282 vlan_map = {}
283 natives = {}
284 for vlan in vlans:
285 vlan_map[vlan['Name']] = vlan['Id']
286 if vlan['VlanMaximum'] == vlan['VlanMinimum']:
287 natives[vlan['VlanMaximum']] = vlan['Id']
288 natives.update({0: 0})
289 return vlan_map, natives
290
291
292 def compare_profile(template, profile):
293 diff = 0
294 diff = diff + apply_diff_key(template, profile, ["BondingTechnology"])
295 # bond_tex = profile["BondingTechnology"]
296 # ignore_bond = 0 if profile['BondingTechnology'] == 'LACP' else -1
297 sip = profile.get('ServerInterfaceProfiles')
298 for nic, ntw in sip.items():
299 tmp = template.get(nic, {})
300 diff = diff + apply_diff_key(tmp, ntw, ["NativeVLAN"])
301 diff = diff + apply_diff_key(tmp, ntw, ["NicBonded"])
302 untags = ntw.get("Networks")
303 s = set(untags) | set(tmp.get('present', set()))
304 s = s - set(tmp.get('absent', set()))
305 if s.symmetric_difference(set(untags)):
306 ntw["Networks"] = s
307 diff = diff + 1
308 return diff
309
310
311 def get_template(module, vlan_dict, natives):
312 template = {"ServerInterfaceProfiles": {}}
313 mparams = module.params
314 ignore_teaming = True
315 if mparams.get('nic_teaming'):
316 template['BondingTechnology'] = mparams.get('nic_teaming')
317 if mparams.get('nic_teaming') != "LACP":
318 ignore_teaming = False
319 if mparams.get('nic_configuration'):
320 for nic in mparams.get('nic_configuration'):
321 nic_data = {}
322 if nic.get('team') is not None and ignore_teaming:
323 nic_data['NicBonded'] = nic.get('team') # if ignore_teaming else False
324 ntvlan = nic.get('untagged_network')
325 if ntvlan is not None:
326 if ntvlan not in natives:
327 module.exit_json(failed=True, msg=INVALID_UNTAGGED.format(id=ntvlan, nic_id=nic['nic_identifier']),
328 natives=natives)
329 nic_data['NativeVLAN'] = ntvlan
330 if nic.get('tagged_networks'):
331 tg = nic.get('tagged_networks')
332 nic_data[tg.get('state')] = set()
333 for vlan_name in tg.get('names'):
334 if vlan_name in vlan_dict:
335 nic_data[tg.get('state')].add(vlan_dict[vlan_name])
336 else:
337 module.exit_json(failed=True, msg=VLAN_NOT_FOUND.format(vlan_name=vlan_name))
338 template[nic['nic_identifier']] = nic_data
339 return template
340
341
342 def get_payload(module, rest_obj, profile_dict):
343 vlan_dict, natives = get_vlan_ids(rest_obj)
344 template = get_template(module, vlan_dict, natives)
345 diff = 0
346 payload = []
347 for stag, prof in profile_dict.items():
348 df = compare_profile(template, prof)
349 if df:
350 sip_list = []
351 for k, v in prof["ServerInterfaceProfiles"].items():
352 if natives.get(v['NativeVLAN']) in set(v['Networks']):
353 module.exit_json(failed=True, msg=NW_OVERLAP.format(service_tag=stag, nic_id=k))
354 sips = {"Id": k, "NativeVLAN": v['NativeVLAN'], "NicBonded": v["NicBonded"],
355 "Networks": [({'Id': ntw}) for ntw in v['Networks']]}
356 sip_list.append(sips)
357 prof["ServerInterfaceProfiles"] = sip_list
358 payload.append(prof)
359 diff = diff + df
360 if not diff:
361 module.exit_json(msg=NO_CHANGES_MSG)
362 if module.check_mode:
363 module.exit_json(msg=CHANGES_MSG, changed=True) # , payload=payload)
364 return payload
365
366
367 def handle_job(module, rest_obj, job_id):
368 if module.params.get("job_wait"):
369 job_failed, msg, job_dict, wait_time = job_tracking(
370 rest_obj, JOB_URI.format(job_id=job_id), max_job_wait_sec=module.params.get('job_wait_timeout'))
371 try:
372 job_resp = rest_obj.invoke_request('GET', LAST_EXEC.format(job_id=job_id))
373 msg = job_resp.json_data.get("Value")
374 msg = msg.replace('\n', ' ')
375 except Exception:
376 msg = job_dict.get('JobDescription', msg)
377 module.exit_json(failed=job_failed, msg=msg, job_id=job_id, changed=True)
378 else:
379 module.exit_json(changed=True, msg=APPLY_TRIGGERED, job_id=job_id)
380
381
382 def main():
383 specs = {"device_id": {"type": 'list', "elements": 'int'},
384 "device_service_tag": {"type": 'list', "elements": 'str'},
385 "nic_teaming": {"choices": ['LACP', 'NoTeaming', 'Other']},
386 "nic_configuration": {
387 "type": 'list', "elements": 'dict',
388 "options": {
389 "nic_identifier": {"type": 'str', "required": True},
390 "team": {"type": 'bool'},
391 "untagged_network": {"type": 'int'},
392 "tagged_networks": {
393 "type": 'dict', "options": {
394 "state": {"choices": ['present', 'absent'], "default": 'present'},
395 "names": {"type": 'list', "elements": 'str', 'required': True}
396 },
397 }
398 }},
399 "job_wait": {"type": 'bool', "default": True},
400 "job_wait_timeout": {"type": 'int', "default": 120}}
401
402 module = OmeAnsibleModule(
403 argument_spec=specs,
404 mutually_exclusive=[
405 ('device_id', 'device_service_tag',)],
406 required_one_of=[('device_id', 'device_service_tag',),
407 ('nic_teaming', 'nic_configuration')],
408 supports_check_mode=True)
409 try:
410 with RestOME(module.params, req_session=True) as rest_obj:
411 service_tags = get_valid_service_tags(module, rest_obj)
412 profiles = get_server_profiles(module, rest_obj, service_tags)
413 apply_data = get_payload(module, rest_obj, profiles)
414 resp = rest_obj.invoke_request("POST", APPLY_SERVER_PROFILES, data=apply_data)
415 jobid = resp.json_data.get("JobId")
416 handle_job(module, rest_obj, jobid)
417 except HTTPError as err:
418 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
419 except URLError as err:
420 module.exit_json(msg=str(err), unreachable=True)
421 except (IOError, ValueError, TypeError, SSLError, ConnectionError, SSLValidationError, OSError) as err:
422 module.exit_json(msg=str(err), failed=True)
423
424
425 if __name__ == '__main__':
426 main()