Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 10.1.0
7 # Copyright (C) 2020-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_smart_fabric_uplink
20 short_description: Create, modify or delete a uplink for a fabric on OpenManage Enterprise Modular
21 version_added: "2.1.0"
22 description: This module allows to create, modify or delete an uplink for a fabric.
23 extends_documentation_fragment:
24 - dellemc.openmanage.omem_auth_options
25 options:
26 state:
27 description:
28 - C(present)
29 - Creates a new uplink with the provided I(name).
30 - Modifies an existing uplink with the provided I(name).
31 - C(absent) – Deletes the uplink with the provided I(name).
32 - I(WARNING) Delete operation can impact the network infrastructure.
33 choices: [present, absent]
34 default: present
35 type: str
36 fabric_name:
37 type: str
38 description: Provide the I(fabric_name) of the fabric for which the uplink is to be configured.
39 required: true
40 name:
41 type: str
42 description: Provide the I(name) of the uplink to be created, modified or deleted.
43 required: true
44 new_name:
45 type: str
46 description: Provide the new I(new_name) for the uplink.
47 description:
48 type: str
49 description: Provide a short description for the uplink to be created or modified.
50 uplink_type:
51 description:
52 - Specify the uplink type.
53 - I(NOTE) The uplink type cannot be changed for an existing uplink.
54 choices: ['Ethernet', 'FCoE', 'FC Gateway', 'FC Direct Attach', 'Ethernet - No Spanning Tree']
55 type: str
56 ufd_enable:
57 description:
58 - "Add or Remove the uplink to the Uplink Failure Detection (UFD) group. The UFD group identifies the loss of
59 connectivity to the upstream switch and notifies the servers that are connected to the switch. During an uplink
60 failure, the switch disables the corresponding downstream server ports. The downstream servers can then select
61 alternate connectivity routes, if available."
62 - "I(WARNING) The firmware version of the I/O Module running the Fabric Manager must support this configuration
63 feature. If not, uplink creation will be successful with an appropriate error message in response."
64 choices: ['Enabled', 'Disabled']
65 type: str
66 primary_switch_service_tag:
67 description: Service tag of the primary switch.
68 type: str
69 primary_switch_ports:
70 description:
71 - The IOM slots to be connected to the primary switch.
72 - I(primary_switch_service_tag) is mandatory for this option.
73 type: list
74 elements: str
75 secondary_switch_service_tag:
76 description: Service tag of the secondary switch.
77 type: str
78 secondary_switch_ports:
79 description:
80 - The IOM slots to be connected to the secondary switch.
81 - I(secondary_switch_service_tag) is mandatory for this option.
82 type: list
83 elements: str
84 tagged_networks:
85 description: VLANs to be associated with the uplink I(name).
86 type: list
87 elements: str
88 untagged_network:
89 description: Specify the name of the VLAN to be added as untagged to the uplink.
90 type: str
91 requirements:
92 - "python >= 3.9.6"
93 author:
94 - "Jagadeesh N V(@jagadeeshnv)"
95 notes:
96 - Run this module from a system that has direct access to Dell OpenManage Enterprise Modular.
97 - This module supports C(check_mode).
98 '''
99
100 EXAMPLES = r'''
101 ---
102 - name: Create an Uplink
103 dellemc.openmanage.ome_smart_fabric_uplink:
104 hostname: "192.168.0.1"
105 username: "username"
106 password: "password"
107 ca_path: "/path/to/ca_cert.pem"
108 state: "present"
109 fabric_name: "fabric1"
110 name: "uplink1"
111 description: "CREATED from OMAM"
112 uplink_type: "Ethernet"
113 ufd_enable: "Enabled"
114 primary_switch_service_tag: "ABC1234"
115 primary_switch_ports:
116 - ethernet1/1/13
117 - ethernet1/1/14
118 secondary_switch_service_tag: "XYZ1234"
119 secondary_switch_ports:
120 - ethernet1/1/13
121 - ethernet1/1/14
122 tagged_networks:
123 - vlan1
124 - vlan3
125 untagged_network: vlan2
126 tags: create_uplink
127
128 - name: Modify an existing uplink
129 dellemc.openmanage.ome_smart_fabric_uplink:
130 hostname: "192.168.0.1"
131 username: "username"
132 password: "password"
133 ca_path: "/path/to/ca_cert.pem"
134 state: "present"
135 fabric_name: "fabric1"
136 name: "uplink1"
137 new_name: "uplink2"
138 description: "Modified from OMAM"
139 uplink_type: "Ethernet"
140 ufd_enable: "Disabled"
141 primary_switch_service_tag: "DEF1234"
142 primary_switch_ports:
143 - ethernet1/2/13
144 - ethernet1/2/14
145 secondary_switch_service_tag: "TUV1234"
146 secondary_switch_ports:
147 - ethernet1/2/13
148 - ethernet1/2/14
149 tagged_networks:
150 - vlan11
151 - vlan33
152 untagged_network: vlan22
153 tags: modify_uplink
154
155 - name: Delete an Uplink
156 dellemc.openmanage.ome_smart_fabric_uplink:
157 hostname: "192.168.0.1"
158 username: "username"
159 password: "password"
160 ca_path: "/path/to/ca_cert.pem"
161 state: "absent"
162 fabric_name: "fabric1"
163 name: "uplink1"
164 tags: delete_uplink
165
166 - name: Modify an Uplink name
167 dellemc.openmanage.ome_smart_fabric_uplink:
168 hostname: "192.168.0.1"
169 username: "username"
170 password: "password"
171 ca_path: "/path/to/ca_cert.pem"
172 state: "present"
173 fabric_name: "fabric1"
174 name: "uplink1"
175 new_name: "uplink2"
176 tags: modify_uplink_name
177
178 - name: Modify Uplink ports
179 dellemc.openmanage.ome_smart_fabric_uplink:
180 hostname: "192.168.0.1"
181 username: "username"
182 password: "password"
183 ca_path: "/path/to/ca_cert.pem"
184 state: "present"
185 fabric_name: "fabric1"
186 name: "uplink1"
187 description: "uplink ports modified"
188 primary_switch_service_tag: "ABC1234"
189 primary_switch_ports:
190 - ethernet1/1/6
191 - ethernet1/1/7
192 secondary_switch_service_tag: "XYZ1234"
193 secondary_switch_ports:
194 - ethernet1/1/9
195 - ethernet1/1/10
196 tags: modify_ports
197
198 - name: Modify Uplink networks
199 dellemc.openmanage.ome_smart_fabric_uplink:
200 hostname: "192.168.0.1"
201 username: "username"
202 password: "password"
203 ca_path: "/path/to/ca_cert.pem"
204 state: "present"
205 fabric_name: "fabric1"
206 name: "create1"
207 description: "uplink networks modified"
208 tagged_networks:
209 - vlan4
210 tags: modify_networks
211 '''
212
213 RETURN = r'''
214 ---
215 msg:
216 type: str
217 description: Overall status of the uplink operation.
218 returned: always
219 sample: "Successfully modified the uplink."
220 uplink_id:
221 type: str
222 description: Returns the ID when an uplink is created or modified.
223 returned: when I(state=present)
224 sample: "ddc3d260-fd71-46a1-97f9-708e12345678"
225 additional_info:
226 type: dict
227 description: Additional details of the fabric operation.
228 returned: when I(state=present) and additional information present in response.
229 sample: {
230 "error": {
231 "@Message.ExtendedInfo": [
232 {
233 "Message": "Unable to configure the Uplink Failure Detection mode on the uplink because the firmware
234 version of the I/O Module running the Fabric Manager does not support the configuration feature.",
235 "MessageArgs": [],
236 "MessageId": "CDEV7151",
237 "RelatedProperties": [],
238 "Resolution": "Update the firmware version of the I/O Module running the Fabric Manager and retry
239 the operation. For information about the recommended I/O Module firmware versions, see the
240 OpenManage Enterprise-Modular User's Guide available on the support site.",
241 "Severity": "Informational"
242 }
243 ],
244 "code": "Base.1.0.GeneralError",
245 "message": "A general error has occurred. See ExtendedInfo for more information."
246 }
247 }
248 error_info:
249 description: Details of the HTTP Error.
250 returned: on HTTP error
251 type: dict
252 sample: {
253 "error": {
254 "code": "Base.1.0.GeneralError",
255 "message": "A general error has occurred. See ExtendedInfo for more information.",
256 "@Message.ExtendedInfo": [
257 {
258 "MessageId": "CGEN1006",
259 "RelatedProperties": [],
260 "Message": "Unable to complete the request because the resource URI does not exist or is not implemented.",
261 "MessageArgs": [],
262 "Severity": "Critical",
263 "Resolution": "Check the request resource URI. Refer to the OpenManage Enterprise-Modular User's Guide
264 for more information about resource URI and its properties."
265 }
266 ]
267 }
268 }
269 '''
270
271 import json
272 from ssl import SSLError
273 from ansible.module_utils.urls import ConnectionError, SSLValidationError
274 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
275 from ansible.module_utils.common.dict_transformations import recursive_diff
276 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
277 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import get_item_and_list
278
279 FABRIC_URI = "NetworkService/Fabrics"
280 UPLINKS_URI = "NetworkService/Fabrics('{fabric_id}')/Uplinks"
281 UPLINK_URI = "NetworkService/Fabrics('{fabric_id}')/Uplinks('{uplink_id}')"
282 APPLICABLE_NETWORKS = "NetworkService/Fabrics('{fabric_id}')/NetworkService.GetApplicableUplinkNetworks"
283 APPLICABLE_UNTAGGED = "NetworkService/Fabrics('{fabric_id}')/NetworkService.GetApplicableUplinkUntaggedNetworks"
284 IOM_DEVICES = "DeviceService/Devices?$filter=Type%20eq%204000"
285 PORT_INFO = "DeviceService/Devices({device_id})/InventoryDetails('portInformation')"
286 MEDIA_TYPES = "NetworkService/UplinkTypes"
287 VLAN_CONFIG = "NetworkConfigurationService/Networks"
288 # Messages
289 CHECK_MODE_MSG = "Changes found to be applied."
290 NO_CHANGES_MSG = "No changes found to be applied to the uplink configuration."
291 SAME_SERVICE_TAG_MSG = "Primary and Secondary service tags must not be the same."
292
293
294 def get_item_id(rest_obj, name, uri, key='Name', attr='Id', value='value'):
295 resp = rest_obj.invoke_request('GET', uri)
296 tlist = []
297 if resp.success and resp.json_data.get(value):
298 tlist = resp.json_data.get(value, [])
299 for xtype in tlist:
300 if xtype.get(key, "") == name:
301 return xtype.get(attr), tlist
302 return 0, tlist
303
304
305 def get_all_uplink_ports(uplinks):
306 portlist = []
307 for uplink in uplinks:
308 portlist = portlist + uplink.get("Ports")
309 return portlist
310
311
312 def validate_ioms(module, rest_obj, uplinks):
313 uplinkports = get_all_uplink_ports(uplinks)
314 payload_ports = []
315 occupied_ports = []
316 used_ports = []
317 for idx in uplinkports:
318 used_ports.append(idx["Id"])
319 iomsts = ("primary", "secondary")
320 for iom in iomsts:
321 prim_st = module.params.get(iom + "_switch_service_tag")
322 if prim_st:
323 prim_ports = list(str(port).strip() for port in module.params.get(iom + "_switch_ports"))
324 id, ioms = get_item_id(rest_obj, prim_st, IOM_DEVICES, key="DeviceServiceTag")
325 if not id:
326 module.exit_json(msg="Device with service tag {0} does not exist.".format(prim_st),
327 failed=True)
328 resp = rest_obj.invoke_request("GET", PORT_INFO.format(device_id=id))
329 port_info_data = resp.json_data.get("InventoryInfo", [])
330 port_info_list = []
331 for port in port_info_data:
332 if port.get("SubPorts"):
333 for subport in port.get("SubPorts"):
334 port_info_list.append(subport["PortNumber"])
335 else:
336 port_info_list.append(port["PortNumber"])
337 # All ports are listed but with "OpticsType": "NotPresent" are shown on UI.
338 non_exist_ports = []
339 for port in prim_ports:
340 if port not in port_info_list:
341 non_exist_ports.append(port)
342 st_port = prim_st + ':' + port
343 payload_ports.append(st_port)
344 if st_port in used_ports:
345 occupied_ports.append(st_port)
346 if non_exist_ports:
347 module.exit_json(msg="{0} Port Numbers {1} does not exist for IOM {2}."
348 .format(iom, (",".join(set(non_exist_ports))), prim_st),
349 failed=True)
350 if occupied_ports:
351 module.exit_json(msg="Ports {0} are already occupied.".format(",".join(set(occupied_ports))),
352 failed=True)
353 return payload_ports
354
355
356 def validate_networks(module, rest_obj, fabric_id, media_id):
357 resp = rest_obj.invoke_request('POST', APPLICABLE_NETWORKS.format(fabric_id=fabric_id),
358 data={"UplinkType": media_id})
359 vlans = []
360 if resp.json_data.get('ApplicableUplinkNetworks'):
361 vlans = resp.json_data.get('ApplicableUplinkNetworks', [])
362 vlan_payload = []
363 vlan_dict = {}
364 for vlan in vlans:
365 vlan_dict[vlan["Name"]] = vlan["Id"]
366 networks = list(str(net).strip() for net in module.params.get("tagged_networks"))
367 invalids = []
368 for ntw in networks:
369 if vlan_dict.get(ntw):
370 vlan_payload.append(vlan_dict.get(ntw))
371 else:
372 invalids.append(ntw)
373 if invalids:
374 module.exit_json(msg="Networks with names {0} are not applicable or valid.".format(",".join(set(invalids))),
375 failed=True)
376 return vlan_payload
377
378
379 def validate_native_vlan(module, rest_obj, fabric_id, media_id):
380 resp = rest_obj.invoke_request('POST', APPLICABLE_UNTAGGED.format(fabric_id=fabric_id),
381 data={"UplinkType": media_id})
382 vlans = []
383 if resp.json_data.get('ApplicableUplinkNetworks'):
384 vlans = resp.json_data.get('ApplicableUplinkNetworks', [])
385 vlan_id = 0
386 vlan_name = module.params.get("untagged_network")
387 for vlan in vlans:
388 if vlan["Name"] == vlan_name:
389 vlan_id = vlan["VlanMaximum"] # considering tagged vlans take the 'Id'
390 break
391 if not vlan_id:
392 module.exit_json(msg="Native VLAN name {0} is not applicable or valid.".format(vlan_name),
393 failed=True)
394 return vlan_id
395
396
397 def create_uplink(module, rest_obj, fabric_id, uplinks):
398 mparams = module.params
399 mandatory_parmas = ["name", "uplink_type", "tagged_networks"]
400 for prm in mandatory_parmas:
401 if not mparams.get(prm):
402 module.exit_json(msg="Mandatory parameter {0} not provided for uplink creation.".format(prm),
403 failed=True)
404 media_id, mtypes = get_item_id(rest_obj, mparams["uplink_type"], MEDIA_TYPES)
405 if not media_id:
406 module.exit_json(msg="Uplink Type {0} does not exist.".format(mparams["uplink_type"]),
407 failed=True)
408 if mparams.get("primary_switch_service_tag") or mparams.get("secondary_switch_service_tag"):
409 if mparams.get("primary_switch_service_tag") == mparams.get("secondary_switch_service_tag"):
410 module.exit_json(msg=SAME_SERVICE_TAG_MSG, failed=True)
411 payload_port_list = validate_ioms(module, rest_obj, uplinks)
412 else:
413 module.exit_json(msg="Provide port details.", failed=True)
414 tagged_networks = validate_networks(module, rest_obj, fabric_id, media_id)
415 create_payload = {
416 "Name": mparams["name"],
417 "MediaType": mparams["uplink_type"],
418 "Ports": [{"Id": port} for port in payload_port_list],
419 "Networks": [{"Id": net} for net in tagged_networks]
420 }
421 if mparams.get("untagged_network"):
422 untagged_id = validate_native_vlan(module, rest_obj, fabric_id, media_id)
423 create_payload["NativeVLAN"] = untagged_id
424 if mparams.get("ufd_enable"):
425 create_payload["UfdEnable"] = mparams.get("ufd_enable")
426 if mparams.get("description"):
427 create_payload["Description"] = mparams.get("description")
428 if module.check_mode:
429 module.exit_json(changed=True, msg=CHECK_MODE_MSG)
430 resp = rest_obj.invoke_request("POST", UPLINKS_URI.format(fabric_id=fabric_id), data=create_payload)
431 uplink_id = resp.json_data
432 if isinstance(resp.json_data, dict):
433 uplink_id, tmp = get_item_id(rest_obj, mparams["name"], UPLINKS_URI.format(fabric_id=fabric_id))
434 if not uplink_id:
435 uplink_id = ""
436 module.exit_json(changed=True, msg="Successfully created the uplink.", uplink_id=uplink_id,
437 additional_info=resp.json_data)
438 module.exit_json(changed=True, msg="Successfully created the uplink.", uplink_id=uplink_id)
439
440
441 def delete_uplink(module, rest_obj, fabric_id, uplink_id):
442 if module.check_mode:
443 module.exit_json(changed=True, msg=CHECK_MODE_MSG)
444 rest_obj.invoke_request("DELETE", UPLINK_URI.format(fabric_id=fabric_id, uplink_id=uplink_id))
445 module.exit_json(msg="Successfully deleted the uplink.", changed=True)
446
447
448 def modify_uplink(module, rest_obj, fabric_id, uplink, uplinks):
449 mparams = module.params
450 pload_keys = ["Id", "Name", "Description", "MediaType", "NativeVLAN", "UfdEnable", "Ports", "Networks"]
451 modify_payload = dict((pload_key, uplink.get(pload_key)) for pload_key in pload_keys)
452 port_list = list(port["Id"] for port in modify_payload["Ports"])
453 modify_payload["Ports"] = sorted(list(set(port_list)))
454 network_list = list(network["Id"] for network in modify_payload["Networks"])
455 modify_payload["Networks"] = sorted(network_list)
456 modify_data = {}
457 if mparams.get("new_name"):
458 modify_data["Name"] = mparams.get("new_name")
459 if mparams.get("description"):
460 modify_data["Description"] = mparams.get("description")
461 if mparams.get("ufd_enable"):
462 modify_data["UfdEnable"] = mparams.get("ufd_enable")
463 if mparams.get("uplink_type"):
464 if mparams.get("uplink_type") != uplink.get("MediaType"):
465 module.exit_json(msg="Uplink Type cannot be modified.", failed=True)
466 modify_data["MediaType"] = mparams["uplink_type"]
467 if mparams.get("primary_switch_service_tag") or mparams.get("secondary_switch_service_tag"):
468 if mparams.get("primary_switch_service_tag") == mparams.get("secondary_switch_service_tag"):
469 module.exit_json(msg=SAME_SERVICE_TAG_MSG, failed=True)
470 payload_port_list = validate_ioms(module, rest_obj, uplinks)
471 modify_data["Ports"] = sorted(list(set(payload_port_list)))
472 media_id, mtypes = get_item_id(rest_obj, uplink.get("MediaType"), MEDIA_TYPES)
473 if mparams.get("tagged_networks") and media_id:
474 tagged_networks = validate_networks(module, rest_obj, fabric_id, media_id)
475 modify_data["Networks"] = sorted(tagged_networks)
476 if mparams.get("untagged_network") and media_id:
477 untagged_id = validate_native_vlan(module, rest_obj, fabric_id, media_id)
478 modify_data["NativeVLAN"] = untagged_id
479 diff = recursive_diff(modify_data, modify_payload)
480 if diff and diff[0]:
481 modify_payload.update(diff[0])
482 if module.check_mode:
483 module.exit_json(changed=True, msg=CHECK_MODE_MSG)
484 modify_payload["Ports"] = list({"Id": port} for port in modify_payload["Ports"])
485 modify_payload["Networks"] = list({"Id": net} for net in modify_payload["Networks"])
486 resp = rest_obj.invoke_request("PUT", UPLINK_URI.format(fabric_id=fabric_id, uplink_id=uplink['Id']),
487 data=modify_payload)
488 if isinstance(resp.json_data, dict):
489 module.exit_json(changed=True, msg="Successfully modified the uplink.", uplink_id=uplink['Id'],
490 additional_info=resp.json_data)
491 module.exit_json(changed=True, msg="Successfully modified the uplink.", uplink_id=uplink['Id'])
492 module.exit_json(msg=NO_CHANGES_MSG)
493
494
495 def main():
496 specs = {
497 "state": {"choices": ['present', 'absent'], "default": "present"},
498 "fabric_name": {"required": True, "type": "str"},
499 "name": {"required": True, "type": "str"},
500 "new_name": {"type": "str"},
501 "description": {"type": "str"},
502 "uplink_type": {
503 "choices": ['Ethernet', 'FCoE', 'FC Gateway', 'FC Direct Attach', 'Ethernet - No Spanning Tree']},
504 "ufd_enable": {"choices": ['Enabled', 'Disabled']},
505 "primary_switch_service_tag": {"type": "str"},
506 "primary_switch_ports": {"type": "list", "elements": "str"},
507 "secondary_switch_service_tag": {"type": "str"},
508 "secondary_switch_ports": {"type": "list", "elements": "str"},
509 "tagged_networks": {"type": "list", "elements": "str"},
510 "untagged_network": {"type": "str"}
511 }
512
513 module = OmeAnsibleModule(
514 argument_spec=specs,
515 required_if=[['state', 'present',
516 ('new_name', 'description', 'uplink_type', 'ufd_enable',
517 'primary_switch_service_tag', 'primary_switch_ports', 'secondary_switch_service_tag',
518 'secondary_switch_ports', 'tagged_networks', 'untagged_network',), True]],
519 required_together=[["primary_switch_service_tag", "primary_switch_ports"],
520 ["secondary_switch_service_tag", "secondary_switch_ports"]],
521 supports_check_mode=True
522 )
523 try:
524 with RestOME(module.params, req_session=True) as rest_obj:
525 fabric_id, fabrics = get_item_id(rest_obj, module.params["fabric_name"], FABRIC_URI)
526 if not fabric_id:
527 module.exit_json(msg="Fabric with name {0} does not exist.".format(module.params["fabric_name"]),
528 failed=True)
529 uplink, uplinks = get_item_and_list(rest_obj, module.params["name"],
530 UPLINKS_URI.format(fabric_id=fabric_id) + '?$expand=Ports,Networks')
531 if module.params["state"] == "present":
532 if uplink:
533 uplinks.remove(uplink)
534 modify_uplink(module, rest_obj, fabric_id, uplink, uplinks)
535 create_uplink(module, rest_obj, fabric_id, uplinks)
536 else:
537 if uplink:
538 delete_uplink(module, rest_obj, fabric_id, uplink['Id'])
539 if module.check_mode:
540 module.exit_json(msg=NO_CHANGES_MSG)
541 module.exit_json(msg="Uplink {0} does not exist.".format(module.params["name"]))
542 except HTTPError as err:
543 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
544 except URLError as err:
545 module.exit_json(msg=str(err), unreachable=True, failed=True)
546 except (IOError, ValueError, TypeError, ConnectionError, SSLValidationError, SSLError, OSError) as err:
547 module.exit_json(msg=str(err), failed=True)
548
549
550 if __name__ == "__main__":
551 main()