Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_smart_fabric.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) 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
20 short_description: Create, modify or delete a fabric on OpenManage Enterprise Modular
21 version_added: "2.1.0"
22 description:
23 - This module allows to create a fabric, and modify or delete an existing fabric
24 on OpenManage Enterprise Modular.
25 extends_documentation_fragment:
26 - dellemc.openmanage.omem_auth_options
27 options:
28 state:
29 type: str
30 description:
31 - C(present) creates a new fabric or modifies an existing fabric.
32 - C(absent) deletes an existing fabric.
33 - "Notes: The create, modify, or delete fabric operation takes around 15-20 minutes to complete. It is recommended
34 not to start an another operation until the current operation is completed."
35 choices: [present, absent]
36 default: present
37 name:
38 required: true
39 type: str
40 description: Provide the I(name) of the fabric to be created, deleted or modified.
41 new_name:
42 type: str
43 description: Provide the I(name) of the fabric to be modified.
44 description:
45 type: str
46 description: Provide a short description of the fabric to be created or modified.
47 fabric_design:
48 type: str
49 description:
50 - "Specify the fabric topology.See the use API
51 U(https://www.dell.com/support/manuals/en-in/poweredge-mx7000/omem_1_20_10_ug/smartfabric-network-topologies)
52 to know why its topology."
53 - I(fabric_design) is mandatory for fabric creation.
54 choices: [2xMX5108n_Ethernet_Switches_in_same_chassis,
55 2xMX9116n_Fabric_Switching_Engines_in_same_chassis,
56 2xMX9116n_Fabric_Switching_Engines_in_different_chassis]
57 primary_switch_service_tag:
58 type: str
59 description:
60 - Service tag of the first switch.
61 - I(primary_switch_service_tag) is mandatory for fabric creation.
62 - I(primary_switch_service_tag) must belong to the model selected in I(fabric_design).
63 secondary_switch_service_tag:
64 type: str
65 description:
66 - Service tag of the second switch.
67 - I(secondary_switch_service_tag) is mandatory for fabric creation.
68 - I(secondary_switch_service_tag) must belong to the model selected in I(fabric_design).
69 override_LLDP_configuration:
70 type: str
71 description:
72 - Enable this configuration to allow Fabric Management Address to be included in LLDP messages.
73 - "Notes: OpenManage Enterprise Modular 1.0 does not support this option.
74 Some software networking solutions require a single management address to be transmitted by all Ethernet switches
75 to represent the entire fabric. Enable this feature only when connecting to such a solution."
76 choices: ['Enabled', 'Disabled']
77 requirements:
78 - "python >= 3.9.6"
79 author:
80 - "Sajna Shetty(@Sajna-Shetty)"
81 notes:
82 - Run this module from a system that has direct access to Dell OpenManage Enterprise Modular.
83 - This module supports C(check_mode).
84 '''
85
86 EXAMPLES = r'''
87 ---
88 - name: Create a fabric
89 dellemc.openmanage.ome_smart_fabric:
90 hostname: "192.168.0.1"
91 username: "username"
92 password: "password"
93 ca_path: "/path/to/ca_cert.pem"
94 state: present
95 name: "fabric1"
96 description: "fabric desc"
97 fabric_design: "2xMX9116n_Fabric_Switching_Engines_in_different_chassis"
98 primary_switch_service_tag: "SVTG123"
99 secondary_switch_service_tag: "PXYT456"
100 override_LLDP_configuration: "Enabled"
101
102 - name: Modify a fabric
103 dellemc.openmanage.ome_smart_fabric:
104 hostname: "192.168.0.1"
105 username: "username"
106 password: "password"
107 ca_path: "/path/to/ca_cert.pem"
108 state: present
109 name: "fabric1"
110 new_name: "fabric_gold1"
111 description: "new description"
112
113 - name: Delete a fabric
114 dellemc.openmanage.ome_smart_fabric:
115 hostname: "192.168.0.1"
116 username: "username"
117 password: "password"
118 ca_path: "/path/to/ca_cert.pem"
119 state: "absent"
120 name: "fabric1"
121 '''
122
123 RETURN = r'''
124 ---
125 msg:
126 type: str
127 description: Overall status of the fabric operation.
128 returned: always
129 sample: "Fabric creation operation is initiated."
130 fabric_id:
131 type: str
132 description: Returns the ID when an fabric is created, modified or deleted.
133 returned: success
134 sample: "1312cceb-c3dd-4348-95c1-d8541a17d776"
135 additional_info:
136 type: dict
137 description: Additional details of the fabric operation.
138 returned: when I(state=present) and additional information present in response.
139 sample: {
140 "error": {
141 "code": "Base.1.0.GeneralError",
142 "message": "A general error has occurred. See ExtendedInfo for more information.",
143 "@Message.ExtendedInfo": [
144 {
145 "RelatedProperties": [],
146 "Message": "Fabric update is successful. The OverrideLLDPConfiguration attribute is not provided in the
147 payload, so it preserves the previous value.",
148 "MessageArgs": [],
149 "Severity": "Informational",
150 "Resolution": "Please update the Fabric with the OverrideLLDPConfiguration as Disabled or Enabled if
151 necessary."
152 }
153 ]
154 }
155 }
156 error_info:
157 description: Details of the HTTP Error.
158 returned: on HTTP error
159 type: dict
160 sample: {
161 "error": {
162 "code": "Base.1.0.GeneralError",
163 "message": "A general error has occurred. See ExtendedInfo for more information.",
164 "@Message.ExtendedInfo": [
165 {
166 "RelatedProperties": [],
167 "Message": "Unable to perform operation, because the fabric manager was not reachable.",
168 "MessageArgs": [],
169 "Severity": "Warning",
170 "Resolution": "Make sure of the following and retry the operation: 1) There is at least one advanced
171 I/O Module in power-on mode. For example, MX9116n Ethernet Switch and MX5108n Ethernet Switch. However,
172 if an advanced I/O Module is available in the power-on mode, make sure that the network profile is not
173 set when the fabric manager is in the switch-over mode. 2) If the issue persists, wait for few minutes and retry the operation."
174 }
175 ]
176 }
177 }
178 '''
179
180 import json
181 import socket
182 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
183 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
184 from ansible.module_utils.urls import ConnectionError, SSLValidationError
185 from ssl import SSLError
186
187 FABRIC_URI = "NetworkService/Fabrics"
188 FABRIC_ID_URI = "NetworkService/Fabrics('{fabric_id}')"
189 DOMAIN_URI = "ManagementDomainService/Domains"
190 DEVICE_URI = "DeviceService/Devices"
191
192 MSM_URI = "DeviceService/Devices({lead_chassis_device_id})/InventoryDetails('deviceSoftware')"
193
194 CHECK_MODE_CHANGE_FOUND_MSG = "Changes found to be applied."
195 CHECK_MODE_CHANGE_NOT_FOUND_MSG = "No Changes found to be applied."
196 FABRIC_NOT_FOUND_ERROR_MSG = "The smart fabric '{0}' is not present in the system."
197 DOMAIN_SERVICE_TAG_ERROR_MSG = "Unable to retrieve the domain information because the" \
198 " domain of the provided service tag {0} is not available."
199 LEAD_CHASSIS_ERROR_MSG = "System should be a lead chassis if the assigned fabric topology type is {0}."
200 SYSTEM_NOT_SUPPORTED_ERROR_MSG = "Fabric management is not supported on the specified system."
201 DESIGN_MODEL_ERROR_MSG = "The network type of the {0} must be {1}."
202 DEVICE_SERVICE_TAG_TYPE_ERROR_MSG = "The {0} type must be {1}."
203 DEVICE_SERVICE_TAG_NOT_FOUND_ERROR_MSG = "Unable to retrieve the device information because the device" \
204 " with the provided service tag {0} is not available."
205 IDEMPOTENCY_MSG = "Specified fabric details are the same as the existing settings."
206 REQUIRED_FIELD = "Options 'fabric_design', 'primary_switch_service_tag' and 'secondary_switch_service_tag'" \
207 " are required for fabric creation."
208 DUPLICATE_TAGS = "The switch details of the primary switch overlaps with the secondary switch details."
209 PRIMARY_SWITCH_OVERLAP_MSG = "The primary switch service tag is overlapping with existing secondary switch details."
210 SECONDARY_SWITCH_OVERLAP_MSG = "The switch details of the secondary switch overlaps with the existing primary" \
211 " switch details."
212
213
214 def get_service_tag_with_fqdn(rest_obj, module):
215 """
216 get the service tag, if hostname is dnsname
217 """
218 hostname = module.params["hostname"]
219 service_tag = None
220 device_details = rest_obj.get_all_items_with_pagination(DEVICE_URI)
221 for each_device in device_details["value"]:
222 for item in each_device["DeviceManagement"]:
223 if item.get("DnsName") == hostname or item.get('NetworkAddress') == hostname:
224 return each_device["DeviceServiceTag"]
225 return service_tag
226
227
228 def validate_lead_msm_version(each_domain, module, fabric_design=None):
229 """
230 validate lead chassis for design type
231 and find the msm version of the domain
232 """
233 role_type = each_domain["DomainRoleTypeValue"].upper()
234 if fabric_design and fabric_design == "2xMX9116n_Fabric_Switching_Engines_in_different_chassis" and \
235 role_type != "LEAD":
236 module.exit_json(msg=LEAD_CHASSIS_ERROR_MSG.format(fabric_design), failed=True)
237 msm_version = each_domain["Version"]
238 return msm_version
239
240
241 def get_ip_from_host(hostname):
242 """
243 workaround:
244 when Virtual IP DNS name used in hostname, the DNS Name not reflected in device info
245 instead it shows original IP DNSName which causes failure in finding service tag of the device
246 Solution: Convert VIP DNS name to IP
247 """
248 ipaddr = hostname
249 try:
250 result = socket.getaddrinfo(hostname, None)
251 last_element = result[-1]
252 ip_address = last_element[-1][0]
253 if ip_address:
254 ipaddr = ip_address
255 except socket.gaierror:
256 ipaddr = hostname
257 except Exception:
258 ipaddr = hostname
259 return ipaddr
260
261
262 def get_msm_device_details(rest_obj, module):
263 """
264 Get msm details
265 :param rest_obj: session object
266 :param module: Ansible module object
267 :return: tuple
268 1st item: service tag of the domain
269 2nd item: msm version of ome-M device
270 """
271 hostname = get_ip_from_host(module.params["hostname"])
272 fabric_design = module.params.get("fabric_design")
273 msm_version = ""
274 service_tag = get_service_tag_with_fqdn(rest_obj, module)
275 domain_details = rest_obj.get_all_items_with_pagination(DOMAIN_URI)
276 for each_domain in domain_details["value"]:
277 if service_tag and service_tag == each_domain["Identifier"]:
278 msm_version = validate_lead_msm_version(each_domain, module, fabric_design)
279 break
280 if hostname in each_domain["PublicAddress"]:
281 msm_version = validate_lead_msm_version(each_domain, module, fabric_design)
282 service_tag = each_domain["Identifier"]
283 break
284 else:
285 module.exit_json(msg=SYSTEM_NOT_SUPPORTED_ERROR_MSG, failed=True)
286 return service_tag, msm_version
287
288
289 def compare_payloads(modify_payload, current_payload):
290 """
291 :param modify_payload: payload created to update existing setting
292 :param current_payload: already existing payload for specified fabric
293 :return: bool - compare existing and requested setting values of fabric in case of modify operations
294 if both are same return True
295 """
296 diff = False
297 for key, val in modify_payload.items():
298 if current_payload is None or current_payload.get(key) is None:
299 return True
300 elif isinstance(val, dict):
301 if compare_payloads(val, current_payload.get(key)):
302 return True
303 elif val != current_payload.get(key):
304 return True
305 return diff
306
307
308 def idempotency_check_for_state_present(fabric_id, current_payload, expected_payload, module):
309 """
310 idempotency check in case of state present
311 :param fabric_id: fabric id
312 :param current_payload: payload created
313 :param expected_payload: already existing payload for specified fabric
314 :param module: ansible module object
315 :return: None
316 """
317 if fabric_id:
318 exp_dict = expected_payload.copy()
319 cur_dict = current_payload.copy()
320 for d in (exp_dict, cur_dict):
321 fab_dz_lst = d.pop("FabricDesignMapping", [])
322 for fab in fab_dz_lst:
323 d[fab.get('DesignNode')] = fab.get('PhysicalNode')
324 payload_diff = compare_payloads(exp_dict, cur_dict)
325 if module.check_mode:
326 if payload_diff:
327 module.exit_json(msg=CHECK_MODE_CHANGE_FOUND_MSG, changed=True)
328 else:
329 module.exit_json(msg=CHECK_MODE_CHANGE_NOT_FOUND_MSG, changed=False)
330 elif not payload_diff:
331 module.exit_json(msg=IDEMPOTENCY_MSG, changed=False)
332 else:
333 if module.check_mode:
334 module.exit_json(msg=CHECK_MODE_CHANGE_FOUND_MSG, changed=True)
335
336
337 def design_node_dict_update(design_node_map):
338 """
339 make one level dictionary for design map for easy processing
340 :param design_node_map: design node map content
341 :return: dict
342 """
343 d = {}
344 for item in design_node_map:
345 if item["DesignNode"] == "Switch-A" and item.get('PhysicalNode'):
346 d.update({'PhysicalNode1': item['PhysicalNode']})
347 if item["DesignNode"] == "Switch-B" and item.get('PhysicalNode'):
348 d.update({'PhysicalNode2': item['PhysicalNode']})
349 return d
350
351
352 def validate_switches_overlap(current_dict, modify_dict, module):
353 """
354 Validation in case of modify operation when current setting user provided switches details overlaps
355 :param current_dict: modify payload created
356 :param modify_dict: current payload of specified fabric
357 :param module: Ansible module object
358 """
359 modify_primary_switch = modify_dict.get("PhysicalNode1")
360 current_secondary_switch = current_dict.get("PhysicalNode2")
361 modify_secondary_switch = modify_dict.get("PhysicalNode2")
362 current_primary_switch = current_dict.get("PhysicalNode1")
363 if modify_primary_switch and current_primary_switch != modify_primary_switch:
364 module.exit_json(msg="The modify operation does not support primary_switch_service_tag update.",
365 failed=True)
366 if modify_secondary_switch and current_secondary_switch != modify_secondary_switch:
367 module.exit_json(msg="The modify operation does not support secondary_switch_service_tag update.",
368 failed=True)
369 flag = all([modify_primary_switch, modify_secondary_switch, current_primary_switch,
370 current_secondary_switch]) and (modify_primary_switch == current_secondary_switch and
371 modify_secondary_switch == current_primary_switch)
372 if not flag and modify_primary_switch is not None and current_secondary_switch is not None and \
373 modify_primary_switch == current_secondary_switch:
374 module.exit_json(PRIMARY_SWITCH_OVERLAP_MSG, failed=True)
375 if not flag and modify_secondary_switch is not None and current_primary_switch is not None and \
376 modify_secondary_switch == current_primary_switch:
377 module.exit_json(SECONDARY_SWITCH_OVERLAP_MSG, failed=True)
378
379
380 def fabric_design_map_payload_creation(design_map_modify_payload, design_map_current_payload, module):
381 """
382 process FabricDesignMapping contents
383 :param design_map_modify_payload: modify payload created
384 :param design_map_current_payload: current payload of specified fabric
385 :param module: Ansible module object
386 :return: list
387 """
388 modify_dict = design_node_dict_update(design_map_modify_payload)
389 current_dict = design_node_dict_update(design_map_current_payload)
390 validate_switches_overlap(current_dict, modify_dict, module)
391 current_dict.update(modify_dict)
392 design_list = []
393 for key, val in current_dict.items():
394 if key == "PhysicalNode1":
395 design_list.append({'DesignNode': 'Switch-A', 'PhysicalNode': val})
396 else:
397 design_list.append({'DesignNode': 'Switch-B', 'PhysicalNode': val})
398 return design_list
399
400
401 def merge_payload(modify_payload, current_payload, module):
402 """
403 :param modify_payload: payload created to update existing setting
404 :param current_payload: already existing payload for specified fabric
405 :param module: Ansible module object
406 :return: bool - compare existing and requested setting values of fabric in case of modify operations
407 if both are same return True
408 """
409 _current_payload = dict(current_payload)
410 _current_payload.update(modify_payload)
411 if modify_payload.get("FabricDesign") and current_payload.get("FabricDesign"):
412 _current_payload["FabricDesign"].update(modify_payload["FabricDesign"])
413 elif modify_payload.get("FabricDesign") and not current_payload.get("FabricDesign"):
414 _current_payload["FabricDesign"] = modify_payload["FabricDesign"]
415 fabric_design_map_list = fabric_design_map_payload_creation(modify_payload.get("FabricDesignMapping", []),
416 current_payload.get("FabricDesignMapping", []), module)
417 if fabric_design_map_list:
418 _current_payload.update({"FabricDesignMapping": fabric_design_map_list})
419 return _current_payload
420
421
422 def get_fabric_design(fabric_design_uri, rest_obj):
423 """
424 Get the fabric design name from the fabric design uri which is returned from GET request
425 :param fabric_design_uri: fabric design uri
426 :param rest_obj: session object
427 :return: dict
428 """
429 fabric_design = {}
430 if fabric_design_uri:
431 resp = rest_obj.invoke_request("GET", fabric_design_uri.split('/api/')[-1])
432 design_type = resp.json_data.get("Name")
433 fabric_design = {"Name": design_type}
434 return fabric_design
435
436
437 def get_current_payload(fabric_details, rest_obj):
438 """
439 extract payload from existing fabric details, which is
440 obtained from GET request of existing fabric, to match with payload created
441 :param fabric_details: dict - specified fabric details
442 :return: dict
443 """
444 if fabric_details.get("OverrideLLDPConfiguration") and fabric_details.get("OverrideLLDPConfiguration") not in \
445 ["Enabled", "Disabled"]:
446 fabric_details.pop("OverrideLLDPConfiguration", None)
447 payload = {
448 "Id": fabric_details["Id"],
449 "Name": fabric_details["Name"],
450 "Description": fabric_details.get("Description"),
451 "OverrideLLDPConfiguration": fabric_details.get("OverrideLLDPConfiguration"),
452 "FabricDesignMapping": fabric_details.get("FabricDesignMapping", []),
453 "FabricDesign": get_fabric_design(fabric_details["FabricDesign"].get("@odata.id"), rest_obj)
454
455 }
456 return dict([(k, v) for k, v in payload.items() if v])
457
458
459 def create_modify_payload(module_params, fabric_id, msm_version):
460 """
461 payload creation for fabric management in case of create/modify operations
462 :param module_params: ansible module parameters
463 :param fabric_id: fabric id in case of modify operation
464 :param msm_version: msm version details
465 :return: dict
466 """
467 backup_params = dict([(k, v) for k, v in module_params.items() if v])
468 _payload = {
469 "Name": backup_params["name"],
470 "Description": backup_params.get("description"),
471 "OverrideLLDPConfiguration": backup_params.get("override_LLDP_configuration"),
472 "FabricDesignMapping": [],
473 "FabricDesign": {}
474 }
475 if backup_params.get("primary_switch_service_tag"):
476 _payload["FabricDesignMapping"].append({
477 "DesignNode": "Switch-A",
478 "PhysicalNode": backup_params["primary_switch_service_tag"]
479 })
480 if backup_params.get("secondary_switch_service_tag"):
481 _payload["FabricDesignMapping"].append({
482 "DesignNode": "Switch-B",
483 "PhysicalNode": backup_params["secondary_switch_service_tag"]
484 })
485 if backup_params.get("fabric_design"):
486 _payload.update({"FabricDesign": {"Name": backup_params["fabric_design"]}})
487 if msm_version.startswith("1.0"): # OverrideLLDPConfiguration attribute not supported in msm 1.0 version
488 _payload.pop("OverrideLLDPConfiguration", None)
489 if fabric_id: # update id/name in case of modify operation
490 _payload["Name"] = backup_params.get("new_name", backup_params["name"])
491 _payload["Id"] = fabric_id
492 payload = dict([(k, v) for k, v in _payload.items() if v])
493 return payload
494
495
496 def get_fabric_id_details(name, all_fabrics):
497 """
498 obtain the fabric id using fabric name
499 :param name: fabric name
500 :param all_fabrics: All available fabric in the system
501 :return: tuple
502 1st item: fabric id
503 2nd item: all details of fabric specified in dict
504 """
505 fabric_id, fabric_details = None, None
506 for fabric_each in all_fabrics:
507 if fabric_each["Name"] == name:
508 fabric_id = fabric_each["Id"]
509 fabric_details = fabric_each
510 break
511 return fabric_id, fabric_details
512
513
514 def validate_device_type(device_type_name, identifier, device_details, module):
515 """
516 Validation for iom and chassis device type and also design modes of model
517 :param device_type_name: device type name eg: NETWORK_IOM, CHASSIS
518 :param identifier: identifier to access device type name
519 :param device_details: all details of device
520 :param module: ansible module object
521 :return: None
522 """
523 device_map = {
524 "primary_switch_service_tag": "NETWORK_IOM",
525 "secondary_switch_service_tag": "NETWORK_IOM",
526 "hostname": "CHASSIS"
527 }
528 design_mode = module.params.get("fabric_design")
529 if device_type_name != device_map[identifier]:
530 module.exit_json(
531 msg=DEVICE_SERVICE_TAG_TYPE_ERROR_MSG.format(identifier, device_map[identifier]),
532 failed=True)
533 if device_type_name != "CHASSIS" and design_mode:
534 design_model = design_mode.split("_")[0].split('2x')[-1]
535 identifier_model = device_details["Model"]
536 if design_model not in identifier_model:
537 module.exit_json(
538 msg=DESIGN_MODEL_ERROR_MSG.format(identifier, design_model),
539 failed=True)
540
541
542 def validate_service_tag(device_service_tag, identifier, device_type_map, rest_obj, module):
543 """
544 Validate the service tag and device type of device
545 :param identifier: identifier options which required find service tag from module params
546 primary_switch_service_tag, secondary_switch_service_tag, hostname
547 :param device_service_tag: device service tag
548 :param device_type_map: map to get the
549 :param rest_obj: session object
550 :param module: ansible module object
551 :return: None
552 """
553 if device_service_tag is not None:
554 device_id_details = rest_obj.get_device_id_from_service_tag(device_service_tag)
555 device_details = device_id_details["value"]
556 if device_id_details["Id"] is None:
557 module.exit_json(msg=DEVICE_SERVICE_TAG_NOT_FOUND_ERROR_MSG.format(device_service_tag),
558 failed=True)
559 identifier_device_type = device_details["Type"]
560 validate_device_type(device_type_map[identifier_device_type], identifier, device_details, module)
561
562
563 def validate_devices(host_service_tag, rest_obj, module):
564 """
565 validate domain, primary switch and secondary switch devices
566 :param host_service_tag: service tag of the hostname provided
567 :param rest_obj: session object
568 :param module: Ansible module object
569 :return: None
570 """
571 primary = module.params.get("primary_switch_service_tag")
572 secondary = module.params.get("secondary_switch_service_tag")
573 device_type_map = rest_obj.get_device_type()
574 validate_service_tag(host_service_tag, "hostname", device_type_map, rest_obj, module)
575 validate_service_tag(primary,
576 "primary_switch_service_tag",
577 device_type_map, rest_obj, module)
578 validate_service_tag(secondary,
579 "secondary_switch_service_tag",
580 device_type_map, rest_obj,
581 module)
582
583
584 def required_field_check_for_create(fabric_id, module):
585 params = module.params
586 if not fabric_id and not all([params.get("fabric_design"), params.get("primary_switch_service_tag"),
587 params.get("secondary_switch_service_tag")]):
588 module.exit_json(msg=REQUIRED_FIELD, failed=True)
589
590
591 def process_output(name, fabric_resp, msg, fabric_id, rest_obj, module):
592 """
593 fabric management actions creation/update of smart fabric output details processing
594 :param name: fabric name specified
595 :param fabric_resp: json response from ome
596 :param msg: specific message of create and modify operation
597 :param fabric_id: fabric id in case of modify
598 :param rest_obj: current session object
599 :param module: Ansible module object
600 :return: None
601 """
602 identifier = fabric_resp
603 if fabric_id:
604 identifier = fabric_id
605 if isinstance(fabric_resp, dict):
606 all_fabrics = rest_obj.get_all_items_with_pagination(FABRIC_URI)["value"]
607 identifier, current_fabric_details = get_fabric_id_details(name, all_fabrics)
608 if not identifier:
609 identifier = ""
610 module.exit_json(msg=msg, fabric_id=identifier, additional_info=fabric_resp, changed=True)
611 module.exit_json(msg=msg, fabric_id=identifier, changed=True)
612
613
614 def validate_modify(module, current_payload):
615 """Fabric modification does not support fabric design type modification"""
616 if module.params.get("fabric_design") and current_payload["FabricDesign"]["Name"] and \
617 (module.params.get("fabric_design") != current_payload["FabricDesign"]["Name"]):
618 module.exit_json(msg="The modify operation does not support fabric_design update.", failed=True)
619
620
621 def create_modify_fabric(name, all_fabric, rest_obj, module):
622 """
623 fabric management actions creation/update of smart fabric
624 :param all_fabric: all available fabrics in system
625 :param rest_obj: current session object
626 :param module: ansible module object
627 :param name: fabric name specified
628 :return: None
629 """
630 fabric_id, current_fabric_details = get_fabric_id_details(name, all_fabric)
631 required_field_check_for_create(fabric_id, module)
632 host_service_tag, msm_version = get_msm_device_details(rest_obj, module)
633 validate_devices(host_service_tag, rest_obj, module)
634 uri = FABRIC_URI
635 expected_payload = create_modify_payload(module.params, fabric_id, msm_version)
636 payload = dict(expected_payload)
637 method = "POST"
638 msg = "Fabric creation operation is initiated."
639 current_payload = {}
640 if fabric_id:
641 current_payload = get_current_payload(current_fabric_details, rest_obj)
642 validate_modify(module, current_payload)
643 method = "PUT"
644 msg = "Fabric modification operation is initiated."
645 uri = FABRIC_ID_URI.format(fabric_id=fabric_id)
646 payload = merge_payload(expected_payload, current_payload, module)
647 idempotency_check_for_state_present(fabric_id, current_payload, expected_payload, module)
648 resp = rest_obj.invoke_request(method, uri, data=payload)
649 fabric_resp = resp.json_data
650 process_output(name, fabric_resp, msg, fabric_id, rest_obj, module)
651
652
653 def check_fabric_exits_for_state_absent(fabric_values, module, fabric_name):
654 """
655 idempotency check in case of state absent
656 :param fabric_values: fabric details of existing fabric
657 :param module: ansible module object
658 :param fabric_name: fabric name
659 :return: str - fabric id
660 """
661 fabric_id, fabric_details = get_fabric_id_details(fabric_name, fabric_values)
662 if module.check_mode and fabric_id is None:
663 module.exit_json(msg=CHECK_MODE_CHANGE_NOT_FOUND_MSG)
664 if module.check_mode and fabric_id is not None:
665 module.exit_json(msg=CHECK_MODE_CHANGE_FOUND_MSG, changed=True)
666 if not module.check_mode and fabric_id is None:
667 module.exit_json(msg=FABRIC_NOT_FOUND_ERROR_MSG.format(fabric_name))
668 return fabric_id
669
670
671 def delete_fabric(all_fabrics, rest_obj, module, name):
672 """
673 deletes the fabric specified
674 :param all_fabrics: All available fabric in system
675 :param rest_obj: session object
676 :param module: ansible module object
677 :param name: fabric name specified
678 :return: None
679 """
680 fabric_id = check_fabric_exits_for_state_absent(all_fabrics, module, name)
681 rest_obj.invoke_request("DELETE", FABRIC_ID_URI.format(fabric_id=fabric_id))
682 module.exit_json(msg="Fabric deletion operation is initiated.", fabric_id=fabric_id, changed=True)
683
684
685 def fabric_actions(rest_obj, module):
686 """
687 fabric management actions
688 :param rest_obj: session object
689 :param module: ansible module object
690 :return: None
691 """
692 module_params = module.params
693 state = module_params["state"]
694 name = module_params["name"]
695 all_fabrics = rest_obj.get_all_items_with_pagination(FABRIC_URI)["value"]
696 if state == "present":
697 create_modify_fabric(name, all_fabrics, rest_obj, module)
698 else:
699 delete_fabric(all_fabrics, rest_obj, module, name)
700
701
702 def main():
703 design_choices = ['2xMX5108n_Ethernet_Switches_in_same_chassis',
704 '2xMX9116n_Fabric_Switching_Engines_in_same_chassis',
705 '2xMX9116n_Fabric_Switching_Engines_in_different_chassis'
706 ]
707 specs = {
708 "state": {"type": "str", "required": False, "default": "present", "choices": ['present', 'absent']},
709 "name": {"required": True, "type": "str"},
710 "new_name": {"required": False, "type": "str"},
711 "description": {"required": False, "type": "str"},
712 "fabric_design": {"required": False, "type": "str",
713 "choices": design_choices},
714 "primary_switch_service_tag": {"required": False, "type": "str"},
715 "secondary_switch_service_tag": {"required": False, "type": "str"},
716 "override_LLDP_configuration": {"required": False, "type": "str", "choices": ['Enabled', 'Disabled']},
717 }
718
719 module = OmeAnsibleModule(
720 argument_spec=specs,
721 required_if=[['state', 'present', ('new_name', 'description', 'fabric_design', 'primary_switch_service_tag',
722 'secondary_switch_service_tag', 'override_LLDP_configuration',), True]],
723 supports_check_mode=True
724 )
725 try:
726 with RestOME(module.params, req_session=True) as rest_obj:
727 fabric_actions(rest_obj, module)
728 except HTTPError as err:
729 if err.code == 501:
730 module.exit_json(msg=SYSTEM_NOT_SUPPORTED_ERROR_MSG, error_info=json.load(err),
731 failed=True)
732 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
733 except URLError as err:
734 module.exit_json(msg=str(err), unreachable=True)
735 except (IOError, ValueError, TypeError, SSLError, ConnectionError, SSLValidationError, OSError) as err:
736 module.exit_json(msg=str(err), failed=True)
737
738
739 if __name__ == "__main__":
740 main()