Debian Codegraph @

ansible_collections/cisco/mso/plugins/modules/ndo_ipsla_track_list.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 from __future__ import absolute_import, division, print_function
9
10 __metaclass__ = type
11
12 ANSIBLE_METADATA = {
13 "metadata_version": "1.1",
14 "status": ["preview"],
15 "supported_by": "community",
16 }
17
18 DOCUMENTATION = r"""
19 ---
20 module: ndo_ipsla_track_list
21 short_description: Manage IPSLA Track Lists on Cisco Nexus Dashboard Orchestrator (NDO).
22 description:
23 - Manage IP Service Level Agreement (SLA) Track Lists on Cisco Nexus Dashboard Orchestrator (NDO).
24 - This module is only supported on ND v3.1 (NDO v4.3) and later.
25 author:
26 - Samita Bhattacharjee (@samitab)
27 options:
28 template:
29 description:
30 - The name of the template.
31 - The template must be a tenant template.
32 - This parameter or O(template_id) is required.
33 type: str
34 template_id:
35 description:
36 - The ID of the template.
37 - The template must be a tenant template.
38 - This parameter or O(template) is required.
39 type: str
40 ipsla_track_list:
41 description:
42 - The name of the IPSLA Track List.
43 type: str
44 aliases: [ name ]
45 description:
46 description:
47 - The description of the IPSLA Track List.
48 type: str
49 ipsla_track_list_uuid:
50 description:
51 - The UUID of the IPSLA Track List.
52 - This parameter is required when the O(ipsla_track_list) attribute needs to be updated.
53 type: str
54 aliases: [ uuid ]
55 type:
56 description:
57 - The IPSLA Track List type used for determining up or down status.
58 - This parameter is required when creating the IPSLA Track List.
59 type: str
60 choices: [ percentage, weight ]
61 threshold_up:
62 description:
63 - The IPSLA Track List percentage or weight up threshold.
64 - The value must be in the range 0 - 100 when O(type=percentage).
65 - The value must be in the range 0 - 255 when O(type=weight).
66 - The value must be greater than or equal to O(threshold_down).
67 - The default value is 1.
68 type: int
69 aliases: [ up ]
70 threshold_down:
71 description:
72 - The IPSLA Track List percentage or weight down threshold.
73 - The value must be in the range 0 - 100 when O(type=percentage).
74 - The value must be in the range 0 - 255 when O(type=weight).
75 - The value must be less than or equal to O(threshold_up).
76 - The default value is 0.
77 type: int
78 aliases: [ down ]
79 members:
80 description:
81 - The IPSLA Track List members.
82 - Providing a new list of O(members) will replace the existing members from the IPSLA Track List.
83 - Providing an empty list will remove the O(members=[]) from the IPSLA Track List.
84 type: list
85 elements: dict
86 suboptions:
87 destination_ip:
88 description:
89 - The destination IP of the member.
90 - Must be a valid IPv4 or IPv6 address.
91 type: str
92 required: true
93 aliases: [ ip ]
94 weight:
95 description:
96 - The weight of the member.
97 - The default value is 10.
98 type: int
99 ipsla_monitoring_policy:
100 description:
101 - The IPSLA Monitoring Policy to use for the member.
102 - This parameter or O(members.ipsla_monitoring_policy_uuid) is required.
103 type: dict
104 suboptions:
105 name:
106 description:
107 - The name of the IPSLA Monitoring Policy to use for the member.
108 type: str
109 required: true
110 ipsla_monitoring_policy_uuid:
111 description:
112 - The IPSLA Monitoring Policy UUID to use for the member.
113 - This parameter or O(members.ipsla_monitoring_policy) is required.
114 type: str
115 scope_type:
116 description:
117 - The scope type of the member.
118 type: str
119 required: true
120 choices: [ bd, l3out ]
121 scope_uuid:
122 description:
123 - The UUID of the BD or L3Out used as the scope for the member.
124 - This parameter or O(members.scope) is required.
125 type: str
126 scope:
127 description:
128 - The BD or L3Out used as the scope for the member.
129 - This parameter or O(members.scope_uuid) is required.
130 type: dict
131 suboptions:
132 name:
133 description:
134 - The name of the BD or L3Out used as the scope for the member.
135 type: str
136 required: true
137 schema:
138 description:
139 - The name of the Schema associated with the BD scope.
140 - This parameter or O(members.scope.schema_id) is only required when the O(members.scope_type=bd).
141 type: str
142 schema_id:
143 description:
144 - The ID of the Schema associated with the BD scope.
145 - This parameter or O(members.scope.schema) is only required when the O(members.scope_type=bd).
146 type: str
147 template:
148 description:
149 - The name of the Template associated with the BD or L3Out scope.
150 - This parameter or O(members.scope.template_id) is required.
151 type: str
152 template_id:
153 description:
154 - The ID of the Template associated with the BD or L3Out scope.
155 - This parameter or O(members.scope.template) is required.
156 type: str
157 state:
158 description:
159 - Use C(absent) for removing.
160 - Use C(query) for listing an object or multiple objects.
161 - Use C(present) for creating or updating.
162 type: str
163 choices: [ absent, query, present ]
164 default: present
165 notes:
166 - The O(template) must exist before using this module in your playbook.
167 Use M(cisco.mso.ndo_template) to create the Tenant template.
168 - The O(members.ipsla_monitoring_policy) must exist before adding O(members).
169 Use M(cisco.mso.ndo_ipsla_monitoring_policy) to create an IPSLA Monitoring Policy.
170 - The O(members.scope) as either a BD or L3Out must exist before adding O(members).
171 Use M(cisco.mso.ndo_l3out_template) to create an L3Out.
172 Use M(cisco.mso.mso_schema_template_bd) to create a BD.
173 seealso:
174 - module: cisco.mso.ndo_template
175 - module: cisco.mso.ndo_ipsla_monitoring_policy
176 - module: cisco.mso.ndo_l3out_template
177 - module: cisco.mso.mso_schema_template_bd
178 extends_documentation_fragment: cisco.mso.modules
179 """
180
181 EXAMPLES = r"""
182 - name: Create a new IPSLA Track List
183 cisco.mso.ndo_ipsla_track_list:
184 host: mso_host
185 username: admin
186 password: SomeSecretPassword
187 template: ansible_tenant_template
188 ipsla_track_list: ansible_test_ipsla_track_list
189 description: Example track list
190 type: percentage
191 threshold_up: 10
192 threshold_down: 2
193 members:
194 - destination_ip: 1.1.1.1
195 scope_type: bd
196 scope:
197 name: ansible_test_bd
198 template: ansible_test_template
199 schema: ansible_test_schema
200 ipsla_monitoring_policy:
201 name: ansible_test_ipsla_monitoring_policy
202 - destination_ip: 2001:0000:130F:0000:0000:09C0:876A:130B
203 scope_type: l3out
204 scope:
205 name: ansible_test_l3out
206 template: ansible_test_template
207 ipsla_monitoring_policy_uuid: "{{ ipsla_mon_pol.current.uuid }}"
208 - destination_ip: 1.1.1.2
209 scope_type: l3out
210 scope_uuid: "{{ l3out.current.uuid }}"
211 ipsla_monitoring_policy:
212 name: ansible_test_ipsla_monitoring_policy
213 state: present
214 register: ipsla_track_list
215
216 - name: Update an IPSLA Track List name with UUID
217 cisco.mso.ndo_ipsla_track_list:
218 host: mso_host
219 username: admin
220 password: SomeSecretPassword
221 template: ansible_tenant_template
222 ipsla_track_list: ansible_test_ipsla_track_list_updated
223 ipsla_track_list_uuid: "{{ ipsla_track_list.current.uuid }}"
224 state: present
225 register: ipsla_track_list_update
226
227 - name: Query an IPSLA Track List with name
228 cisco.mso.ndo_ipsla_track_list:
229 host: mso_host
230 username: admin
231 password: SomeSecretPassword
232 template: ansible_tenant_template
233 ipsla_track_list: ansible_test_ipsla_track_list
234 state: query
235 register: query_one
236
237 - name: Query an IPSLA Track List with UUID
238 cisco.mso.ndo_ipsla_track_list:
239 host: mso_host
240 username: admin
241 password: SomeSecretPassword
242 template: ansible_tenant_template
243 ipsla_track_list_uuid: "{{ query_one.current.uuid }}"
244 state: query
245 register: query_one_uuid
246
247 - name: Query all IPSLA Track Lists in the template
248 cisco.mso.ndo_ipsla_track_list:
249 host: mso_host
250 username: admin
251 password: SomeSecretPassword
252 template: ansible_tenant_template
253 state: query
254 register: query_all
255
256 - name: Remove all members from an IPSLA Track List
257 cisco.mso.ndo_ipsla_track_list:
258 host: mso_host
259 username: admin
260 password: SomeSecretPassword
261 template: ansible_tenant_template
262 ipsla_track_list: ansible_test_ipsla_track_list
263 type: percentage
264 members: []
265 state: present
266
267 - name: Delete an IPSLA Track List with name
268 cisco.mso.ndo_ipsla_track_list:
269 host: mso_host
270 username: admin
271 password: SomeSecretPassword
272 template: ansible_tenant_template
273 ipsla_track_list: ansible_test_ipsla_track_list
274 state: absent
275
276 - name: Delete an IPSLA Track List with UUID
277 cisco.mso.ndo_ipsla_track_list:
278 host: mso_host
279 username: admin
280 password: SomeSecretPassword
281 template: ansible_tenant_template
282 ipsla_track_list_uuid: "{{ query_one.current.uuid }}"
283 state: absent
284 """
285
286 RETURN = r"""
287 """
288
289 from ansible.module_utils.basic import AnsibleModule
290 from ansible_collections.cisco.mso.plugins.module_utils.mso import (
291 MSOModule,
292 mso_argument_spec,
293 )
294 from ansible_collections.cisco.mso.plugins.module_utils.schema import MSOSchema
295 from ansible_collections.cisco.mso.plugins.module_utils.template import (
296 MSOTemplate,
297 KVPair,
298 )
299 from ansible_collections.cisco.mso.plugins.module_utils.utils import (
300 append_update_ops_data,
301 )
302 import copy
303
304
305 def main():
306 argument_spec = mso_argument_spec()
307 argument_spec.update(
308 dict(
309 template=dict(type="str"),
310 template_id=dict(type="str"),
311 ipsla_track_list=dict(type="str", aliases=["name"]),
312 ipsla_track_list_uuid=dict(type="str", aliases=["uuid"]),
313 description=dict(type="str"),
314 type=dict(type="str", choices=["percentage", "weight"]),
315 threshold_up=dict(type="int", aliases=["up"]),
316 threshold_down=dict(type="int", aliases=["down"]),
317 members=dict(
318 type="list",
319 elements="dict",
320 mutually_exclusive=[
321 ("scope", "scope_uuid"),
322 ("ipsla_monitoring_policy", "ipsla_monitoring_policy_uuid"),
323 ],
324 required_one_of=[
325 ["scope", "scope_uuid"],
326 ["ipsla_monitoring_policy", "ipsla_monitoring_policy_uuid"],
327 ],
328 options=dict(
329 destination_ip=dict(type="str", aliases=["ip"], required=True),
330 ipsla_monitoring_policy=dict(
331 type="dict",
332 options=dict(
333 name=dict(type="str", required=True),
334 ),
335 ),
336 ipsla_monitoring_policy_uuid=dict(type="str"),
337 scope_uuid=dict(type="str"),
338 scope=dict(
339 type="dict",
340 options=dict(
341 name=dict(type="str", required=True),
342 template=dict(type="str"),
343 template_id=dict(type="str"),
344 schema=dict(type="str"),
345 schema_id=dict(type="str"),
346 ),
347 required_one_of=[
348 ["template", "template_id"],
349 ],
350 mutually_exclusive=[
351 ("schema", "schema_id"),
352 ("template", "template_id"),
353 ],
354 ),
355 scope_type=dict(type="str", choices=["bd", "l3out"], required=True),
356 weight=dict(type="int"),
357 ),
358 ),
359 state=dict(type="str", choices=["absent", "query", "present"], default="present"),
360 )
361 )
362
363 module = AnsibleModule(
364 argument_spec=argument_spec,
365 supports_check_mode=True,
366 mutually_exclusive=[
367 ("template", "template_id"),
368 ],
369 required_if=[
370 ["state", "absent", ["ipsla_track_list", "ipsla_track_list_uuid"], True],
371 ["state", "present", ["ipsla_track_list", "ipsla_track_list_uuid"], True],
372 ["state", "present", ["type"]],
373 ],
374 required_one_of=[
375 ["template", "template_id"],
376 ],
377 )
378
379 mso = MSOModule(module)
380
381 template = module.params.get("template")
382 template_id = module.params.get("template_id")
383 ipsla_track_list = module.params.get("ipsla_track_list")
384 description = module.params.get("description")
385 ipsla_track_list_uuid = module.params.get("ipsla_track_list_uuid")
386 list_type = module.params.get("type")
387 thresholds = {
388 "down": module.params.get("threshold_down"),
389 "up": module.params.get("threshold_up"),
390 }
391 members = module.params.get("members")
392 state = module.params.get("state")
393
394 # Validate
395 valid_upper = 100
396 valid_lower = 0
397 if list_type == "weight":
398 valid_upper = 255
399 for threshold_key, threshold_value in thresholds.items():
400 if threshold_value is not None and threshold_value not in range(valid_lower, valid_upper):
401 mso.fail_json(
402 msg="Invalid value provided for threshold_{0}: {1}; it must be in the range {2} - {3}".format(
403 threshold_key, threshold_value, valid_lower, valid_upper
404 )
405 )
406
407 ops = []
408 match = None
409
410 # The object dictionary is used as a cache store for schema & template data.
411 # This is done to limit the amount of API calls when UUID is not specified for member scope references.
412 obj_cache = {}
413
414 mso_template = MSOTemplate(mso, "tenant", template, template_id)
415 mso_template.validate_template("tenantPolicy")
416 obj_cache["template-tenant-{0}".format(template if template else template_id)] = mso_template
417
418 object_description = "IPSLA Track List"
419 path = "/tenantPolicyTemplate/template/ipslaTrackLists"
420
421 existing_ipsla_track_lists = mso_template.template.get("tenantPolicyTemplate", {}).get("template", {}).get("ipslaTrackLists", [])
422 if ipsla_track_list or ipsla_track_list_uuid:
423 match = mso_template.get_object_by_key_value_pairs(
424 object_description,
425 existing_ipsla_track_lists,
426 [KVPair("uuid", ipsla_track_list_uuid) if ipsla_track_list_uuid else KVPair("name", ipsla_track_list)],
427 )
428 if match:
429 set_template_and_references(mso_template, match.details)
430 mso.existing = mso.previous = copy.deepcopy(match.details)
431 else:
432 mso.existing = mso.previous = [set_template_and_references(mso_template, track_list) for track_list in existing_ipsla_track_lists]
433
434 if state == "present":
435 if ipsla_track_list_uuid and not mso.existing:
436 mso.fail_json(msg="{0} with the UUID: '{1}' not found".format(object_description, ipsla_track_list_uuid))
437
438 mso_values = {
439 "name": ipsla_track_list,
440 "description": description,
441 "type": list_type,
442 "{0}Up".format(list_type): thresholds["up"],
443 "{0}Down".format(list_type): thresholds["down"],
444 }
445 if members is not None:
446 mso_values["trackListMembers"] = format_track_list_members(mso, mso_template, members, obj_cache)
447 if match:
448 append_update_ops_data(ops, match.details, "{0}/{1}".format(path, match.index), mso_values)
449 mso.sanitize(match.details, collate=True)
450 else:
451 mso.sanitize(mso_values)
452 ops.append(dict(op="add", path="{0}/-".format(path), value=mso.sent))
453
454 elif state == "absent":
455 if match:
456 ops.append(dict(op="remove", path="{0}/{1}".format(path, match.index)))
457
458 if not module.check_mode and ops:
459 response = mso.request(mso_template.template_path, method="PATCH", data=ops)
460 ipsla_track_lists = response.get("tenantPolicyTemplate", {}).get("template", {}).get("ipslaTrackLists", [])
461 match = mso_template.get_object_by_key_value_pairs(
462 object_description,
463 ipsla_track_lists,
464 [KVPair("uuid", ipsla_track_list_uuid) if ipsla_track_list_uuid else KVPair("name", ipsla_track_list)],
465 )
466 if match:
467 set_template_and_references(mso_template, match.details)
468 mso.existing = match.details
469 else:
470 mso.existing = {}
471 elif module.check_mode and state != "query":
472 set_template_and_references(mso_template, mso.proposed)
473 mso.existing = mso.proposed if state == "present" else {}
474
475 mso.exit_json()
476
477
478 def format_track_list_members(mso, mso_template, members, obj_cache):
479 track_list_members = []
480
481 def get_scope_obj_uuid(scope_type, uuid, obj):
482 if uuid:
483 return uuid
484
485 name = obj.get("name")
486 template = obj.get("template")
487 template_id = obj.get("template_id")
488
489 if scope_type == "bd":
490 schema_name = obj.get("schema")
491 schema_id = obj.get("schema_id")
492 if not schema_name and not schema_id:
493 mso.fail_json(msg="A member scope_type is bd and scope is used but the schema or schema_id option is missing.")
494 key = "schema-{0}-{1}-{2}".format(scope_type, schema_name, template if template else template_id)
495 mso_schema = obj_cache.get(key)
496 if not mso_schema:
497 mso_schema = MSOSchema(mso, schema_name, template, None, schema_id, template_id)
498 obj_cache[key] = mso_schema
499 mso_schema.set_template_bd(name, fail_module=True)
500 return mso_schema.schema_objects.get("template_bd").details.get("uuid")
501
502 if scope_type == "l3out":
503 key = "template-{0}-{1}".format(scope_type, template if template else template_id)
504 mso_template = obj_cache.get(key)
505 if not mso_template:
506 mso_template = MSOTemplate(mso, scope_type, template, template_id)
507 mso_template.validate_template(scope_type)
508 obj_cache[key] = mso_template
509 return mso_template.get_l3out_object(name=name, fail_module=True).details.get("uuid")
510
511 for member in members:
512 scope_type = member.get("scope_type")
513 track_member = {
514 "trackMember": {
515 "destIP": member.get("destination_ip"),
516 "scope": get_scope_obj_uuid(scope_type, member.get("scope_uuid"), member.get("scope")),
517 "scopeType": scope_type,
518 "ipslaMonitoringRef": mso_template.get_ipsla_monitoring_policy(
519 uuid=member.get("ipsla_monitoring_policy_uuid"),
520 name=member.get("ipsla_monitoring_policy").get("name") if member.get("ipsla_monitoring_policy") else None,
521 fail_module=True,
522 ).details.get("uuid"),
523 },
524 "weight": member.get("weight"),
525 }
526 track_list_members.append(track_member)
527 return track_list_members
528
529
530 def set_template_and_references(mso_template, ipsla_track_list_config):
531 l3out_scope_ref = {
532 "name": "scopeName",
533 "reference": "scope",
534 "template": "scopeTemplateName",
535 "templateId": "scopeTemplateId",
536 "type": "l3out",
537 }
538 bd_scope_ref = {
539 "name": "scopeName",
540 "reference": "scope",
541 "template": "scopeTemplateName",
542 "templateId": "scopeTemplateId",
543 "schema": "scopeSchemaName",
544 "schemaId": "scopeSchemaId",
545 "type": "bd",
546 }
547 ipsla_ref = {
548 "name": "ipslaMonitoringPolicyName",
549 "reference": "ipslaMonitoringRef",
550 "type": "ipslaMonitoringPolicy",
551 }
552 mso_template.clear_template_objects_cache()
553 mso_template.update_config_with_template_and_references(ipsla_track_list_config)
554 for track_member in ipsla_track_list_config.get("trackListMembers", []):
555 ref_dict = {}
556 if track_member.get("trackMember", {}).get("scopeType") == "l3out":
557 ref_dict["scope"] = l3out_scope_ref
558 else:
559 ref_dict["scope"] = bd_scope_ref
560 ref_dict["ipslaMonitoringPolicy"] = ipsla_ref
561 mso_template.update_config_with_template_and_references(track_member["trackMember"], ref_dict, False, True)
562 return ipsla_track_list_config
563
564
565 if __name__ == "__main__":
566 main()