summaryrefslogtreecommitdiffstats
path: root/ansible_collections/cisco/aci/plugins/modules/aci_vrf_multicast.py
blob: 4d380990244f6ec4cf940a7537cb3ba5b12cf279 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
#!/usr/bin/python
# -*- coding: utf-8 -*-

# Copyright: (c) 2023, Tim Cragg (@timcragg)
# Copyright: (c) 2023, Akini Ross (@akinross)
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import absolute_import, division, print_function

__metaclass__ = type

ANSIBLE_METADATA = {"metadata_version": "1.1", "status": ["preview"], "supported_by": "community"}

DOCUMENTATION = r"""
---
module: aci_vrf_multicast
short_description: Manage VRF Multicast objects (pim:CtxP)
description:
- Manage VRF Multicast objects on Cisco ACI fabrics.
- Creating I(state=present) enables Protocol Independent Multicast (PIM) on a VRF
- Deleting I(state=absent) disables Protocol Independent Multicast (PIM) on a VRF.
options:
  tenant:
    description:
    - The name of an existing tenant.
    type: str
    aliases: [ tenant_name ]
  vrf:
    description:
    - The name of an existing VRF.
    type: str
    aliases: [ vrf_name ]
  pim_setting:
    description: Configuration container for Protocol Independent Multicast (PIM) settings.
    type: dict
    suboptions:
      mtu:
        description:
        - The MTU size supported for multicast.
        - The APIC defaults to C(1500) when unset during creation.
        type: int
      control_state:
        description:
        - The action(s) to take when a loop is detected.
        - Specify C([]) to remove the control state configuration.
        type: list
        elements: str
        aliases: [ control, ctrl ]
        choices: [ fast, strict ]
  resource_policy:
    description: Configuration container for Protocol Independent Multicast (PIM) resource policy.
    type: dict
    suboptions:
      maximum_limit:
        description:
        - The Max Multicast Entries.
        - The APIC defaults to C(unlimited) when unset during creation.
        - Specify C(0) to reset to C(unlimited).
        type: int
        aliases: [ max ]
      reserved_multicast_entries:
        description:
        - The Reserved Multicast Entries.
        - The APIC defaults to C(undefined) when unset during creation.
        - Required when C(reserved_route_map) is provided.
        type: int
        aliases: [ rsvd ]
      reserved_route_map:
        description:
        - The DN of the Route Map.
        - Specify C("") to remove the Route Map configuration.
        - Required when C(reserved_multicast_entries) is provided.
        type: str
        aliases: [ route_map, route_map_dn ]
  any_source_multicast:
    description: Configuration container for Protocol Independent Multicast (PIM) Any Source Multicast (ASM) settings.
    type: dict
    aliases: [ asm, any_source ]
    suboptions:
      shared_range_route_map:
        description:
        - The DN of the Route Map.
        - Specify C("") to remove the Route Map configuration.
        type: str
        aliases: [ shared_range_policy ]
      source_group_expiry_route_map:
        description:
        - The DN of the Route Map.
        - Specify C("") to remove the Route Map configuration.
        type: str
        aliases: [ sg_expiry_route_map ]
      expiry:
        description:
        - The expiry time in seconds.
        - The APIC defaults to C(default-timeout) when unset during creation.
        - Specify C(0) to reset to C(default-timeout).
        type: int
        aliases: [ expiry_seconds ]
      max_rate:
        description:
        - The maximum rate per second.
        - The APIC defaults to C(65535) when unset during creation.
        type: int
        aliases: [ max_rate_per_second ]
      source_ip:
        description:
        - The source IP address.
        type: str
        aliases: [ source, source_ip_address ]
  source_specific_multicast:
    description: Configuration container for Protocol Independent Multicast (PIM) Source Specific Multicast (SSM) settings.
    type: dict
    aliases: [ ssm, specific_source ]
    suboptions:
      group_range_route_map:
        description:
        - The DN of the Route Map.
        - Specify C("") to remove the Route Map configuration.
        type: str
        aliases: [ group_range_policy ]
  bootstrap_router:
    description: Configuration container for Protocol Independent Multicast (PIM) Bootstrap Router (BSR) settings.
    type: dict
    aliases: [ bsr, bootstrap ]
    suboptions:
      bsr_filter:
        description:
        - The DN of the Route Map.
        - Specify C("") to remove the Route Map configuration.
        type: str
        aliases: [ filter, route_map, route_map_dn ]
      rp_updates:
        description:
        - The control state of the Bootstrap Router (BSR) policy.
        - Specify C([]) to remove the control state configuration.
        type: list
        elements: str
        aliases: [ control, ctrl ]
        choices: [ forward, listen ]
  auto_rp:
    description: Configuration container for Protocol Independent Multicast (PIM) Auto-Rendezvous Point (Auto-RP) settings.
    type: dict
    aliases: [ auto ]
    suboptions:
      ma_filter:
        description:
        - The DN of the Route Map.
        - Specify C("") to remove the Route Map configuration.
        type: str
        aliases: [ filter, route_map, route_map_dn ]
      rp_updates:
        description:
        - The control state of the Auto-Rendezvous Point (Auto-RP) policy.
        - Specify C([]) to remove the control state configuration.
        type: list
        elements: str
        aliases: [ control, ctrl ]
        choices: [ forward, listen ]
  state:
    description:
    - Use C(present) or C(absent) for adding or removing.
    - Use C(query) for listing an object or multiple objects.
    type: str
    choices: [ absent, present, query ]
    default: present
extends_documentation_fragment:
- cisco.aci.aci
- cisco.aci.annotation
- cisco.aci.owner

notes:
- The I(tenant) and I(vrf) must exist before using this module in your playbook.
  The M(cisco.aci.aci_tenant) and M(cisco.aci.aci_vrf) modules can be used for this.
seealso:
- name: APIC Management Information Model reference
  description: More information about the internal APIC class B(pim:CtxP).
  link: https://developer.cisco.com/docs/apic-mim-ref/
author:
- Tim Cragg (@timcragg)
- Akini Ross (@akinross)
"""

