Debian Codegraph @

ansible_collections/cisco/mso/plugins/modules/mso_schema_template_bd.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2018, Dag Wieers (@dagwieers) <[email protected]>
5 # Copyright: (c) 2021, Shreyas Srish (@shrsr) <[email protected]>
6 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12 ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"}
13
14 DOCUMENTATION = r"""
15 ---
16 module: mso_schema_template_bd
17 short_description: Manage Bridge Domains (BDs) in schema templates
18 description:
19 - Manage BDs in schema templates on Cisco ACI Multi-Site.
20 author:
21 - Dag Wieers (@dagwieers)
22 - Shreyas Srish (@shrsr)
23 options:
24 schema:
25 description:
26 - The name of the schema.
27 type: str
28 required: true
29 template:
30 description:
31 - The name of the template.
32 - Display Name of template for operations can only be used in some versions of mso.
33 - Use the name of template instead of Display Name to avoid discrepency.
34 type: str
35 required: true
36 bd:
37 description:
38 - The name of the BD to manage.
39 type: str
40 aliases: [ name ]
41 display_name:
42 description:
43 - The name as displayed on the MSO web interface.
44 type: str
45 description:
46 description:
47 - The description of BD is supported on versions of MSO that are 3.3 or greater.
48 type: str
49 vrf:
50 description:
51 - The VRF associated to this BD. This is required only when creating a new BD.
52 type: dict
53 suboptions:
54 name:
55 description:
56 - The name of the VRF to associate with.
57 required: true
58 type: str
59 schema:
60 description:
61 - The schema that defines the referenced VRF.
62 - If this parameter is unspecified, it defaults to the current schema.
63 type: str
64 template:
65 description:
66 - The template that defines the referenced VRF.
67 - If this parameter is unspecified, it defaults to the current template.
68 type: str
69 dhcp_policy:
70 description:
71 - The DHCP Policy
72 type: dict
73 suboptions:
74 name:
75 description:
76 - The name of the DHCP Relay Policy
77 type: str
78 required: true
79 version:
80 description:
81 - The version of DHCP Relay Policy
82 type: int
83 required: true
84 dhcp_option_policy:
85 description:
86 - The DHCP Option Policy
87 type: dict
88 suboptions:
89 name:
90 description:
91 - The name of the DHCP Option Policy
92 type: str
93 required: true
94 version:
95 description:
96 - The version of the DHCP Option Policy
97 type: int
98 required: true
99 dhcp_policies:
100 description:
101 - A list DHCP Policies to be assciated with the BD
102 - This option can only be used on versions of MSO that are 3.1.1h or greater.
103 type: list
104 elements: dict
105 suboptions:
106 name:
107 description:
108 - The name of the DHCP Relay Policy
109 type: str
110 required: true
111 version:
112 description:
113 - The version of DHCP Relay Policy
114 type: int
115 required: true
116 dhcp_option_policy:
117 description:
118 - The DHCP Option Policy
119 type: dict
120 suboptions:
121 name:
122 description:
123 - The name of the DHCP Option Policy
124 type: str
125 required: true
126 version:
127 description:
128 - The version of the DHCP Option Policy
129 type: int
130 required: true
131 subnets:
132 description:
133 - The subnets associated to this BD.
134 type: list
135 elements: dict
136 suboptions:
137 subnet:
138 description:
139 - The IP range in CIDR notation.
140 type: str
141 required: true
142 aliases: [ ip ]
143 description:
144 description:
145 - The description of this subnet.
146 type: str
147 scope:
148 description:
149 - The scope of the subnet.
150 type: str
151 default: private
152 choices: [ private, public ]
153 shared:
154 description:
155 - Whether this subnet is shared between VRFs.
156 type: bool
157 default: false
158 no_default_gateway:
159 description:
160 - Whether this subnet has a default gateway.
161 type: bool
162 default: false
163 querier:
164 description:
165 - Whether this subnet is an IGMP querier.
166 type: bool
167 default: false
168 virtual:
169 description:
170 - Treat as Virtual IP Address.
171 type: bool
172 default: false
173 primary:
174 description:
175 - Treat as Primary Subnet.
176 - There can be only one primary subnet per address family under a BD.
177 - This option can only be used on versions of MSO that are 3.1.1h or greater.
178 type: bool
179 default: false
180 intersite_bum_traffic:
181 description:
182 - Whether to allow intersite BUM traffic.
183 type: bool
184 optimize_wan_bandwidth:
185 description:
186 - Whether to optimize WAN bandwidth.
187 type: bool
188 layer2_stretch:
189 description:
190 - Whether to enable L2 stretch.
191 type: bool
192 default: true
193 layer2_unknown_unicast:
194 description:
195 - Layer2 unknown unicast.
196 type: str
197 choices: [ flood, proxy ]
198 layer3_multicast:
199 description:
200 - Whether to enable L3 multicast.
201 type: bool
202 unknown_multicast_flooding:
203 description:
204 - Unknown Multicast Flooding can either be Flood or Optimized Flooding.
205 type: str
206 choices: [ flood, optimized_flooding ]
207 multi_destination_flooding:
208 description:
209 - Multi-Destination Flooding can either be Flood in BD, Drop or Flood in Encapsulation.
210 - Flood in Encapsulation is only supported on versions of MSO that are 3.3 or greater.
211 type: str
212 choices: [ flood_in_bd, drop, encap-flood ]
213 ipv6_unknown_multicast_flooding:
214 description:
215 - IPv6 Unknown Multicast Flooding can either be Flood or Optimized Flooding
216 type: str
217 choices: [ flood, optimized_flooding ]
218 arp_flooding:
219 description:
220 - ARP Flooding
221 type: bool
222 virtual_mac_address:
223 description:
224 - Virtual MAC Address
225 type: str
226 unicast_routing:
227 description:
228 - Unicast Routing
229 - This option can only be used on versions of MSO that are 3.1.1h or greater.
230 type: bool
231 multicast_route_map_source_filter:
232 description:
233 - The name of the Route Map Source Filter.
234 - The Route Map Source Filter must reside in the same tenant as the tenant associated to the schema.
235 - This option can only be used when the BD has Layer 3 Multicast enabled.
236 - Providing an empty string O(multicast_route_map_source_filter="") will remove the Route Map Source Filter from the BD.
237 type: str
238 multicast_route_map_destination_filter:
239 description:
240 - The name of the Route Map Destination Filter.
241 - The Route Map Destination Filter must reside in the same tenant as the tenant associated to the schema.
242 - This option can only be used when the BD has Layer 3 Multicast enabled.
243 - Providing an empty string O(multicast_route_map_destination_filter="") will remove the Route Map Destination Filter from the BD.
244 type: str
245 ep_move_detection_mode:
246 description:
247 - Enables detection of endpoint moves using Gratuitous ARP (GARP) packets.
248 type: bool
249 state:
250 description:
251 - Use C(present) or C(absent) for adding or removing.
252 - Use C(query) for listing an object or multiple objects.
253 type: str
254 choices: [ absent, present, query ]
255 default: present
256 extends_documentation_fragment: cisco.mso.modules
257 """
258
259 EXAMPLES = r"""
260 - name: Add a new BD
261 cisco.mso.mso_schema_template_bd:
262 host: mso_host
263 username: admin
264 password: SomeSecretPassword
265 schema: Schema 1
266 template: Template 1
267 bd: BD 1
268 vrf:
269 name: VRF1
270 state: present
271
272 - name: Add a new BD from another Schema
273 mso_schema_template_bd:
274 host: mso_host
275 username: admin
276 password: SomeSecretPassword
277 schema: Schema 1
278 template: Template 1
279 bd: BD 1
280 vrf:
281 name: VRF1
282 schema: Schema Origin
283 template: Template Origin
284 state: present
285
286 - name: Add bd with options available on version 3.1
287 mso_schema_template_bd:
288 host: mso_host
289 username: admin
290 password: SomeSecretPassword
291 schema: Schema 1
292 template: Template 1
293 bd: BD 1
294 intersite_bum_traffic: true
295 optimize_wan_bandwidth: false
296 layer2_stretch: true
297 layer2_unknown_unicast: flood
298 layer3_multicast: false
299 unknown_multicast_flooding: flood
300 multi_destination_flooding: drop
301 ipv6_unknown_multicast_flooding: flood
302 arp_flooding: false
303 virtual_mac_address: 00:00:5E:00:01:3C
304 subnets:
305 - subnet: 10.0.0.128/24
306 - subnet: 10.0.1.254/24
307 description: 1234567890
308 - ip: 192.168.0.254/24
309 description: "My description for a subnet"
310 scope: private
311 shared: false
312 no_default_gateway: true
313 vrf:
314 name: vrf1
315 schema: Test
316 template: Template1
317 dhcp_policy:
318 name: ansible_test
319 version: 1
320 dhcp_option_policy:
321 name: ansible_test_option
322 version: 1
323 state: present
324
325 - name: Add bd with options available on version 3.1.1h or greater
326 mso_schema_template_bd:
327 host: mso_host
328 username: admin
329 password: SomeSecretPassword
330 schema: Schema 1
331 template: Template 1
332 bd: BD 1
333 intersite_bum_traffic: true
334 optimize_wan_bandwidth: false
335 layer2_stretch: true
336 layer2_unknown_unicast: flood
337 layer3_multicast: false
338 unknown_multicast_flooding: flood
339 multi_destination_flooding: drop
340 ipv6_unknown_multicast_flooding: flood
341 arp_flooding: false
342 virtual_mac_address: 00:00:5E:00:01:3C
343 unicast_routing: true
344 subnets:
345 - subnet: 10.0.0.128/24
346 primary: true
347 - subnet: 10.0.1.254/24
348 description: 1234567890
349 virtual: true
350 - ip: 192.168.0.254/24
351 description: "My description for a subnet"
352 scope: private
353 shared: false
354 no_default_gateway: true
355 vrf:
356 name: vrf1
357 schema: Schema1
358 template: Template1
359 dhcp_policies:
360 - name: ansible_test
361 version: 1
362 dhcp_option_policy:
363 name: ansible_test_option
364 version: 1
365 - name: ansible_test2
366 version: 1
367 dhcp_option_policy:
368 name: ansible_test_option2
369 version: 1
370 - name: ansible_test3
371 version: 1
372 dhcp_option_policy:
373 name: ansible_test_option
374 version: 1
375 state: present
376
377 - name: Remove a BD
378 cisco.mso.mso_schema_template_bd:
379 host: mso_host
380 username: admin
381 password: SomeSecretPassword
382 schema: Schema 1
383 template: Template 1
384 bd: BD1
385 state: absent
386
387 - name: Query a specific BD
388 cisco.mso.mso_schema_template_bd:
389 host: mso_host
390 username: admin
391 password: SomeSecretPassword
392 schema: Schema 1
393 template: Template 1
394 bd: BD1
395 state: query
396 register: query_result
397
398 - name: Query all BDs
399 cisco.mso.mso_schema_template_bd:
400 host: mso_host
401 username: admin
402 password: SomeSecretPassword
403 schema: Schema 1
404 template: Template 1
405 state: query
406 register: query_result
407 """
408
409 RETURN = r"""
410 """
411
412
413 import copy
414 from ansible.module_utils.basic import AnsibleModule
415 from ansible_collections.cisco.mso.plugins.module_utils.mso import MSOModule, mso_argument_spec, mso_reference_spec, mso_bd_subnet_spec, mso_dhcp_spec
416 from ansible_collections.cisco.mso.plugins.module_utils.template import MSOTemplate
417 from ansible_collections.cisco.mso.plugins.module_utils.utils import append_update_ops_data
418
419
420 def main():
421 argument_spec = mso_argument_spec()
422 argument_spec.update(
423 schema=dict(type="str", required=True),
424 template=dict(type="str", required=True),
425 bd=dict(type="str", aliases=["name"]), # This parameter is not required for querying all objects
426 display_name=dict(type="str"),
427 description=dict(type="str"),
428 intersite_bum_traffic=dict(type="bool"),
429 optimize_wan_bandwidth=dict(type="bool"),
430 layer2_stretch=dict(type="bool", default="true"),
431 layer2_unknown_unicast=dict(type="str", choices=["flood", "proxy"]),
432 layer3_multicast=dict(type="bool"),
433 vrf=dict(type="dict", options=mso_reference_spec()),
434 dhcp_policy=dict(type="dict", options=mso_dhcp_spec()),
435 dhcp_policies=dict(type="list", elements="dict", options=mso_dhcp_spec()),
436 subnets=dict(type="list", elements="dict", options=mso_bd_subnet_spec()),
437 unknown_multicast_flooding=dict(type="str", choices=["optimized_flooding", "flood"]),
438 multi_destination_flooding=dict(type="str", choices=["flood_in_bd", "drop", "encap-flood"]),
439 ipv6_unknown_multicast_flooding=dict(type="str", choices=["optimized_flooding", "flood"]),
440 arp_flooding=dict(type="bool"),
441 virtual_mac_address=dict(type="str"),
442 unicast_routing=dict(type="bool"),
443 multicast_route_map_source_filter=dict(type="str"),
444 multicast_route_map_destination_filter=dict(type="str"),
445 ep_move_detection_mode=dict(type="bool"),
446 state=dict(type="str", default="present", choices=["absent", "present", "query"]),
447 )
448
449 module = AnsibleModule(
450 argument_spec=argument_spec,
451 supports_check_mode=True,
452 required_if=[
453 ["state", "absent", ["bd"]],
454 ["state", "present", ["bd", "vrf"]],
455 ],
456 )
457
458 schema = module.params.get("schema")
459 template = module.params.get("template").replace(" ", "")
460 bd = module.params.get("bd")
461 display_name = module.params.get("display_name")
462 description = module.params.get("description")
463 intersite_bum_traffic = module.params.get("intersite_bum_traffic")
464 optimize_wan_bandwidth = module.params.get("optimize_wan_bandwidth")
465 layer2_stretch = module.params.get("layer2_stretch")
466 layer2_unknown_unicast = module.params.get("layer2_unknown_unicast")
467 layer3_multicast = module.params.get("layer3_multicast")
468 vrf = module.params.get("vrf")
469 if vrf is not None and vrf.get("template") is not None:
470 vrf["template"] = vrf.get("template").replace(" ", "")
471 dhcp_policy = module.params.get("dhcp_policy")
472 dhcp_policies = module.params.get("dhcp_policies")
473 subnets = module.params.get("subnets")
474 unknown_multicast_flooding = module.params.get("unknown_multicast_flooding")
475 multi_destination_flooding = module.params.get("multi_destination_flooding")
476 ipv6_unknown_multicast_flooding = module.params.get("ipv6_unknown_multicast_flooding")
477 arp_flooding = module.params.get("arp_flooding")
478 virtual_mac_address = module.params.get("virtual_mac_address")
479 unicast_routing = module.params.get("unicast_routing")
480 multicast_route_map_source_filter = module.params.get("multicast_route_map_source_filter")
481 multicast_route_map_destination_filter = module.params.get("multicast_route_map_destination_filter")
482 ep_move_detection_mode = module.params.get("ep_move_detection_mode")
483 state = module.params.get("state")
484
485 mso = MSOModule(module)
486
487 # Map choices
488 if unknown_multicast_flooding == "optimized_flooding":
489 unknown_multicast_flooding = "opt-flood"
490 if ipv6_unknown_multicast_flooding == "optimized_flooding":
491 ipv6_unknown_multicast_flooding = "opt-flood"
492 if multi_destination_flooding == "flood_in_bd":
493 multi_destination_flooding = "bd-flood"
494
495 if layer2_unknown_unicast == "flood":
496 arp_flooding = True
497
498 # Get schema objects
499 schema_id, schema_path, schema_obj = mso.query_schema(schema)
500
501 # Get template
502 templates = [t.get("name") for t in schema_obj.get("templates")]
503 if template not in templates:
504 mso.fail_json(msg="Provided template '{0}' does not exist. Existing templates: {1}".format(template, ", ".join(templates)))
505 template_idx = templates.index(template)
506
507 # Get BDs
508 bds = [b.get("name") for b in schema_obj.get("templates")[template_idx]["bds"]]
509
510 if bd is not None and bd in bds:
511 bd_idx = bds.index(bd)
512 mso.existing = schema_obj.get("templates")[template_idx]["bds"][bd_idx]
513
514 if state == "query":
515 if bd is None:
516 mso.existing = schema_obj.get("templates")[template_idx]["bds"]
517 elif not mso.existing:
518 mso.fail_json(msg="BD '{bd}' not found".format(bd=bd))
519 mso.exit_json()
520
521 if multicast_route_map_source_filter or multicast_route_map_destination_filter:
522 if not layer3_multicast:
523 mso.fail_json(msg="Layer 3 Multicast must be enabled to use Multicast Route Map Filters.")
524 source_id, destination_id = get_route_map_filter_uuids(
525 mso, schema_obj.get("templates")[template_idx].get("tenantId"), multicast_route_map_source_filter, multicast_route_map_destination_filter
526 )
527
528 bds_path = "/templates/{0}/bds".format(template)
529 bd_path = "/templates/{0}/bds/{1}".format(template, bd)
530 ops = []
531
532 mso.previous = copy.deepcopy(mso.existing)
533 if state == "absent":
534 if mso.existing:
535 mso.sent = mso.existing = {}
536 ops.append(dict(op="remove", path=bd_path))
537
538 elif state == "present":
539 vrf_ref = mso.make_reference(vrf, "vrf", schema_id, template)
540 subnets = mso.make_subnets(subnets)
541 dhcp_label = mso.make_dhcp_label(dhcp_policy)
542 dhcp_labels = mso.make_dhcp_label(dhcp_policies)
543
544 if display_name is None and not mso.existing:
545 display_name = bd
546 if subnets is None and not mso.existing:
547 subnets = []
548 mso_remove_values = []
549 payload = dict(
550 name=bd,
551 displayName=display_name,
552 intersiteBumTrafficAllow=intersite_bum_traffic,
553 optimizeWanBandwidth=optimize_wan_bandwidth,
554 l2UnknownUnicast=layer2_unknown_unicast,
555 l2Stretch=layer2_stretch,
556 l3MCast=layer3_multicast,
557 subnets=subnets,
558 vrfRef=vrf_ref,
559 dhcpLabel=dhcp_label,
560 unkMcastAct=unknown_multicast_flooding,
561 multiDstPktAct=multi_destination_flooding,
562 v6unkMcastAct=ipv6_unknown_multicast_flooding,
563 vmac=virtual_mac_address,
564 arpFlood=arp_flooding,
565 )
566
567 if dhcp_labels:
568 payload.update(dhcpLabels=dhcp_labels)
569
570 if unicast_routing is not None:
571 payload.update(unicastRouting=unicast_routing)
572
573 if description:
574 payload.update(description=description)
575
576 if multicast_route_map_source_filter or multicast_route_map_destination_filter:
577 route_map_filter = {}
578
579 # Static setting defined version and mcastRtMapDestVersion to 0 are set in UI but seem not required so excluding them
580 # If in future this is required then uncomment the below line
581 # route_map_filter = {"version": 0, "mcastRtMapDestVersion": 0}
582
583 if source_id:
584 route_map_filter["mcastRtMapSourceRef"] = source_id
585 if destination_id:
586 route_map_filter["mcastRtMapDestRef"] = destination_id
587 payload.update(mcastRtMapFilter=route_map_filter)
588 elif multicast_route_map_source_filter == "" and multicast_route_map_destination_filter == "" and mso.existing.get("mcastRtMapFilter"):
589 mso_remove_values.append("mcastRtMapFilter")
590 mso.existing.pop("mcastRtMapFilter")
591
592 if ep_move_detection_mode:
593 payload.update(epMoveDetectMode="garp")
594 elif ep_move_detection_mode is False:
595 payload.update(epMoveDetectMode="none")
596
597 mso.sanitize(payload, collate=True, required=["dhcpLabel", "dhcpLabels"])
598
599 if mso.existing:
600 # When updating an existing BD, replace operation for each attribute to avoid existing configuration being replaced
601 # This case is specifically important for subnet and dhcp policy which can be configured as a child module
602 append_update_ops_data(ops, copy.deepcopy(mso.existing), bd_path, payload, mso_remove_values)
603 else:
604 ops.append(dict(op="add", path=bds_path + "/-", value=mso.sent))
605
606 mso.existing = mso.proposed
607
608 if "bdRef" in mso.previous:
609 del mso.previous["bdRef"]
610 if "vrfRef" in mso.previous:
611 if isinstance(mso.previous.get("vrfRef"), dict):
612 mso.previous["vrfRef"] = mso.previous.get("vrfRef")
613 else:
614 mso.previous["vrfRef"] = mso.vrf_dict_from_ref(mso.previous.get("vrfRef"))
615
616 if not module.check_mode and mso.proposed != mso.previous:
617 mso.request(schema_path, method="PATCH", data=ops)
618
619 mso.exit_json()
620
621
622 def get_route_map_filter_uuids(mso, tenant_id, multicast_route_map_source_filter, multicast_route_map_destination_filter):
623 source_id, destination_id = None, None
624
625 # Only tenant type templates contain the correct route map policies
626 # Retrieves the list templates that contain the same tenant because only route map policies for the tenant assigned to the schema are options to be chosen
627 templates = [
628 MSOTemplate(mso, template_id=template.get("templateId")) for template in MSOTemplate(mso, "tenant").template if template.get("tenantId") == tenant_id
629 ]
630
631 # NDO restricts route map policies in the same tenant to have the same name thus we can loop through the route map policies to find the correct uuid
632 for template in templates:
633 for route_map_policy in template.template.get("tenantPolicyTemplate", {}).get("template", {}).get("mcastRouteMapPolicies", []):
634 if multicast_route_map_source_filter and route_map_policy.get("name") == multicast_route_map_source_filter:
635 source_id = route_map_policy.get("uuid")
636 if multicast_route_map_destination_filter and route_map_policy.get("name") == multicast_route_map_destination_filter:
637 destination_id = route_map_policy.get("uuid")
638 if (multicast_route_map_source_filter is None or source_id) and (multicast_route_map_destination_filter is None or destination_id):
639 break
640 if (multicast_route_map_source_filter is None or source_id) and (multicast_route_map_destination_filter is None or destination_id):
641 break
642
643 # Error handling for when N amount of route map policies are not found
644 error_message = ""
645 if multicast_route_map_source_filter and not source_id:
646 error_message = "Route Map Source Filter '{0}' not found.".format(multicast_route_map_source_filter)
647 if multicast_route_map_destination_filter and not destination_id:
648 if error_message == "":
649 error_message = "Route Map Destination Filter '{0}' not found.".format(multicast_route_map_destination_filter)
650 else:
651 error_message += "\nRoute Map Destination Filter '{0}' not found.".format(multicast_route_map_destination_filter)
652 if error_message:
653 mso.fail_json(msg=error_message)
654
655 return source_id, destination_id
656
657
658 if __name__ == "__main__":
659 main()