Debian Codegraph @

ansible_collections/cisco/aci/plugins/modules/aci_tenant_action_rule_profile.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2023, Dag Wieers (@dagwieers)
5 # Copyright: (c) 2023, Tim Cragg (@timcragg) <[email protected]>
6 # Copyright: (c) 2023, Gaspard Micol (@gmicol) <[email protected]>
7 # Copyright: (c) 2025, Shreyas Srish (@shrsr) <[email protected]>
8 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
9
10 from __future__ import absolute_import, division, print_function
11
12 __metaclass__ = type
13
14 ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "certified"}
15
16 DOCUMENTATION = r"""
17 ---
18 module: aci_tenant_action_rule_profile
19 short_description: Manage action rule profiles (rtctrl:AttrP)
20 description:
21 - Manage action rule profiles on Cisco ACI fabrics.
22 options:
23 tenant:
24 description:
25 - The name of the tenant.
26 type: str
27 aliases: [ tenant_name ]
28 action_rule:
29 description:
30 - The name of the action rule profile.
31 type: str
32 aliases: [action_rule_name, name ]
33 set_community:
34 description:
35 - The set action rule based on communities.
36 - To delete this attribute, pass an empty dictionary.
37 type: dict
38 suboptions:
39 community:
40 description:
41 - The community value.
42 type: str
43 criteria:
44 description:
45 - The community criteria.
46 - The option to append or replace the community value.
47 type: str
48 choices: [ append, replace, none ]
49 set_dampening:
50 description:
51 - The set action rule based on dampening.
52 - To delete this attribute, pass an empty dictionary.
53 type: dict
54 suboptions:
55 half_life:
56 description:
57 - The half life value (minutes).
58 type: int
59 max_suppress_time:
60 description:
61 - The maximum suppress time value (minutes).
62 type: int
63 reuse:
64 description:
65 - The reuse limit value.
66 type: int
67 suppress:
68 description:
69 - The suppress limit value.
70 type: int
71 set_next_hop:
72 description:
73 - The set action rule based on the next hop address.
74 - To delete this attribute, pass an empty string.
75 type: str
76 next_hop_propagation:
77 description:
78 - The set action rule based on nexthop unchanged configuration.
79 - Can not be configured along with C(set_route_tag).
80 - Can not be configured for APIC version 4.2 and prior.
81 - The APIC defaults to C(false) when unset.
82 type: bool
83 multipath:
84 description:
85 - Set action rule based on set redistribute multipath configuration.
86 - Can not be configured along with C(set_route_tag).
87 - Can not be configured for APIC version 4.2 and prior.
88 - The APIC defaults to C(false) when unset.
89 type: bool
90 set_preference:
91 description:
92 - The set action rule based on preference.
93 - To delete this attribute, pass an empty string.
94 type: str
95 set_metric:
96 description:
97 - The set action rule based on metric.
98 - To delete this attribute, pass an empty string.
99 type: str
100 set_metric_type:
101 description:
102 - The set action rule based on a metric type.
103 - To delete this attribute, pass an empty string.
104 type: str
105 choices: [ ospf_type_1, ospf_type_2, "" ]
106 set_route_tag:
107 description:
108 - The set action rule based on route tag.
109 - Can not be configured along with C(next_hop_propagation) and C(multipath).
110 - To delete this attribute, pass an empty string.
111 type: str
112 set_weight:
113 description:
114 - The set action rule based on weight.
115 - To delete this attribute, pass an empty string.
116 type: str
117 set_communities:
118 description:
119 - List of additional communities to add to the action rule profile using the append criteria.
120 - Providing an empty list O(set_communities=[]) will remove all communities.
121 - This is only supported in Cisco ACI Release 6.0(2) and higher.
122 type: list
123 elements: dict
124 suboptions:
125 community:
126 description:
127 - The community value (e.g., no-advertise, no-export, or regular:as2-nn2:4:15).
128 type: str
129 required: true
130 description:
131 description:
132 - Description for the community.
133 type: str
134 aliases: [ descr ]
135 set_as_path:
136 description:
137 - List of Autonomous System (AS) path prepend configurations.
138 - Providing an empty list O(set_as_path=[]) will remove all AS path configurations.
139 - This is only supported in Cisco ACI Release 6.0(2) and higher.
140 type: list
141 elements: dict
142 suboptions:
143 criteria:
144 description:
145 - The AS path criteria.
146 type: str
147 choices: [ prepend, prepend-last-as ]
148 last_num:
149 description:
150 - Number of times to prepend the last AS.
151 - Only applicable when criteria is prepend-last-as.
152 type: int
153 asns:
154 description:
155 - List of ASNs to prepend.
156 - Only applicable when criteria is prepend.
157 type: list
158 elements: dict
159 suboptions:
160 asn:
161 description:
162 - The ASN to prepend.
163 type: str
164 required: true
165 order:
166 description:
167 - The order of the ASN in the prepend list.
168 type: int
169 required: true
170 set_policy_tag:
171 description:
172 - The set action rule based on policy tag (External EPG or ESG).
173 - Providing an empty dictionary O(set_policy_tag={}) will remove this attribute.
174 - Either External EPG (l3out and external_epg) or ESG (ap and esg) must be configured, but not both.
175 - This is only supported in Cisco ACI Release 6.0(2) and higher.
176 type: dict
177 suboptions:
178 l3out:
179 description:
180 - The name of the L3Out.
181 - Required together with C(external_epg).
182 - Mutually exclusive with C(ap) and C(esg).
183 type: str
184 external_epg:
185 description:
186 - The name of the External EPG.
187 - Required together with C(l3out).
188 - Mutually exclusive with C(ap) and C(esg).
189 type: str
190 aliases: [ extepg, inst_p ]
191 ap:
192 description:
193 - The name of the Application Profile.
194 - Required together with C(esg).
195 - Mutually exclusive with C(l3out) and C(external_epg).
196 type: str
197 aliases: [ app_profile ]
198 esg:
199 description:
200 - The name of the Endpoint Security Group (ESG).
201 - Required together with C(ap).
202 - Mutually exclusive with C(l3out) and C(external_epg).
203 type: str
204 description:
205 description:
206 - The description for the action rule profile.
207 type: str
208 aliases: [ descr ]
209 state:
210 description:
211 - Use C(present) or C(absent) for adding or removing.
212 - Use C(query) for listing an object or multiple objects.
213 type: str
214 choices: [ absent, present, query ]
215 default: present
216 name_alias:
217 description:
218 - The alias for the current object. This relates to the nameAlias field in ACI.
219 type: str
220 extends_documentation_fragment:
221 - cisco.aci.aci
222 - cisco.aci.annotation
223
224 notes:
225 - The C(tenant) used must exist before using this module in your playbook.
226 The M(cisco.aci.aci_tenant) module can be used for this.
227 seealso:
228 - module: cisco.aci.aci_tenant
229 - name: APIC Management Information Model reference
230 description: More information about the internal APIC class B(rtctrl:AttrP).
231 link: https://developer.cisco.com/docs/apic-mim-ref/
232 author:
233 - Dag Wieers (@dagwieers)
234 - Tim Cragg (@timcragg)
235 - Gaspard Micol (@gmicol)
236 - Shreyas Srish (@shrsr)
237 """
238
239 EXAMPLES = r"""
240 - name: Create a action rule profile (with External EPG policy tag)
241 cisco.aci.aci_tenant_action_rule_profile:
242 host: apic
243 username: admin
244 password: SomeSecretPassword
245 action_rule: my_action_rule
246 tenant: prod
247 set_preference: 100
248 set_weight: 100
249 set_metric: 100
250 set_metric_type: ospf_type_1
251 set_next_hop: 1.1.1.1
252 next_hop_propagation: true
253 multipath: true
254 set_community:
255 community: no-advertise
256 criteria: replace
257 set_dampening:
258 half_life: 10
259 reuse: 1
260 suppress: 10
261 max_suppress_time: 100
262 set_communities:
263 - community: no-advertise
264 description: test
265 - community: no-export
266 description: test2
267 set_as_path:
268 - criteria: prepend
269 asns:
270 - asn: "65001"
271 order: 0
272 - asn: "65002"
273 order: 1
274 - criteria: prepend-last-as
275 last_num: 4
276 set_policy_tag:
277 l3out: test
278 external_epg: test
279 state: present
280 delegate_to: localhost
281
282 - name: Create a action rule profile (with ESG policy tag)
283 cisco.aci.aci_tenant_action_rule_profile:
284 host: apic
285 username: admin
286 password: SomeSecretPassword
287 action_rule: my_action_rule
288 tenant: Test
289 set_communities:
290 - community: no-advertise
291 description: test
292 - community: no-export
293 description: test2
294 set_as_path:
295 - criteria: prepend
296 asns:
297 - asn: "65001"
298 order: 0
299 - asn: "65002"
300 order: 1
301 - criteria: prepend-last-as
302 last_num: 4
303 set_policy_tag:
304 ap: ap
305 esg: test
306 state: present
307 delegate_to: localhost
308
309 - name: Delete action rule profile's children
310 cisco.aci.aci_tenant_action_rule_profile:
311 host: apic
312 username: admin
313 password: SomeSecretPassword
314 action_rule: my_action_rule
315 tenant: prod
316 set_preference: ""
317 set_weight: ""
318 set_metric: ""
319 set_metric_type: ""
320 set_next_hop: ""
321 next_hop_propagation: false
322 multipath: false
323 set_community: {}
324 set_dampening: {}
325 set_communities: []
326 set_as_path: []
327 set_policy_tag: {}
328 state: present
329 delegate_to: localhost
330
331 - name: Delete an action rule profile
332 cisco.aci.aci_tenant_action_rule_profile:
333 host: apic
334 username: admin
335 password: SomeSecretPassword
336 action_rule: my_action_rule
337 tenant: prod
338 state: absent
339 delegate_to: localhost
340
341 - name: Query all action rule profiles
342 cisco.aci.aci_tenant_action_rule_profile:
343 host: apic
344 username: admin
345 password: SomeSecretPassword
346 state: query
347 delegate_to: localhost
348 register: query_result
349
350 - name: Query a specific action rule profile
351 cisco.aci.aci_tenant_action_rule_profile:
352 host: apic
353 username: admin
354 password: SomeSecretPassword
355 action_rule: my_action_rule
356 tenant: prod
357 state: query
358 delegate_to: localhost
359 register: query_result
360 """
361
362 RETURN = r"""
363 current:
364 description: The existing configuration from the APIC after the module has finished
365 returned: success
366 type: list
367 sample:
368 [
369 {
370 "fvTenant": {
371 "attributes": {
372 "descr": "Production environment",
373 "dn": "uni/tn-production",
374 "name": "production",
375 "nameAlias": "",
376 "ownerKey": "",
377 "ownerTag": ""
378 }
379 }
380 }
381 ]
382 error:
383 description: The error information as returned from the APIC
384 returned: failure
385 type: dict
386 sample:
387 {
388 "code": "122",
389 "text": "unknown managed object class foo"
390 }
391 raw:
392 description: The raw output returned by the APIC REST API (xml or json)
393 returned: parse error
394 type: str
395 sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class foo"/></imdata>'
396 sent:
397 description: The actual/minimal configuration pushed to the APIC
398 returned: info
399 type: list
400 sample:
401 {
402 "fvTenant": {
403 "attributes": {
404 "descr": "Production environment"
405 }
406 }
407 }
408 previous:
409 description: The original configuration from the APIC before the module has started
410 returned: info
411 type: list
412 sample:
413 [
414 {
415 "fvTenant": {
416 "attributes": {
417 "descr": "Production",
418 "dn": "uni/tn-production",
419 "name": "production",
420 "nameAlias": "",
421 "ownerKey": "",
422 "ownerTag": ""
423 }
424 }
425 }
426 ]
427 proposed:
428 description: The assembled configuration from the user-provided parameters
429 returned: info
430 type: dict
431 sample:
432 {
433 "fvTenant": {
434 "attributes": {
435 "descr": "Production environment",
436 "name": "production"
437 }
438 }
439 }
440 filter_string:
441 description: The filter string used for the request
442 returned: failure or debug
443 type: str
444 sample: ?rsp-prop-include=config-only
445 method:
446 description: The HTTP method used for the request to the APIC
447 returned: failure or debug
448 type: str
449 sample: POST
450 response:
451 description: The HTTP response from the APIC
452 returned: failure or debug
453 type: str
454 sample: OK (30 bytes)
455 status:
456 description: The HTTP status from the APIC
457 returned: failure or debug
458 type: int
459 sample: 200
460 url:
461 description: The HTTP url used for the request to the APIC
462 returned: failure or debug
463 type: str
464 sample: https://10.11.12.13/api/mo/uni/tn-production.json
465 """
466
467 from ansible.module_utils.basic import AnsibleModule
468 from ansible_collections.cisco.aci.plugins.module_utils.aci import (
469 ACIModule,
470 aci_argument_spec,
471 aci_annotation_spec,
472 action_rule_set_comm_spec,
473 action_rule_set_dampening_spec,
474 )
475 from ansible_collections.cisco.aci.plugins.module_utils.constants import MATCH_ACTION_RULE_SET_METRIC_TYPE_MAPPING
476
477
478 def main():
479 argument_spec = aci_argument_spec()
480 argument_spec.update(aci_annotation_spec())
481 argument_spec.update(
482 action_rule=dict(type="str", aliases=["action_rule_name", "name"]), # Not required for querying all objects
483 tenant=dict(type="str", aliases=["tenant_name"]), # Not required for querying all objects
484 set_community=dict(type="dict", options=action_rule_set_comm_spec()),
485 set_dampening=dict(type="dict", options=action_rule_set_dampening_spec()),
486 set_next_hop=dict(type="str"),
487 next_hop_propagation=dict(type="bool"),
488 multipath=dict(type="bool"),
489 set_preference=dict(type="str"),
490 set_metric=dict(type="str"),
491 set_metric_type=dict(type="str", choices=["ospf_type_1", "ospf_type_2", ""]),
492 set_route_tag=dict(type="str"),
493 set_weight=dict(type="str"),
494 set_communities=dict(
495 type="list",
496 elements="dict",
497 options=dict(
498 community=dict(type="str", required=True),
499 description=dict(type="str", aliases=["descr"]),
500 ),
501 ),
502 set_as_path=dict(
503 type="list",
504 elements="dict",
505 options=dict(
506 criteria=dict(type="str", choices=["prepend", "prepend-last-as"]),
507 last_num=dict(type="int"),
508 asns=dict(
509 type="list",
510 elements="dict",
511 options=dict(
512 asn=dict(type="str", required=True),
513 order=dict(type="int", required=True),
514 ),
515 ),
516 ),
517 ),
518 set_policy_tag=dict(
519 type="dict",
520 options=dict(
521 l3out=dict(type="str"),
522 external_epg=dict(type="str", aliases=["extepg", "inst_p"]),
523 ap=dict(type="str", aliases=["app_profile"]),
524 esg=dict(type="str"),
525 ),
526 mutually_exclusive=[
527 ["l3out", "ap"],
528 ["l3out", "esg"],
529 ["external_epg", "ap"],
530 ["external_epg", "esg"],
531 ],
532 required_together=[
533 ["l3out", "external_epg"],
534 ["ap", "esg"],
535 ],
536 ),
537 description=dict(type="str", aliases=["descr"]),
538 state=dict(type="str", default="present", choices=["absent", "present", "query"]),
539 name_alias=dict(type="str"),
540 )
541
542 module = AnsibleModule(
543 argument_spec=argument_spec,
544 supports_check_mode=True,
545 required_if=[
546 ["state", "absent", ["action_rule", "tenant"]],
547 ["state", "present", ["action_rule", "tenant"]],
548 ],
549 )
550
551 action_rule = module.params.get("action_rule")
552 description = module.params.get("description")
553 state = module.params.get("state")
554 tenant = module.params.get("tenant")
555 name_alias = module.params.get("name_alias")
556
557 aci = ACIModule(module)
558
559 # This dict contains the name of the child classes as well as the corresping attribute input (and attribute name if the input is a string)
560 # this dict is deviating from normal child classes list structure in order to determine which child classes should be created, modified, deleted or ignored.
561 child_classes = dict(
562 rtctrlSetComm=dict(attribute_input=module.params.get("set_community")),
563 rtctrlSetDamp=dict(attribute_input=module.params.get("set_dampening")),
564 rtctrlSetNh=dict(attribute_input=module.params.get("set_next_hop"), attribute_name="addr"),
565 rtctrlSetPref=dict(attribute_input=module.params.get("set_preference"), attribute_name="localPref"),
566 rtctrlSetRtMetric=dict(attribute_input=module.params.get("set_metric"), attribute_name="metric"),
567 rtctrlSetRtMetricType=dict(
568 attribute_input=MATCH_ACTION_RULE_SET_METRIC_TYPE_MAPPING.get(module.params.get("set_metric_type")), attribute_name="metricType"
569 ),
570 rtctrlSetTag=dict(attribute_input=module.params.get("set_route_tag"), attribute_name="tag"),
571 rtctrlSetWeight=dict(attribute_input=module.params.get("set_weight"), attribute_name="weight"),
572 )
573
574 # This condition deal with child classes which do not exist in APIC version 4.2 and prior.
575 additional_child_classes = dict(
576 rtctrlSetNhUnchanged=dict(attribute_input=module.params.get("next_hop_propagation")),
577 rtctrlSetRedistMultipath=dict(attribute_input=module.params.get("multipath")),
578 )
579 for class_name, attribute in additional_child_classes.items():
580 if attribute.get("attribute_input") is not None:
581 child_classes[class_name] = attribute
582
583 # Add new child classes which do not exist in APIC version 5.8/6.0 and prior for list-based configurations
584 list_child_classes = []
585 if module.params.get("set_communities") is not None:
586 list_child_classes.append("rtctrlSetAddComm")
587 if module.params.get("set_as_path") is not None:
588 list_child_classes.append("rtctrlSetASPath")
589 if module.params.get("set_policy_tag") is not None:
590 list_child_classes.append("rtctrlSetPolicyTag")
591
592 aci.construct_url(
593 root_class=dict(
594 aci_class="fvTenant",
595 aci_rn="tn-{0}".format(tenant),
596 module_object=tenant,
597 target_filter={"name": tenant},
598 ),
599 subclass_1=dict(
600 aci_class="rtctrlAttrP",
601 aci_rn="attr-{0}".format(action_rule),
602 module_object=action_rule,
603 target_filter={"name": action_rule},
604 ),
605 child_classes=list(child_classes.keys()) + list_child_classes,
606 )
607
608 aci.get_existing()
609
610 if state == "present":
611 child_configs = []
612
613 # Process existing single-value child classes
614 for class_name, attribute in child_classes.items():
615 attribute_input = attribute.get("attribute_input")
616 # This condition enables to user to keep its previous configurations if they are not passing anything in the payload.
617 if attribute_input is not None:
618 # This condition checks if the attribute input is a dict and checks if all of its values are None (stored as a boolean in only_none).
619 only_none = False
620 if isinstance(attribute_input, dict):
621 only_none = all(value is None for value in attribute_input.values())
622 # This condition checks if the child object needs to be deleted depending on the type of the corresponding attribute input (bool, str, dict).
623 if (attribute_input == "" or attribute_input is False or only_none) and isinstance(aci.existing, list) and len(aci.existing) > 0:
624 for child in aci.existing[0].get("rtctrlAttrP", {}).get("children", {}):
625 if child.get(class_name):
626 child_configs.append(
627 {
628 class_name: dict(
629 attributes=dict(status="deleted"),
630 ),
631 }
632 )
633 # This condition checks if the child object needs to be modified or created depending on the type of the corresponding attribute input.
634 elif attribute_input != "" or attribute_input is True or attribute_input != {}:
635 if class_name == "rtctrlSetComm" and isinstance(attribute_input, dict):
636 child_configs.append(
637 {
638 class_name: dict(
639 attributes=dict(
640 community=attribute_input.get("community"),
641 setCriteria=attribute_input.get("criteria"),
642 ),
643 )
644 }
645 )
646 elif class_name == "rtctrlSetDamp" and isinstance(attribute_input, dict):
647 child_configs.append(
648 {
649 class_name: dict(
650 attributes=dict(
651 halfLife=attribute_input.get("half_life"),
652 maxSuppressTime=attribute_input.get("max_suppress_time"),
653 reuse=attribute_input.get("reuse"),
654 suppress=attribute_input.get("suppress"),
655 ),
656 )
657 }
658 )
659 elif class_name in ["rtctrlSetNhUnchanged", "rtctrlSetRedistMultipath"]:
660 child_configs.append({class_name: dict(attributes=dict(descr=""))})
661 else:
662 child_configs.append({class_name: dict(attributes={attribute.get("attribute_name"): attribute_input})})
663
664 # Process rtctrlSetAddComm (list of communities)
665 set_communities = module.params.get("set_communities")
666 if set_communities is not None:
667 existing_communities = []
668
669 # Get existing communities from APIC
670 if isinstance(aci.existing, list) and len(aci.existing) > 0:
671 for child in aci.existing[0].get("rtctrlAttrP", {}).get("children", []):
672 if child.get("rtctrlSetAddComm"):
673 existing_communities.append(child["rtctrlSetAddComm"])
674
675 # Get list of communities from user input
676 new_communities = [comm.get("community") for comm in set_communities]
677
678 # Delete communities that are no longer in the new list
679 for community_obj in existing_communities:
680 existing_community = community_obj.get("attributes", {}).get("community")
681 if existing_community and existing_community not in new_communities:
682 child_configs.append(
683 {
684 "rtctrlSetAddComm": dict(
685 attributes=dict(
686 community=existing_community,
687 status="deleted",
688 ),
689 )
690 }
691 )
692
693 # Add new communities
694 for comm in set_communities:
695 child_configs.append(
696 {
697 "rtctrlSetAddComm": dict(
698 attributes=dict(
699 community=comm.get("community"),
700 descr=comm.get("description"),
701 ),
702 )
703 }
704 )
705
706 # Process rtctrlSetASPath (list of AS path configurations)
707 # Process rtctrlSetASPath (list of AS path configurations)
708 set_as_path = module.params.get("set_as_path")
709 if set_as_path is not None:
710 existing_as_paths = []
711
712 # Get existing AS paths from APIC
713 if isinstance(aci.existing, list) and len(aci.existing) > 0:
714 for child in aci.existing[0].get("rtctrlAttrP", {}).get("children", []):
715 if child.get("rtctrlSetASPath"):
716 existing_as_paths.append(child["rtctrlSetASPath"])
717
718 # Organize AS path configurations
719 prepend_config = None
720 prepend_last_as_config = None
721
722 for as_path_config in set_as_path:
723 criteria = as_path_config.get("criteria")
724
725 if criteria == "prepend-last-as":
726 prepend_last_as_config = as_path_config
727 elif criteria == "prepend":
728 prepend_config = as_path_config
729
730 # Build list of criteria identifiers that should exist in new config
731 new_criteria = []
732 if prepend_config:
733 new_criteria.append("prepend")
734 if prepend_last_as_config:
735 new_criteria.append("prepend-last-as")
736
737 # Delete AS paths that are no longer in the new list
738 for as_path_obj in existing_as_paths:
739 existing_criteria = as_path_obj.get("attributes", {}).get("criteria", "")
740
741 if existing_criteria not in new_criteria:
742 # Build deletion config based on criteria
743 if existing_criteria == "prepend-last-as":
744 child_configs.append(
745 {
746 "rtctrlSetASPath": dict(
747 attributes=dict(
748 criteria="prepend-last-as",
749 status="deleted",
750 ),
751 )
752 }
753 )
754 else:
755 child_configs.append(
756 {
757 "rtctrlSetASPath": dict(
758 attributes=dict(
759 criteria="prepend",
760 status="deleted",
761 ),
762 )
763 }
764 )
765
766 # Add/update prepend configuration
767 if prepend_config:
768 asns_list = prepend_config.get("asns", [])
769
770 # Get existing ASNs for prepend (if it exists)
771 existing_prepend_asns = []
772 for as_path_obj in existing_as_paths:
773 existing_criteria = as_path_obj.get("attributes", {}).get("criteria")
774
775 if existing_criteria == "prepend":
776 # Get existing ASN children
777 existing_asn_children = as_path_obj.get("children", [])
778
779 for child in existing_asn_children:
780 if child.get("rtctrlSetASPathASN"):
781 asn = child["rtctrlSetASPathASN"]["attributes"].get("asn")
782 order = child["rtctrlSetASPathASN"]["attributes"].get("order")
783 if asn and order is not None:
784 existing_prepend_asns.append({"asn": str(asn), "order": str(order)})
785 break
786
787 # Build list of new ASN identifiers
788 new_asn_identifiers = []
789 for idx, asn_config in enumerate(asns_list):
790 asn = str(asn_config.get("asn"))
791 order = asn_config.get("order")
792 order = str(order)
793 new_asn_identifiers.append({"asn": asn, "order": order})
794
795 # Delete ASNs that are no longer in the new list
796 for existing_asn in existing_prepend_asns:
797 asn_found = False
798 for new_asn in new_asn_identifiers:
799 if existing_asn["asn"] == new_asn["asn"] and existing_asn["order"] == new_asn["order"]:
800 asn_found = True
801 break
802
803 if not asn_found:
804 # Delete this ASN
805 child_configs.append(
806 {
807 "rtctrlSetASPath": dict(
808 attributes=dict(criteria="prepend"),
809 children=[
810 {
811 "rtctrlSetASPathASN": dict(
812 attributes=dict(
813 asn=existing_asn["asn"],
814 order=existing_asn["order"],
815 status="deleted",
816 ),
817 )
818 }
819 ],
820 )
821 }
822 )
823
824 # Add new ASNs
825 asn_children = []
826 for idx, asn_config in enumerate(asns_list):
827 asn = asn_config.get("asn")
828 order = asn_config.get("order")
829
830 asn_children.append(
831 {
832 "rtctrlSetASPathASN": dict(
833 attributes=dict(
834 asn=str(asn),
835 order=str(order),
836 ),
837 children=[],
838 )
839 }
840 )
841
842 as_path_attrs = dict(criteria="prepend")
843 child_configs.append({"rtctrlSetASPath": dict(attributes=as_path_attrs, children=asn_children)})
844
845 # Add/update prepend-last-as configuration
846 if prepend_last_as_config:
847 last_num = prepend_last_as_config.get("last_num")
848
849 as_path_attrs = dict(
850 criteria="prepend-last-as",
851 lastnum=str(last_num),
852 )
853 child_configs.append({"rtctrlSetASPath": dict(attributes=as_path_attrs, children=[])})
854
855 # Process rtctrlSetPolicyTag (External EPG or ESG reference)
856 # Only one type can be configured at a time (mutually exclusive)
857 set_policy_tag = module.params.get("set_policy_tag")
858 if set_policy_tag is not None:
859 existing_policy_tags = []
860
861 # Get existing policy tags from APIC
862 if isinstance(aci.existing, list) and len(aci.existing) > 0:
863 for child in aci.existing[0].get("rtctrlAttrP", {}).get("children", []):
864 if child.get("rtctrlSetPolicyTag"):
865 existing_policy_tags.append(child["rtctrlSetPolicyTag"])
866
867 # Check if all values are None (empty dict behavior)
868 all_none = all(value is None for value in set_policy_tag.values()) if set_policy_tag else True
869 # If empty dict is passed (all values are None), delete all existing policy tags
870 if all_none:
871 if existing_policy_tags:
872 child_configs.append(
873 {
874 "rtctrlSetPolicyTag": dict(
875 attributes=dict(status="deleted"),
876 )
877 }
878 )
879 else:
880 # Determine which type is being configured
881 l3out = set_policy_tag.get("l3out")
882 external_epg = set_policy_tag.get("external_epg")
883 ap = set_policy_tag.get("ap")
884 esg = set_policy_tag.get("esg")
885
886 new_target_dn = None
887 new_relationship_class = None
888
889 # External EPG configuration
890 if l3out and external_epg:
891 new_target_dn = "uni/tn-{0}/out-{1}/instP-{2}".format(tenant, l3out, external_epg)
892 new_relationship_class = "rtctrlRsSetPolicyTagToInstP"
893 # ESG configuration
894 elif ap and esg:
895 new_target_dn = "uni/tn-{0}/ap-{1}/esg-{2}".format(tenant, ap, esg)
896 new_relationship_class = "rtctrlRsSetPolicyTagToESg"
897
898 # If we have valid new configuration
899 if new_target_dn and new_relationship_class:
900 needs_update = False
901
902 # Check if existing policy tag matches the new configuration
903 if existing_policy_tags:
904 existing_policy_tag = existing_policy_tags[0]
905 existing_children = existing_policy_tag.get("children", [])
906
907 # Check if the same relationship with same target exists
908 existing_match = False
909 for rel_child in existing_children:
910 if rel_child.get(new_relationship_class):
911 existing_target_dn = rel_child[new_relationship_class]["attributes"].get("tDn")
912 if existing_target_dn == new_target_dn:
913 existing_match = True
914 break
915
916 # If existing doesn't match, we need to update
917 if not existing_match:
918 needs_update = True
919 aci.api_call(
920 "DELETE",
921 "{0}/api/mo/uni/tn-{1}/attr-{2}/sptag.json".format(aci.base_url, tenant, action_rule),
922 )
923 else:
924 # No existing policy tag, need to create
925 needs_update = True
926
927 # Add new policy tag configuration if update is needed
928 if needs_update:
929 policy_tag_children = [
930 {
931 new_relationship_class: dict(
932 attributes=dict(tDn=new_target_dn),
933 children=[],
934 )
935 }
936 ]
937 child_configs.append(
938 {
939 "rtctrlSetPolicyTag": dict(
940 attributes=dict(),
941 children=policy_tag_children,
942 )
943 }
944 )
945
946 aci.payload(
947 aci_class="rtctrlAttrP",
948 class_config=dict(
949 name=action_rule,
950 descr=description,
951 nameAlias=name_alias,
952 ),
953 child_configs=child_configs,
954 )
955
956 aci.get_diff(aci_class="rtctrlAttrP")
957
958 aci.post_config()
959
960 elif state == "absent":
961 aci.delete_config()
962
963 aci.exit_json()
964
965
966 if __name__ == "__main__":
967 main()