EXAMPLES = r"""
- name: Enable Multicast on a VRF
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    tenant: ansible_tenant
    vrf: ansible_vrf
    state: present
  delegate_to: localhost

- name: Change Multicast PIM Settings on a VRF
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    tenant: ansible_tenant
    vrf: ansible_vrf
    pim_setting:
      mtu: 2000
      control_state: [ fast, strict ]
    state: present
  delegate_to: localhost

- name: Change Multicast Resource Policy on a VRF
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    tenant: ansible_tenant
    vrf: ansible_vrf
    resource_policy:
      maximum_limit: 100
      reserved_multicast_entries: 20
      reserved_route_map: uni/tn-ansible_test/rtmap-ansible_test
    state: present
  delegate_to: localhost

- name: Remove Route-Map from Multicast Resource Policy on a VRF
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    tenant: ansible_tenant
    vrf: ansible_vrf
    resource_policy:
      reserved_route_map: ""
    state: present
  delegate_to: localhost

- name: Change Multicast Any Source Multicast (ASM) Settings on a VRF
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    tenant: ansible_tenant
    vrf: ansible_vrf
    any_source_multicast:
      shared_range_route_map: uni/tn-ansible_test/rtmap-ansible_test
      source_group_expiry_route_map: uni/tn-ansible_test/rtmap-ansible_test
      expiry: 500
      max_rate: 64000
      source_ip: 1.1.1.1
    state: present
  delegate_to: localhost

- name: Change Multicast Source Specific Multicast (SSM) Settings on a VRF
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    tenant: ansible_tenant
    vrf: ansible_vrf
    source_specific_multicast:
      group_range_route_map: uni/tn-ansible_test/rtmap-ansible_test
    state: present
  delegate_to: localhost

- name: Change Multicast Bootstrap Router (BSR) Settings on a VRF
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    tenant: ansible_tenant
    vrf: ansible_vrf
    bootstrap_router:
      bsr_filter: uni/tn-ansible_test/rtmap-ansible_test
      rp_updates: [ forward, listen ]
    state: present
  delegate_to: localhost

- name: Change Multicast Auto-Rendezvous Point (Auto-RP) Settings on a VRF
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    tenant: ansible_tenant
    vrf: ansible_vrf
    auto_rp:
      ma_filter: uni/tn-ansible_test/rtmap-ansible_test
      rp_updates: [ forward, listen ]
    state: present
  delegate_to: localhost

- name: Disable Multicast on a VRF
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    tenant: ansible_tenant
    vrf: ansible_vrf
    state: absent
  delegate_to: localhost

- name: Query Multicast Settings for a VRF
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    tenant: ansible_tenant
    vrf: ansible_vrf
    state: query
  delegate_to: localhost
  register: query_result

- name: Query Multicast Settings for all VRFs
  cisco.aci.aci_vrf_multicast:
    host: apic
    username: admin
    password: SomeSecretePassword
    state: query
  delegate_to: localhost
  register: query_result
"""

