Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2025, Shreyas Srish (@shrsr) <[email protected]>
5
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: ndo_l3out_interface_group_policy
17 short_description: Manage L3Out Interface Group Policy on Cisco Nexus Dashboard Orchestrator (NDO).
18 description:
19 - Manage L3Out Interface Group Policy on Cisco Nexus Dashboard Orchestrator (NDO).
20 - This module is only supported on ND v3.1 (NDO v4.3) and later.
21 author:
22 - Shreyas Srish (@shrsr)
23 options:
24 template:
25 description:
26 - The name of the template.
27 - The template must be an L3Out template.
28 - This parameter or O(template_id) is required.
29 type: str
30 aliases: [ l3out_template ]
31 template_id:
32 description:
33 - The ID of the L3Out template.
34 - This parameter or O(template) is required.
35 type: str
36 aliases: [ l3out_template_id ]
37 l3out:
38 description:
39 - The name of the L3Out.
40 - This parameter or O(l3out_uuid) is required.
41 type: str
42 aliases: [ l3out_name ]
43 l3out_uuid:
44 description:
45 - The UUID of the L3Out.
46 - This parameter or O(l3out) is required.
47 type: str
48 description:
49 description:
50 - The description of the L3Out Interface Group Policy.
51 type: str
52 name:
53 description:
54 - The name of the L3Out Interface Group Policy.
55 type: str
56 aliases: [ l3out_interface_group_policy ]
57 interface_routing_policy:
58 description:
59 - The configuration of the Interface Routing Policy.
60 - Providing an empty dictionary will remove the O(interface_routing_policy={}) from L3Out Interface Group Policy.
61 type: dict
62 suboptions:
63 name:
64 description:
65 - The name of the L3Out Interface Routing Policy.
66 type: str
67 template:
68 description:
69 - The template associated with the L3Out Interface Routing Policy.
70 - This parameter or O(interface_routing_policy.template_id) is required.
71 type: str
72 template_id:
73 description:
74 - The template ID associated with the L3Out Interface Routing Policy.
75 - This parameter or O(interface_routing_policy.template) is required.
76 type: str
77 interface_routing_policy_uuid:
78 description:
79 - The UUID of the L3Out Interface Routing Policy.
80 - Providing an empty string will remove the O(interface_routing_policy_uuid="") from L3Out Interface Group Policy.
81 type: str
82 bfd:
83 description:
84 - The Bidirectional Forwarding Detection (BFD) configuration.
85 - Providing an empty dictionary will remove the O(bfd={}) from the L3Out Interface Group Policy.
86 type: dict
87 suboptions:
88 enable:
89 description:
90 - Whether BFD is enabled.
91 type: bool
92 authentication:
93 description:
94 - Whether BFD authentication is enabled.
95 type: bool
96 key_id:
97 description:
98 - The BFD key ID.
99 type: int
100 key:
101 description:
102 - The BFD key.
103 type: str
104 bfd_multi_hop:
105 description:
106 - The Bidirectional Forwarding Detection (BFD) multi-hop configuration.
107 - Providing an empty dictionary will remove the O(bfd_multi_hop={}) from the L3Out Interface Group Policy.
108 type: dict
109 suboptions:
110 enable:
111 description:
112 - Whether BFD multi-hop is enabled.
113 type: bool
114 authentication:
115 description:
116 - Whether BFD multi-hop authentication is enabled.
117 type: bool
118 key_id:
119 description:
120 - The BFD multi-hop key ID.
121 type: int
122 key:
123 description:
124 - The BFD multi-hop key.
125 type: str
126 ospf:
127 description:
128 - The Open Shortest Path First (OSPF) configuration.
129 - Providing an empty dictionary will remove the O(ospf={}) from the L3Out Interface Group Policy.
130 type: dict
131 suboptions:
132 enable:
133 description:
134 - Whether OSPF is enabled.
135 type: bool
136 authentication_type:
137 description:
138 - The type of OSPF authentication.
139 type: str
140 choices: [ simple, md5, none ]
141 key_id:
142 description:
143 - The OSPF key ID.
144 type: int
145 key:
146 description:
147 - The OSPF key.
148 type: str
149 qos_priority:
150 description:
151 - The QoS priority level.
152 type: str
153 choices: [ level1, level2, level3, level4, level5, level6, unspecified ]
154 custom_qos_policy:
155 description:
156 - The Custom QoS Policy configuration.
157 - Providing an empty dictionary will remove the O(custom_qos_policy={}) from L3Out Interface Group Policy.
158 type: dict
159 suboptions:
160 name:
161 description:
162 - The name of the Custom QoS Policy.
163 type: str
164 template:
165 description:
166 - The template associated with the Custom QoS Policy.
167 - This parameter or O(custom_qos_policy.template_id) is required.
168 type: str
169 template_id:
170 description:
171 - The template ID associated with the the Custom QoS Policy.
172 - This parameter or O(custom_qos_policy.template) is required.
173 type: str
174 custom_qos_policy_uuid:
175 description:
176 - The UUID of the Custom QoS Policy.
177 - Providing an empty string will remove the O(custom_qos_policy_uuid="") from L3Out Interface Group Policy.
178 type: str
179 state:
180 description:
181 - Determines the desired state of the resource.
182 - Use C(absent) to remove the resource.
183 - Use C(query) to list the resource.
184 - Use C(present) to create or update the resource.
185 type: str
186 choices: [ absent, query, present ]
187 default: query
188 notes:
189 - The O(template) must exist before using this module in your playbook.
190 The M(cisco.mso.ndo_template) module can be used for this.
191 - The O(l3out) must exist before using this module in your playbook.
192 The M(cisco.mso.ndo_l3out_template) module can be used for this.
193 - The O(interface_routing_policy) must exist before using it in the module.
194 Use M(cisco.mso.ndo_l3out_interface_routing_policy) to create the L3Out Node Routing Policy.
195 - The O(custom_qos_policy) must exist before using it in the module.
196 Use M(cisco.mso.ndo_tenant_custom_qos_policy) to create the Custom QoS Policy.
197 seealso:
198 - module: cisco.mso.ndo_template
199 - module: cisco.mso.ndo_l3out_template
200 - module: cisco.mso.ndo_l3out_interface_routing_policy
201 - module: cisco.mso.ndo_tenant_custom_qos_policy
202 extends_documentation_fragment: cisco.mso.modules
203 """
204
205 EXAMPLES = r"""
206 - name: Create an L3Out interface group policy
207 cisco.mso.ndo_l3out_interface_group_policy:
208 host: mso_host
209 username: admin
210 password: SomeSecretPassword
211 template: l3out_template
212 l3out: l3out
213 name: interface_group_policy_1
214 description: Test description
215 interface_routing_policy:
216 name: ansible_l3out_interface_routing_policy
217 template: ansible_tenant_template
218 bfd:
219 enable: true
220 authentication: true
221 key_id: 1
222 key: TestKey
223 bfd_multi_hop:
224 enable: true
225 authentication: true
226 key_id: 1
227 key: TestKey
228 ospf:
229 enable: true
230 authentication_type: simple
231 key_id: 1
232 key: TestKey
233 custom_qos_policy:
234 template: ansible_tenant_template
235 name: ansible_custom_qos_policy
236 qos_priority: level1
237 state: present
238
239 - name: Query an existing L3Out interface group policy with name
240 cisco.mso.ndo_l3out_interface_group_policy:
241 host: mso_host
242 username: admin
243 password: SomeSecretPassword
244 template: l3out_template
245 l3out: l3out
246 name: interface_group_policy_1
247 state: query
248 register: query_with_name
249
250 - name: Query all existing L3Out interface group policies under l3out
251 cisco.mso.ndo_l3out_interface_group_policy:
252 host: mso_host
253 username: admin
254 password: SomeSecretPassword
255 template: l3out_template
256 l3out: l3out
257 state: query
258
259 - name: Delete an existing L3Out interface group policy with name
260 cisco.mso.ndo_l3out_interface_group_policy:
261 host: mso_host
262 username: admin
263 password: SomeSecretPassword
264 template: l3out_template
265 l3out: l3out
266 name: interface_group_policy_1
267 state: absent
268 """
269
270 RETURN = r"""
271 """
272
273 import copy
274 from ansible.module_utils.basic import AnsibleModule
275 from ansible_collections.cisco.mso.plugins.module_utils.mso import (
276 MSOModule,
277 mso_argument_spec,
278 )
279 from ansible_collections.cisco.mso.plugins.module_utils.template import (
280 MSOTemplate,
281 KVPair,
282 )
283 from ansible_collections.cisco.mso.plugins.module_utils.utils import (
284 append_update_ops_data,
285 check_if_all_elements_are_none,
286 )
287 from ansible_collections.cisco.mso.plugins.module_utils.constants import QOS_LEVEL
288
289
290 def main():
291 argument_spec = mso_argument_spec()
292 argument_spec.update(
293 template=dict(type="str", aliases=["l3out_template"]),
294 template_id=dict(type="str", aliases=["l3out_template_id"]),
295 l3out=dict(type="str", aliases=["l3out_name"]),
296 l3out_uuid=dict(type="str"),
297 description=dict(type="str"),
298 name=dict(type="str", aliases=["l3out_interface_group_policy"]),
299 interface_routing_policy=dict(
300 type="dict",
301 options=dict(
302 name=dict(type="str"),
303 template=dict(type="str"),
304 template_id=dict(type="str"),
305 ),
306 required_by={
307 "template": "name",
308 "template_id": "name",
309 },
310 mutually_exclusive=[
311 ["template", "template_id"],
312 ],
313 ),
314 interface_routing_policy_uuid=dict(type="str"),
315 bfd=dict(
316 type="dict",
317 options=dict(
318 enable=dict(type="bool"),
319 authentication=dict(type="bool"),
320 key_id=dict(type="int"),
321 key=dict(type="str", no_log=True),
322 ),
323 ),
324 bfd_multi_hop=dict(
325 type="dict",
326 options=dict(
327 enable=dict(type="bool"),
328 authentication=dict(type="bool"),
329 key_id=dict(type="int"),
330 key=dict(type="str", no_log=True),
331 ),
332 ),
333 ospf=dict(
334 type="dict",
335 options=dict(
336 enable=dict(type="bool"),
337 authentication_type=dict(type="str", choices=["simple", "md5", "none"]),
338 key_id=dict(type="int"),
339 key=dict(type="str", no_log=True),
340 ),
341 ),
342 qos_priority=dict(type="str", choices=QOS_LEVEL),
343 custom_qos_policy=dict(
344 type="dict",
345 options=dict(
346 name=dict(type="str"),
347 template=dict(type="str"),
348 template_id=dict(type="str"),
349 ),
350 required_by={
351 "template": "name",
352 "template_id": "name",
353 },
354 mutually_exclusive=[
355 ["template", "template_id"],
356 ],
357 ),
358 custom_qos_policy_uuid=dict(type="str"),
359 state=dict(type="str", default="query", choices=["absent", "query", "present"]),
360 )
361
362 module = AnsibleModule(
363 argument_spec=argument_spec,
364 supports_check_mode=True,
365 required_if=[
366 ["state", "absent", ["name"]],
367 ["state", "present", ["name"]],
368 ],
369 required_one_of=[
370 ["template", "template_id"],
371 ["l3out", "l3out_uuid"],
372 ],
373 mutually_exclusive=[
374 ["template", "template_id"],
375 ["l3out", "l3out_uuid"],
376 ["interface_routing_policy", "interface_routing_policy_uuid"],
377 ["custom_qos_policy", "custom_qos_policy_uuid"],
378 ],
379 )
380
381 mso = MSOModule(module)
382
383 template = module.params.get("template")
384 template_id = module.params.get("template_id")
385 l3out = module.params.get("l3out")
386 l3out_uuid = module.params.get("l3out_uuid")
387 name = module.params.get("name")
388 description = module.params.get("description")
389 interface_routing_policy = module.params.get("interface_routing_policy")
390 interface_routing_policy_uuid = module.params.get("interface_routing_policy_uuid")
391 bfd = module.params.get("bfd")
392 bfd_multi_hop = module.params.get("bfd_multi_hop")
393 ospf = module.params.get("ospf")
394 qos_priority = module.params.get("qos_priority")
395 custom_qos_policy = module.params.get("custom_qos_policy")
396 custom_qos_policy_uuid = module.params.get("custom_qos_policy_uuid")
397 state = module.params.get("state")
398
399 mso_template = MSOTemplate(mso, "l3out", template, template_id)
400 mso_template.validate_template("l3out")
401 object_description = "L3Out Interface Group Policy"
402
403 l3out_object = mso_template.get_l3out_object(l3out_uuid, l3out, True)
404 existing_interface_groups = l3out_object.details.get("interfaceGroups", [])
405 mso.check_template_when_name_is_provided(interface_routing_policy)
406 mso.check_template_when_name_is_provided(custom_qos_policy)
407 reference_dict = {
408 "qos": {
409 "name": "qosName",
410 "reference": "qosRef",
411 "type": "qos",
412 "template": "qosTemplateName",
413 "templateId": "qosTemplateId",
414 },
415 "interfaceRoutingPolicy": {
416 "name": "interfaceRoutingPolicyName",
417 "reference": "interfaceRoutingPolicyRef",
418 "type": "l3OutIntfPolGroup",
419 "template": "interfaceRoutingPolicyTemplateName",
420 "templateId": "interfaceRoutingPolicyTemplateId",
421 },
422 }
423 if name:
424 match = mso_template.get_object_by_key_value_pairs(
425 object_description,
426 existing_interface_groups,
427 [KVPair("name", name)],
428 )
429 if match:
430 mso_template.update_config_with_template_and_references(match.details, reference_dict)
431 mso.existing = mso.previous = copy.deepcopy(match.details)
432 else:
433 mso.existing = mso.previous = [
434 mso_template.update_config_with_template_and_references(interface_group, reference_dict) for interface_group in existing_interface_groups
435 ]
436
437 if state != "query":
438 interface_group_policy_path = "/l3outTemplate/l3outs/{0}/interfaceGroups/{1}".format(l3out_object.index, match.index if match else "-")
439
440 ops = []
441
442 protocols_dict = {"bfd": bfd, "bfdMultiHop": bfd_multi_hop, "ospf": ospf}
443 empty_interface_routing_policy = False
444 empty_custom_qos_policy = False
445
446 if state == "present":
447 check_authentication_requirements(mso, protocols_dict)
448 mso_values = dict(
449 name=name,
450 description=description,
451 interfaceRoutingPolicyRef=interface_routing_policy_uuid,
452 qosPriority=qos_priority,
453 qosRef=custom_qos_policy_uuid,
454 )
455
456 use_same_instance = (
457 interface_routing_policy
458 and custom_qos_policy
459 and (
460 (interface_routing_policy.get("template") is not None and interface_routing_policy.get("template") == custom_qos_policy.get("template"))
461 or (
462 interface_routing_policy.get("template_id") is not None
463 and interface_routing_policy.get("template_id") == custom_qos_policy.get("template_id")
464 )
465 )
466 )
467
468 if use_same_instance:
469 tenant_template = MSOTemplate(mso, "tenant", interface_routing_policy.get("template"), interface_routing_policy.get("template_id"))
470 tenant_template.validate_template("tenantPolicy")
471 process_tenant_policy(
472 mso_values,
473 tenant_template,
474 interface_routing_policy,
475 "interfaceRoutingPolicyRef",
476 "l3OutIntfPolGroups",
477 )
478 process_tenant_policy(mso_values, tenant_template, custom_qos_policy, "qosRef", "qosPolicies")
479 else:
480 if interface_routing_policy:
481 empty_interface_routing_policy = check_if_all_elements_are_none(list(interface_routing_policy.values()))
482 if not empty_interface_routing_policy:
483 tenant_template_interface = MSOTemplate(
484 mso, "tenant", interface_routing_policy.get("template"), interface_routing_policy.get("template_id")
485 )
486 tenant_template_interface.validate_template("tenantPolicy")
487 process_tenant_policy(mso_values, tenant_template_interface, interface_routing_policy, "interfaceRoutingPolicyRef", "l3OutIntfPolGroups")
488
489 if custom_qos_policy:
490 empty_custom_qos_policy = check_if_all_elements_are_none(list(custom_qos_policy.values()))
491 if not empty_custom_qos_policy:
492 tenant_template_qos = MSOTemplate(mso, "tenant", custom_qos_policy.get("template"), custom_qos_policy.get("template_id"))
493 tenant_template_qos.validate_template("tenantPolicy")
494 process_tenant_policy(mso_values, tenant_template_qos, custom_qos_policy, "qosRef", "qosPolicies")
495
496 if match:
497 mso_values_remove = list()
498
499 if (interface_routing_policy_uuid == "" or empty_interface_routing_policy) and match.details.get("interfaceRoutingPolicyRef"):
500 mso_values_remove.append("interfaceRoutingPolicyRef")
501 if (custom_qos_policy_uuid == "" or empty_custom_qos_policy) and match.details.get("qosRef"):
502 mso_values_remove.append("qosRef")
503
504 for protocol_name, protocol_dict in protocols_dict.items():
505 if protocol_dict is not None:
506 attribute_is_empty = check_if_all_elements_are_none(list(protocol_dict.values()))
507
508 if match.details.get(protocol_name, {}).get("key", {}).get("ref"):
509 match.details[protocol_name]["key"].pop("ref", None)
510 mso.previous[protocol_name]["key"].pop("ref", None)
511 mso.existing[protocol_name]["key"].pop("ref", None)
512
513 if attribute_is_empty and match.details.get(protocol_name):
514 mso_values_remove.append(protocol_name)
515
516 elif not attribute_is_empty and not match.details.get(protocol_name):
517 update_mso_values_attributes_payload(mso_values, {protocol_name: protocol_dict})
518
519 elif not attribute_is_empty and match.details.get(protocol_name):
520 mso_values[(protocol_name, "enabled")] = protocol_dict.get("enable")
521 if protocol_dict.get("enable") is True:
522 if protocol_name == "ospf":
523 mso_values[(protocol_name, "authType")] = protocol_dict.get("authentication_type")
524 else:
525 mso_values[(protocol_name, "authEnabled")] = protocol_dict.get("authentication")
526 mso_values[(protocol_name, "keyID")] = protocol_dict.get("key_id")
527
528 if protocol_dict.get("key") is not None:
529 if match.details.get(protocol_name, {}).get("key") is not None:
530 mso_values[(protocol_name, "key", "value")] = protocol_dict.get("key")
531 else:
532 mso_values[(protocol_name, "key")] = dict(value=protocol_dict.get("key"))
533 else:
534 if protocol_name == "ospf" and match.details.get(protocol_name, {}).get("authType"):
535 mso_values_remove.extend([(protocol_name, "key"), (protocol_name, "keyID"), (protocol_name, "authType")])
536 elif match.details.get(protocol_name, {}).get("authEnabled"):
537 mso_values_remove.extend([(protocol_name, "key"), (protocol_name, "keyID"), (protocol_name, "authEnabled")])
538
539 append_update_ops_data(ops, match.details, interface_group_policy_path, mso_values, mso_values_remove)
540 mso.sanitize(match.details, collate=True)
541 else:
542 update_mso_values_attributes_payload(mso_values, protocols_dict)
543 mso.sanitize(mso_values)
544 ops.append(dict(op="add", path=interface_group_policy_path, value=mso_values))
545
546 elif state == "absent":
547 if mso.existing:
548 ops.append(dict(op="remove", path=interface_group_policy_path))
549
550 if not module.check_mode and ops:
551 mso_template.template = mso.request(mso_template.template_path, method="PATCH", data=ops)
552 l3out_object = mso_template.get_l3out_object(l3out_uuid, l3out, True)
553 interface_groups = l3out_object.details.get("interfaceGroups", [])
554 match = mso_template.get_object_by_key_value_pairs(
555 object_description,
556 interface_groups,
557 [KVPair("name", name)],
558 )
559 if match:
560 for protocol_name in protocols_dict.keys():
561 if match.details.get(protocol_name, {}).get("key", {}).get("ref"):
562 match.details[protocol_name]["key"].pop("ref", None)
563 mso_template.update_config_with_template_and_references(match.details, reference_dict)
564 mso.existing = match.details
565 else:
566 mso.existing = {} # When the state is absent
567 elif module.check_mode and state != "query": # When the state is present/absent with check mode
568 mso_template.update_config_with_template_and_references(mso.proposed, reference_dict)
569 mso.existing = mso.proposed if state == "present" else {}
570
571 mso.exit_json()
572
573
574 def check_authentication_requirements(mso, protocols_dict):
575 failed_attributes = []
576
577 for protocol_name, protocol_dict in protocols_dict.items():
578 if protocol_dict is not None:
579 if (
580 protocol_dict.get("enable") is True
581 and (protocol_dict.get("authentication") is True or protocol_dict.get("authentication_type") in ["md5", "simple"])
582 and (protocol_dict.get("key") is None or protocol_dict.get("key_id") is None)
583 ):
584 failed_attributes.append("key and key_id are required under {0}".format(protocol_name))
585 elif (protocol_dict.get("enable") is not True) and (
586 protocol_dict.get("authentication") is not None or protocol_dict.get("key") is not None or protocol_dict.get("key_id") is not None
587 ):
588 failed_attributes.append("{0} must be enabled in order to use authentication, key and key_id".format(protocol_name))
589
590 if failed_attributes:
591 failure_messages = " | ".join(failed_attributes)
592 mso.fail_json(msg=failure_messages)
593
594
595 def update_mso_values_attributes_payload(mso_values, protocols_dict):
596 for protocol_name, protocol_dict in protocols_dict.items():
597 if protocol_dict is not None:
598 if protocol_dict.get("enable") is not None:
599 mso_values[protocol_name] = {
600 "enabled": protocol_dict.get("enable"),
601 }
602 if protocol_dict.get("enable") is True:
603 if protocol_dict.get("authentication") is True:
604 mso_values[protocol_name].update(
605 {
606 "authEnabled": protocol_dict.get("authentication"),
607 "keyID": protocol_dict.get("key_id"),
608 "key": {"value": protocol_dict.get("key")},
609 }
610 )
611 elif protocol_dict.get("authentication_type") in ["md5", "simple"]:
612 mso_values[protocol_name].update(
613 {
614 "authType": protocol_dict.get("authentication_type"),
615 "keyID": protocol_dict.get("key_id"),
616 "key": {"value": protocol_dict.get("key")},
617 }
618 )
619
620
621 def process_tenant_policy(mso_values, tenant_template, policy, policy_ref, policy_type):
622 mso_values[policy_ref] = tenant_template.get_template_policy_uuid("tenant", policy.get("name"), policy_type)
623
624
625 if __name__ == "__main__":
626 main()