Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2025, Samita Bhattacharjee (@samiib) <[email protected]>
5
6 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8
9 from __future__ import absolute_import, division, print_function
10
11 __metaclass__ = type
12
13 ANSIBLE_METADATA = {
14 "metadata_version": "1.1",
15 "status": ["preview"],
16 "supported_by": "community",
17 }
18
19 DOCUMENTATION = r"""
20 ---
21 module: ndo_set_rule_policy
22 version_added: "2.12.0"
23 short_description: Manage Tenant Set Rule Policies on Cisco Nexus Dashboard Orchestrator (NDO).
24 description:
25 - Manage Tenant Set Rule Policies on Cisco Nexus Dashboard Orchestrator (NDO).
26 - This module is only supported on ND v4.1 (NDO v5.1) and later.
27 author:
28 - Samita Bhattacharjee (@samiib)
29 options:
30 template:
31 description:
32 - The name of the template.
33 - The template must be a tenant template.
34 - This parameter or O(template_id) is required.
35 type: str
36 template_id:
37 description:
38 - The ID of the tenant template.
39 - This parameter or O(template) is required.
40 type: str
41 name:
42 description:
43 - The name of the Set Rule Policy.
44 type: str
45 aliases: [ set_rule_policy ]
46 uuid:
47 description:
48 - The UUID of the Set Rule Policy.
49 - This parameter is required when the O(name) attribute needs to be updated.
50 type: str
51 aliases: [ set_rule_policy_uuid ]
52 description:
53 description:
54 - The description of the Set Rule Policy.
55 type: str
56 set_community:
57 description:
58 - The community rule to add to the Set Rule Policy.
59 - Providing an empty dictionary will remove the O(set_community={}) rule from the Set Rule Policy.
60 type: dict
61 suboptions:
62 community:
63 description:
64 - The community value.
65 type: str
66 criteria:
67 description:
68 - The criteria to be applied to the community value.
69 type: str
70 choices: [ none, replace, append ]
71 set_route_tag:
72 description:
73 - The route tag rule to add to the Set Rule Policy.
74 - The value must be a number between 0 and 999999999.
75 - Providing an empty string will remove the O(set_route_tag="") rule from the Set Rule Policy.
76 type: str
77 set_dampening:
78 description:
79 - The dampening rule to add to the Set Rule Policy.
80 - Providing an empty dictionary will remove the O(set_dampening={}) rule from the Set Rule Policy.
81 type: dict
82 suboptions:
83 half_life:
84 description:
85 - The half life time in minutes.
86 - The value must be between 1 and 60.
87 type: int
88 reuse_limit:
89 description:
90 - The re-use limit.
91 - The value must be between 1 and 20000.
92 type: int
93 suppress_limit:
94 description:
95 - The suppress limit.
96 - The value must be between 1 and 20000.
97 type: int
98 max_suppress_time:
99 description:
100 - The maximum suppress time in minutes.
101 - The value must be between 1 and 255.
102 type: int
103 set_weight:
104 description:
105 - The weight rule to add to the Set Rule Policy.
106 - The value must be a number between 0 and 9999.
107 - Providing an empty string will remove the O(set_weight="") rule from the Set Rule Policy.
108 type: str
109 set_next_hop:
110 description:
111 - The next hop rule to add to the Set Rule Policy.
112 - The value must be a valid IPv4 or IPv6 address.
113 - Providing an empty string will remove the O(set_next_hop="") rule from the Set Rule Policy.
114 type: str
115 set_preference:
116 description:
117 - The preference rule to add to the Set Rule Policy.
118 - The value must be between 0 and 999999999.
119 - Providing an empty string will remove the O(set_preference="") rule from the Set Rule Policy.
120 type: str
121 set_metric:
122 description:
123 - The metric rule to add to the Set Rule Policy.
124 - The value must be between 0 and 999999999.
125 - Providing an empty string will remove the O(set_metric="") rule from the Set Rule Policy.
126 type: str
127 set_metric_type:
128 description:
129 - The type of metric rule to add to the Set Rule Policy.
130 - Providing an empty string will remove the O(set_metric_type="") from the Set Rule Policy.
131 type: str
132 choices: [ ospf_type1, ospf_type2, type1, type2, '' ]
133 set_next_hop_propagate:
134 description:
135 - The next hop propagation value to add to the Set Rule Policy.
136 - Providing a value of C(false) will remove next hop propagation from the Set Rule Policy.
137 - O(set_next_hop_propagate) cannot be enabled with O(set_route_tag) configured.
138 type: bool
139 set_multi_path:
140 description:
141 - The multipath option to add to the Set Rule Policy.
142 - Providing a value of C(false) will remove multipath from the Set Rule Policy.
143 - Enabling multipath requires O(set_next_hop_propagate=true) to be enabled.
144 type: bool
145 set_additional_community:
146 description:
147 - The append list of communities to configure in the Set Rule Policy.
148 - Providing an empty list will remove the O(set_additional_community=[]) from the Set Rule Policy.
149 type: list
150 elements: str
151 aliases: [ set_add_communities ]
152 set_as_path:
153 description:
154 - The Autonomous System (AS) path rules to add to the Set Rule Policy.
155 - Providing an empty dictionary will remove the O(set_as_path={}) rules from the Set Rule Policy.
156 type: dict
157 suboptions:
158 last_asn_count:
159 description:
160 - The prepend last AS count.
161 - The value must be between 1 and 10.
162 type: int
163 path_asn_list:
164 description:
165 - The list of path AS numbers to prepend.
166 - Providing an empty list will remove the O(set_as_path.path_asn_list=[]).
167 type: list
168 elements: dict
169 suboptions:
170 asn:
171 description:
172 - The AS number.
173 - The value must be between 1 and 10.
174 type: int
175 required: true
176 order:
177 description:
178 - The order of the AS number.
179 - The value must be between 0 and 31.
180 type: int
181 required: true
182 state:
183 description:
184 - Determines the desired state of the resource.
185 - Use C(absent) to remove the resource.
186 - Use C(query) to list the resource.
187 - Use C(present) to create or update the resource.
188 type: str
189 choices: [ absent, query, present ]
190 default: query
191 notes:
192 - The O(template) must exist before using this module in your playbook.
193 Use M(cisco.mso.ndo_template) to create the Tenant template.
194 seealso:
195 - module: cisco.mso.ndo_template
196 extends_documentation_fragment: cisco.mso.modules
197 """
198
199 EXAMPLES = r"""
200 - name: Create a new Set Rule Policy
201 cisco.mso.ndo_set_rule_policy:
202 host: mso_host
203 username: admin
204 password: SomeSecretPassword
205 template: tenant_template
206 name: set_rule_policy_1
207 description: Ansible Set Rule Policy
208 set_community:
209 community: no-export
210 criteria: replace
211 set_additional_community:
212 - no-advertise
213 - extended:color:35
214 set_route_tag: 500
215 set_dampening:
216 half_life: 15
217 reuse_limit: 750
218 suppress_limit: 2000
219 max_suppress_time: 60
220 set_weight: 50
221 set_next_hop: 'aa::'
222 set_preference: 200
223 set_metric: 100
224 set_metric_type: type2
225 set_as_path:
226 last_asn_count: 10
227 path_asn_list:
228 - order: 11
229 asn: 1
230 - order: 10
231 asn: 2
232 state: present
233 register: create_set_rule_policy_1
234
235 - name: Update the name of the Set Rule Policy using UUID
236 cisco.mso.ndo_set_rule_policy:
237 host: mso_host
238 username: admin
239 password: SomeSecretPassword
240 template_id: "{{ create_tenant.current.templateId }}"
241 uuid: "{{ create_set_rule_policy_1.current.uuid }}"
242 name: set_rule_policy_1_updated
243 state: present
244 register: update_set_rule_policy_1
245
246 - name: Query an existing Set Rule Policy using UUID
247 cisco.mso.ndo_set_rule_policy:
248 host: mso_host
249 username: admin
250 password: SomeSecretPassword
251 template: tenant_template
252 uuid: "{{ create_set_rule_policy_1.current.uuid }}"
253 state: query
254 register: query_with_uuid
255
256 - name: Query an existing Set Rule Policy using name
257 cisco.mso.ndo_set_rule_policy:
258 host: mso_host
259 username: admin
260 password: SomeSecretPassword
261 template: tenant_template
262 name: set_rule_policy_1_updated
263 state: query
264 register: query_with_name
265
266 - name: Query all Set Rule Policies
267 cisco.mso.ndo_set_rule_policy:
268 host: mso_host
269 username: admin
270 password: SomeSecretPassword
271 template: tenant_template
272 state: query
273 register: query_all
274
275 - name: Remove set rules from a Set Rule Policy
276 cisco.mso.ndo_set_rule_policy:
277 host: mso_host
278 username: admin
279 password: SomeSecretPassword
280 template: tenant_template
281 name: set_rule_policy_1_updated
282 set_additional_community: []
283 set_community: {}
284 set_route_tag: ''
285 set_propagate_next_hop: false
286 state: present
287
288 - name: Delete an existing Set Rule Policy using UUID
289 cisco.mso.ndo_set_rule_policy:
290 host: mso_host
291 username: admin
292 password: SomeSecretPassword
293 template: tenant_template
294 uuid: "{{ create_set_rule_policy_1.current.uuid }}"
295 state: absent
296
297 - name: Delete an existing Set Rule Policy using Name
298 cisco.mso.ndo_set_rule_policy:
299 host: mso_host
300 username: admin
301 password: SomeSecretPassword
302 template: tenant_template
303 name: set_rule_policy_1_updated
304 state: absent
305 """
306
307 RETURN = r"""
308 """
309
310 from ansible.module_utils.basic import AnsibleModule
311 from ansible_collections.cisco.mso.plugins.module_utils.mso import MSOModule, mso_argument_spec
312 from ansible_collections.cisco.mso.plugins.module_utils.template import MSOTemplate
313 from ansible_collections.cisco.mso.plugins.module_utils.utils import append_update_ops_data, check_if_all_elements_are_none
314 from ansible_collections.cisco.mso.plugins.module_utils.constants import ROUTE_MAP_METRIC_TYPE_MAP
315 import copy
316
317
318 def main():
319 argument_spec = mso_argument_spec()
320 argument_spec.update(
321 template=dict(type="str"),
322 template_id=dict(type="str"),
323 name=dict(type="str", aliases=["set_rule_policy"]),
324 uuid=dict(type="str", aliases=["set_rule_policy_uuid"]),
325 description=dict(type="str"),
326 set_community=dict(
327 type="dict",
328 options=dict(
329 community=dict(type="str"),
330 criteria=dict(type="str", choices=["none", "replace", "append"]),
331 ),
332 ),
333 set_route_tag=dict(type="str"),
334 set_weight=dict(type="str"),
335 set_dampening=dict(
336 type="dict",
337 options=dict(
338 half_life=dict(type="int"),
339 reuse_limit=dict(type="int"),
340 suppress_limit=dict(type="int"),
341 max_suppress_time=dict(type="int"),
342 ),
343 ),
344 set_next_hop=dict(type="str"),
345 set_preference=dict(type="str"),
346 set_metric=dict(type="str"),
347 set_metric_type=dict(type="str", choices=list(ROUTE_MAP_METRIC_TYPE_MAP)),
348 set_next_hop_propagate=dict(type="bool"),
349 set_multi_path=dict(type="bool"),
350 set_additional_community=dict(type="list", elements="str", aliases=["set_add_communities"]),
351 set_as_path=dict(
352 type="dict",
353 options=dict(
354 last_asn_count=dict(type="int"),
355 path_asn_list=dict(
356 type="list",
357 elements="dict",
358 options=dict(
359 asn=dict(type="int", required=True),
360 order=dict(type="int", required=True),
361 ),
362 ),
363 ),
364 ),
365 state=dict(type="str", default="query", choices=["absent", "query", "present"]),
366 )
367
368 module = AnsibleModule(
369 argument_spec=argument_spec,
370 supports_check_mode=True,
371 mutually_exclusive=[
372 ("template", "template_id"),
373 ],
374 required_if=[
375 ["state", "absent", ["name", "uuid"], True],
376 ["state", "present", ["name", "uuid"], True],
377 ],
378 required_one_of=[["template", "template_id"]],
379 )
380
381 mso = MSOModule(module)
382
383 template = module.params.get("template")
384 template_id = module.params.get("template_id")
385 name = module.params.get("name")
386 uuid = module.params.get("uuid")
387 description = module.params.get("description")
388 set_community = module.params.get("set_community")
389 set_route_tag = get_int_empty_or_none(module.params.get("set_route_tag"))
390 set_weight = get_int_empty_or_none(module.params.get("set_weight"))
391 set_preference = get_int_empty_or_none(module.params.get("set_preference"))
392 set_metric = get_int_empty_or_none(module.params.get("set_metric"))
393 set_dampening = module.params.get("set_dampening")
394 set_next_hop = module.params.get("set_next_hop")
395 set_metric_type = ROUTE_MAP_METRIC_TYPE_MAP.get(module.params.get("set_metric_type"), None)
396 set_next_hop_propagate = module.params.get("set_next_hop_propagate")
397 set_multi_path = module.params.get("set_multi_path")
398 set_additional_community = module.params.get("set_additional_community")
399 if set_additional_community is not None and len(set_additional_community) > 0:
400 set_additional_community = [dict(criteria="append", community=comm) for comm in set_additional_community]
401 set_as_path = None
402 if module.params.get("set_as_path") is not None:
403 set_as_path = []
404 last_asn_count = module.params.get("set_as_path", {}).get("last_asn_count")
405 path_asn_list = module.params.get("set_as_path", {}).get("path_asn_list")
406 if last_asn_count is not None:
407 set_as_path.append(dict(criteria="prepend-last-as", asnCount=last_asn_count))
408 if path_asn_list is not None:
409 set_as_path.append(dict(criteria="prepend", pathASNs=path_asn_list))
410 state = module.params.get("state")
411
412 if set_dampening is not None and check_if_all_elements_are_none(set_dampening.values()):
413 set_dampening = {}
414
415 if set_community is not None and check_if_all_elements_are_none(set_community.values()):
416 set_community = {}
417
418 ops = []
419 match = None
420
421 mso_template = MSOTemplate(mso, "tenant", template, template_id)
422 mso_template.validate_template("tenantPolicy")
423
424 object_description = "Set Rule Policy"
425 path = "/tenantPolicyTemplate/template/setRulePolicies"
426 set_rule_policy_path = None
427
428 match = mso_template.get_set_rule_policy_object(uuid, name, search_object=None, fail_module=False)
429 if (name or uuid) and match:
430 set_rule_policy_path = "{0}/{1}".format(path, match.index)
431 mso_template.update_config_with_template_and_references(match.details)
432 mso.existing = copy.deepcopy(match.details)
433 mso.previous = copy.deepcopy(match.details)
434 elif match:
435 mso.existing = mso.previous = [mso_template.update_config_with_template_and_references(obj) for obj in match]
436
437 if state == "present":
438 if uuid and not mso.existing:
439 mso.fail_json(msg="{0} with the UUID: '{1}' not found".format(object_description, uuid))
440
441 if match:
442 mso_values = dict(name=name, description=description)
443 mso_values_remove = list()
444
445 if set_route_tag == "" and match.details.get("setRouteTag"):
446 mso_values_remove.append("setRouteTag")
447 elif set_route_tag:
448 mso_values["setRouteTag"] = set_route_tag
449
450 if set_weight == "" and match.details.get("setWeight"):
451 mso_values_remove.append("setWeight")
452 elif set_weight:
453 mso_values["setWeight"] = set_weight
454
455 if set_next_hop == "" and match.details.get("setNextHop"):
456 mso_values_remove.append("setNextHop")
457 elif set_next_hop:
458 mso_values["setNextHop"] = set_next_hop
459
460 if set_preference == "" and match.details.get("setPreference"):
461 mso_values_remove.append("setPreference")
462 elif set_preference:
463 mso_values["setPreference"] = set_preference
464
465 if set_metric == "" and match.details.get("setMetric"):
466 mso_values_remove.append("setMetric")
467 elif set_metric:
468 mso_values["setMetric"] = set_metric
469
470 if set_metric_type == "" and match.details.get("setMetricType"):
471 mso_values_remove.append("setMetricType")
472 elif set_metric_type:
473 mso_values["setMetricType"] = set_metric_type
474
475 if set_next_hop_propagate is False and match.details.get("setNextHopPropagate"):
476 mso_values_remove.append("setNextHopPropagate")
477 elif set_next_hop_propagate:
478 mso_values["setNextHopPropagate"] = set_next_hop_propagate
479
480 if set_multi_path is False and match.details.get("setMultiPath"):
481 mso_values_remove.append("setMultiPath")
482 elif set_multi_path:
483 mso_values["setMultiPath"] = set_multi_path
484
485 if set_additional_community == [] and match.details.get("setAddCommunities"):
486 mso_values_remove.append("setAddCommunities")
487 elif set_additional_community:
488 mso_values["setAddCommunities"] = set_additional_community
489
490 if set_as_path == [] and match.details.get("setAsPath"):
491 mso_values_remove.append("setAsPath")
492 elif set_as_path:
493 mso_values["setAsPath"] = set_as_path
494
495 if set_community == {} and match.details.get("setCommunity"):
496 mso_values_remove.append("setCommunity")
497 elif set_community:
498 mso_values[("setCommunity", "community")] = set_community.get("community")
499 mso_values[("setCommunity", "criteria")] = set_community.get("criteria")
500
501 if set_dampening == {} and match.details.get("setDampening"):
502 mso_values_remove.append("setDampening")
503 elif set_dampening:
504 mso_values[("setDampening", "halfLife")] = set_dampening.get("half_life")
505 mso_values[("setDampening", "reuseLimit")] = set_dampening.get("reuse_limit")
506 mso_values[("setDampening", "suppressLimit")] = set_dampening.get("suppress_limit")
507 mso_values[("setDampening", "maxSuppressTime")] = set_dampening.get("max_suppress_time")
508 proposed_payload = copy.deepcopy(match.details)
509 append_update_ops_data(ops, proposed_payload, set_rule_policy_path, mso_values, mso_values_remove)
510 mso.sanitize(proposed_payload, collate=True)
511 else:
512 mso_values = dict(
513 name=name,
514 description=description,
515 setRouteTag=set_route_tag,
516 setWeight=set_weight,
517 setNextHop=set_next_hop,
518 setPreference=set_preference,
519 setMetric=set_metric,
520 setMetricType=set_metric_type,
521 setNextHopPropagate=set_next_hop_propagate,
522 setMultiPath=set_multi_path,
523 setAddCommunities=set_additional_community,
524 setAsPath=set_as_path,
525 setCommunity=set_community,
526 setDampening=(
527 dict(
528 halfLife=set_dampening.get("half_life"),
529 reuseLimit=set_dampening.get("reuse_limit"),
530 suppressLimit=set_dampening.get("suppress_limit"),
531 maxSuppressTime=set_dampening.get("max_suppress_time"),
532 )
533 if set_dampening
534 else None
535 ),
536 )
537 mso.sanitize(mso_values)
538 ops.append(dict(op="add", path="{0}/-".format(path), value=mso.sent))
539
540 elif state == "absent":
541 if match:
542 ops.append(dict(op="remove", path=set_rule_policy_path))
543
544 if not module.check_mode and ops:
545 response = mso.request(mso_template.template_path, method="PATCH", data=ops)
546 match = mso_template.get_set_rule_policy_object(uuid, name, search_object=response, fail_module=False)
547 if match:
548 mso_template.update_config_with_template_and_references(match.details)
549 mso.existing = match.details # When the state is present
550 else:
551 mso.existing = {} # When the state is absent
552 elif module.check_mode and state != "query": # When the state is present/absent with check mode
553 mso_template.update_config_with_template_and_references(mso.proposed)
554 mso.existing = mso.proposed if state == "present" else {}
555
556 mso.exit_json()
557
558
559 def get_int_empty_or_none(value):
560 if value == "":
561 return ""
562 return int(value) if value is not None else None
563
564
565 if __name__ == "__main__":
566 main()