RETURN = r"""
   current:
     description: The existing configuration from the APIC after the module has finished
     returned: success
     type: list
     sample:
       [
           {
               "fvTenant": {
                   "attributes": {
                       "descr": "Production environment",
                       "dn": "uni/tn-production",
                       "name": "production",
                       "nameAlias": "",
                       "ownerKey": "",
                       "ownerTag": ""
                   }
               }
           }
       ]
   error:
     description: The error information as returned from the APIC
     returned: failure
     type: dict
     sample:
       {
           "code": "122",
           "text": "unknown managed object class foo"
       }
   raw:
     description: The raw output returned by the APIC REST API (xml or json)
     returned: parse error
     type: str
     sample: '<?xml version="1.0" encoding="UTF-8"?><imdata totalCount="1"><error code="122" text="unknown managed object class "/></imdata>'
   sent:
     description: The actual/minimal configuration pushed to the APIC
     returned: info
     type: list
     sample:
       {
           "fvTenant": {
               "attributes": {
                   "descr": "Production environment"
               }
           }
       }
   previous:
     description: The original configuration from the APIC before the module has started
     returned: info
     type: list
     sample:
       [
           {
               "fvTenant": {
                   "attributes": {
                       "descr": "Production",
                       "dn": "uni/tn-production",
                       "name": "production",
                       "nameAlias": "",
                       "ownerKey": "",
                       "ownerTag": ""
                   }
               }
           }
       ]
   proposed:
     description: The assembled configuration from the user-provided parameters
     returned: info
     type: dict
     sample:
       {
           "fvTenant": {
               "attributes": {
                   "descr": "Production environment",
                   "name": "production"
               }
           }
       }
   filter_string:
     description: The filter string used for the request
     returned: failure or debug
     type: str
     sample: ?rsp-prop-include=config-only
   method:
     description: The HTTP method used for the request to the APIC
     returned: failure or debug
     type: str
     sample: POST
   response:
     description: The HTTP response from the APIC
     returned: failure or debug
     type: str
     sample: OK (30 bytes)
   status:
     description: The HTTP status from the APIC
     returned: failure or debug
     type: int
     sample: 200
   url:
     description: The HTTP url used for the request to the APIC
     returned: failure or debug
     type: str
     sample: https://10.11.12.13/api/mo/uni/tn-production.json
   """

from ansible.module_utils.basic import AnsibleModule
from ansible_collections.cisco.aci.plugins.module_utils.aci import ACIModule, aci_argument_spec, aci_annotation_spec, aci_owner_spec
from ansible_collections.cisco.aci.plugins.module_utils.constants import PIM_SETTING_CONTROL_STATE_MAPPING


def main():
    argument_spec = aci_argument_spec()
    argument_spec.update(aci_annotation_spec())
    argument_spec.update(aci_owner_spec())
    argument_spec.update(
        tenant=dict(type="str", aliases=["tenant_name"]),
        vrf=dict(type="str", aliases=["vrf_name"]),
        pim_setting=dict(
            type="dict",
            options=dict(
                mtu=dict(type="int"),
                control_state=dict(type="list", elements="str", choices=["fast", "strict"], aliases=["control", "ctrl"]),
            ),
        ),
        resource_policy=dict(
            type="dict",
            options=dict(
                maximum_limit=dict(type="int", aliases=["max"]),
                reserved_multicast_entries=dict(type="int", aliases=["rsvd"]),
                reserved_route_map=dict(type="str", aliases=["route_map", "route_map_dn"]),
            ),
        ),
        any_source_multicast=dict(
            type="dict",
            options=dict(
                shared_range_route_map=dict(type="str", aliases=["shared_range_policy"]),
                source_group_expiry_route_map=dict(type="str", aliases=["sg_expiry_route_map"]),
                expiry=(dict(type="int", aliases=["expiry_seconds"])),
                max_rate=(dict(type="int", aliases=["max_rate_per_second"])),
                source_ip=(dict(type="str", aliases=["source", "source_ip_address"])),
            ),
            aliases=["asm", "any_source"],
        ),
        source_specific_multicast=dict(
            type="dict",
            options=dict(
                group_range_route_map=dict(type="str", aliases=["group_range_policy"]),
            ),
            aliases=["ssm", "specific_source"],
        ),
        bootstrap_router=dict(
            type="dict",
            options=dict(
                bsr_filter=dict(type="str", aliases=["filter", "route_map", "route_map_dn"]),
                rp_updates=dict(type="list", elements="str", choices=["forward", "listen"], aliases=["control", "ctrl"]),
            ),
            aliases=["bsr", "bootstrap"],
        ),
        auto_rp=dict(
            type="dict",
            options=dict(
                ma_filter=dict(type="str", aliases=["filter", "route_map", "route_map_dn"]),
                rp_updates=dict(type="list", elements="str", choices=["forward", "listen"], aliases=["control", "ctrl"]),
            ),
            aliases=["auto"],
        ),
        state=dict(type="str", default="present", choices=["absent", "present", "query"]),
    )

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
        required_if=[
            ["state", "absent", ["tenant", "vrf"]],
            ["state", "present", ["tenant", "vrf"]],
        ],
    )

    aci = ACIModule(module)

    tenant = module.params.get("tenant")
    vrf = module.params.get("vrf")
    pim_setting = module.params.get("pim_setting")
    resource_policy = module.params.get("resource_policy")
    any_source_multicast = module.params.get("any_source_multicast")
    source_specific_multicast = module.params.get("source_specific_multicast")
    bootstrap_router = module.params.get("bootstrap_router")
    auto_rp = module.params.get("auto_rp")
    state = module.params.get("state")

    if resource_policy and resource_policy.get("reserved_multicast_entries") and resource_policy.get("reserved_route_map") is None:
        aci.fail_json(msg="parameters are mutually exclusive: reserved_route_map|reserved_multicast_entries")
    elif resource_policy and resource_policy.get("reserved_route_map") and not resource_policy.get("reserved_multicast_entries"):
        aci.fail_json(msg="C(reserved_multicast_entries) must be provided and greater than 0 when C(reserved_route_map) is provided")

    aci.construct_url(
        root_class=dict(
            aci_class="fvTenant",
            aci_rn="tn-{0}".format(tenant),
            module_object=tenant,
            target_filter={"name": tenant},
        ),
        subclass_1=dict(
            aci_class="fvCtx",
            aci_rn="ctx-{0}".format(vrf),
            module_object=vrf,
            target_filter={"name": vrf},
        ),
        subclass_2=dict(
            aci_class="pimCtxP",
            aci_rn="pimctxp",
            target_filter={"name": ""},
        ),
        child_classes=["pimResPol", "pimASMPatPol", "pimSSMPatPol", "pimAutoRPPol", "pimBSRPPol"],
    )

    aci.get_existing()

    if state == "present":
        existing_config = aci.existing[0] if aci.existing else {}
        child_configs = []

        resource_policy_config = dict(pimResPol=dict(attributes=dict(name=""), children=[]))
        if resource_policy:
            max = "unlimited" if resource_policy.get("maximum_limit") == 0 else resource_policy.get("maximum_limit")
            if max is not None:
                resource_policy_config["pimResPol"]["attributes"]["max"] = str(max)

            reserved_route_map = resource_policy.get("reserved_route_map")
            if reserved_route_map is not None:
                existing_rrm = get_child_from_existing_config(existing_config, ["pimCtxP", "pimResPol", "rtdmcRsFilterToRtMapPol"])
                rsvd = resource_policy.get("reserved_multicast_entries")

                if (existing_rrm or reserved_route_map != "") and rsvd:
                    resource_policy_config["pimResPol"]["attributes"]["rsvd"] = str(rsvd)
                elif existing_rrm and reserved_route_map == "":
                    resource_policy_config["pimResPol"]["attributes"]["rsvd"] = "undefined"

                set_route_map_config(
                    existing_config,
                    resource_policy_config["pimResPol"]["children"],
                    ["pimCtxP", "pimResPol", "rtdmcRsFilterToRtMapPol"],
                    reserved_route_map,
                )

        child_configs.append(resource_policy_config)

        any_source_multicast_config = dict(
            pimASMPatPol=dict(
                attributes=dict(name=""),
                children=[
                    dict(pimSharedRangePol=dict(attributes=dict(name=""), children=[])),
                    dict(pimSGRangeExpPol=dict(attributes=dict(name=""), children=[])),
                    dict(pimRegTrPol=dict(attributes=dict(name=""), children=[])),
                ],
            )
        )
        if any_source_multicast:
            if any_source_multicast.get("shared_range_route_map") is not None:
                set_route_map_config(
                    existing_config,
                    any_source_multicast_config["pimASMPatPol"]["children"][0]["pimSharedRangePol"]["children"],
                    ["pimCtxP", "pimASMPatPol", "pimSharedRangePol", "rtdmcRsFilterToRtMapPol"],
                    any_source_multicast.get("shared_range_route_map"),
                )

            if any_source_multicast.get("source_group_expiry_route_map") is not None:
                set_route_map_config(
                    existing_config,
                    any_source_multicast_config["pimASMPatPol"]["children"][1]["pimSGRangeExpPol"]["children"],
                    ["pimCtxP", "pimASMPatPol", "pimSGRangeExpPol", "rtdmcRsFilterToRtMapPol"],
                    any_source_multicast.get("source_group_expiry_route_map"),
                )

            expiry = any_source_multicast.get("expiry")
            if expiry is not None:
                sg_expiry_config = "default-timeout" if any_source_multicast.get("expiry") == 0 else any_source_multicast.get("expiry")
                any_source_multicast_config["pimASMPatPol"]["children"][1]["pimSGRangeExpPol"]["attributes"]["sgExpItvl"] = str(sg_expiry_config)

            if any_source_multicast.get("max_rate") is not None:
                any_source_multicast_config["pimASMPatPol"]["children"][2]["pimRegTrPol"]["attributes"]["maxRate"] = str(any_source_multicast.get("max_rate"))

            if any_source_multicast.get("source_ip") is not None:
                any_source_multicast_config["pimASMPatPol"]["children"][2]["pimRegTrPol"]["attributes"]["srcIp"] = any_source_multicast.get("source_ip")

        child_configs.append(any_source_multicast_config)

        source_specific_multicast_config = dict(
            pimSSMPatPol=dict(
                attributes=dict(name=""),
                children=[
                    dict(pimSSMRangePol=dict(attributes=dict(name=""), children=[])),
                ],
            )
        )
        if source_specific_multicast and source_specific_multicast.get("group_range_route_map") is not None:
            set_route_map_config(
                existing_config,
                source_specific_multicast_config["pimSSMPatPol"]["children"][0]["pimSSMRangePol"]["children"],
                ["pimCtxP", "pimSSMPatPol", "pimSSMRangePol", "rtdmcRsFilterToRtMapPol"],
                source_specific_multicast.get("group_range_route_map"),
            )

        child_configs.append(source_specific_multicast_config)

        if bootstrap_router:
            bsr_config = dict(pimBSRPPol=dict(attributes=dict(name=""), children=[dict(pimBSRFilterPol=dict(attributes=dict(name=""), children=[]))]))
            if bootstrap_router.get("bsr_filter") is not None:
                set_route_map_config(
                    existing_config,
                    bsr_config["pimBSRPPol"]["children"][0]["pimBSRFilterPol"]["children"],
                    ["pimCtxP", "pimBSRPPol", "pimBSRFilterPol", "rtdmcRsFilterToRtMapPol"],
                    bootstrap_router.get("bsr_filter"),
                )

            rp_updates = bootstrap_router.get("rp_updates")
            if rp_updates is not None:
                bsr_config["pimBSRPPol"]["attributes"]["ctrl"] = ",".join(sorted(rp_updates))

            child_configs.append(bsr_config)

        if auto_rp:
            auto_rp_config = dict(pimAutoRPPol=dict(attributes=dict(name=""), children=[dict(pimMAFilterPol=dict(attributes=dict(name=""), children=[]))]))

            if auto_rp.get("ma_filter") is not None:
                set_route_map_config(
                    existing_config,
                    auto_rp_config["pimAutoRPPol"]["children"][0]["pimMAFilterPol"]["children"],
                    ["pimCtxP", "pimAutoRPPol", "pimMAFilterPol", "rtdmcRsFilterToRtMapPol"],
                    auto_rp.get("ma_filter"),
                )

            rp_updates = auto_rp.get("rp_updates")
            if rp_updates is not None:
                auto_rp_config["pimAutoRPPol"]["attributes"]["ctrl"] = ",".join(sorted(rp_updates))

            child_configs.append(auto_rp_config)

        mtu = None
        control_state = None
        if pim_setting:
            mtu = pim_setting.get("mtu")
            control_state = (
                ",".join(sorted([PIM_SETTING_CONTROL_STATE_MAPPING.get(v) for v in pim_setting.get("control_state")]))
                if pim_setting.get("control_state") is not None
                else None
            )

        aci.payload(
            aci_class="pimCtxP",
            class_config=dict(mtu=mtu, ctrl=control_state),
            child_configs=child_configs,
        )

        aci.get_diff(aci_class="pimCtxP")

        aci.post_config()

    elif state == "absent":
        aci.delete_config()

    aci.exit_json()


def get_child_from_existing_config(config, class_names):
    parent = class_names[0]
    class_names.remove(parent)

    for child in config.get(parent, {}).get("children", []):
        if len(class_names) == 1 and class_names[0] in child.keys():
            return child
        elif child.get(class_names[0], {}).get("children"):
            return get_child_from_existing_config(child, class_names)


def set_route_map_config(existing_config, new_config, class_names, route_map):
    existing_route_map = get_child_from_existing_config(existing_config, class_names)
    if route_map == "" and existing_route_map:
        new_config.append(dict(rtdmcRsFilterToRtMapPol=dict(attributes=dict(tDn=route_map, status="deleted"))))
    elif route_map:
        new_config.append(dict(rtdmcRsFilterToRtMapPol=dict(attributes=dict(tDn=route_map))))


if __name__ == "__main__":
    main()