-
Notifications
You must be signed in to change notification settings - Fork 0
/
6.1.3.txt
4444 lines (4335 loc) · 163 KB
/
6.1.3.txt
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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/plugins/module_utils/network/ios/argspec/bgp_global/bgp_global.py b/plugins/module_utils/network/ios/argspec/bgp_global/bgp_global.py
index 21bb051..6e82c99 100644
--- a/plugins/module_utils/network/ios/argspec/bgp_global/bgp_global.py
+++ b/plugins/module_utils/network/ios/argspec/bgp_global/bgp_global.py
@@ -163,6 +163,20 @@ class Bgp_globalArgs(object): # pylint: disable=R0903
"route_map": {"type": "str"},
},
},
+ "default": {
+ "type": "dict",
+ "apply_defaults": True,
+ "options": {
+ "ipv4_unicast": {"type": "bool", "default": True},
+ "route_target": {
+ "type": "dict",
+ "apply_defaults": True,
+ "options": {
+ "filter": {"type": "bool", "default": True},
+ },
+ },
+ },
+ },
"deterministic_med": {"type": "bool"},
"dmzlink_bw": {"type": "bool"},
"enforce_first_as": {"type": "bool"},
diff --git a/plugins/module_utils/network/ios/argspec/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/ios/argspec/l3_interfaces/l3_interfaces.py
index 4552614..82ae98e 100644
--- a/plugins/module_utils/network/ios/argspec/l3_interfaces/l3_interfaces.py
+++ b/plugins/module_utils/network/ios/argspec/l3_interfaces/l3_interfaces.py
@@ -36,6 +36,8 @@ class L3_interfacesArgs(object): # pylint: disable=R0903
"type": "list",
"elements": "dict",
"options": {
+ "autostate": {"type": "bool"},
+ "mac_address": {"type": "str"},
"name": {"type": "str", "required": True},
"ipv4": {
"type": "list",
@@ -54,6 +56,14 @@ class L3_interfacesArgs(object): # pylint: disable=R0903
},
},
"pool": {"type": "str"},
+ "source_interface": {
+ "type": "dict",
+ "options": {
+ "name": {"type": "str"},
+ "poll": {"type": "bool"},
+ "point_to_point": {"type": "bool"},
+ },
+ },
},
},
"ipv6": {
@@ -72,6 +82,7 @@ class L3_interfacesArgs(object): # pylint: disable=R0903
"rapid_commit": {"type": "bool"},
},
},
+ "enable": {"type": "bool"},
"anycast": {"type": "bool"},
"cga": {"type": "bool"},
"eui": {"type": "bool"},
diff --git a/plugins/module_utils/network/ios/argspec/vlans/vlans.py b/plugins/module_utils/network/ios/argspec/vlans/vlans.py
index 9db593d..65e6318 100644
--- a/plugins/module_utils/network/ios/argspec/vlans/vlans.py
+++ b/plugins/module_utils/network/ios/argspec/vlans/vlans.py
@@ -51,7 +51,10 @@ class VlansArgs(object):
"private_vlan": {
"type": "dict",
"options": {
- "type": {"type": "str", "choices": ["primary", "community", "isolated"]},
+ "type": {
+ "type": "str",
+ "choices": ["primary", "community", "isolated"],
+ },
"associated": {"type": "list", "elements": "int"},
},
},
@@ -65,7 +68,6 @@ class VlansArgs(object):
},
"type": "list",
},
- "configuration": {"type": "bool"},
"running_config": {"type": "str"},
"state": {
"choices": [
@@ -75,6 +77,7 @@ class VlansArgs(object):
"deleted",
"rendered",
"parsed",
+ "purged",
"gathered",
],
"default": "merged",
diff --git a/plugins/module_utils/network/ios/config/acls/acls.py b/plugins/module_utils/network/ios/config/acls/acls.py
index 164c75c..7e784eb 100644
--- a/plugins/module_utils/network/ios/config/acls/acls.py
+++ b/plugins/module_utils/network/ios/config/acls/acls.py
@@ -119,6 +119,16 @@ class Acls(ResourceModule):
for wname, wentry in iteritems(wplists):
hentry = hplists.pop(wname, {})
acl_type = wentry["acl_type"] if wentry.get("acl_type") else hentry.get("acl_type")
+ # If ACLs type is different between existing and wanted ACL, we need first remove it
+ if acl_type != hentry.get("acl_type", acl_type):
+ self.commands.append(
+ "no " + self.acl_name_cmd(wname, afi, hentry.get("acl_type", "")),
+ )
+ hentry.pop(
+ "aces",
+ {},
+ ) # We remove ACEs because we have previously add a command to suppress completely the ACL
+
begin = len(self.commands) # to determine the index for acl command
self._compare_aces(
wentry.pop("aces", {}),
@@ -205,15 +215,36 @@ class Acls(ResourceModule):
negate=True,
)
# remove ace if not in want
+ # we might think why not update it directly,
+ # if we try to update without negating the entry appliance
+ # reports % Duplicate sequence number
if hentry != wentry:
self.addcmd(add_afi(hentry, afi), "aces", negate=True)
+ # once an ace is negated intentionally emptying out have so that
+ # the remarks are repopulated, as the remarks and ace behavior is sticky
+ # if an ace is taken out all the remarks is removed automatically.
+ rem_hentry["remarks"] = {}
+
if rem_wentry.get("remarks"): # add remark if not in have
for k_wrems, wrems in rem_wentry.get("remarks").items():
if k_wrems not in rem_hentry.get("remarks", {}).keys():
self.addcmd(
- {"remarks": wrems, "sequence": hentry.get("sequence", "")},
+ {
+ "remarks": wrems,
+ "sequence": hentry.get("sequence", ""),
+ },
"remarks",
)
+ else:
+ rem_hentry.get("remarks", {}).pop(k_wrems)
+ # We remove remarks that are not in the wentry for this ACE
+ for k_hrems, hrems in rem_hentry.get("remarks", {}).items():
+ self.addcmd(
+ {"remarks": hrems, "sequence": hentry.get("sequence", "")},
+ "remarks",
+ negate=True,
+ )
+
# add ace if not in have
if hentry != wentry:
self.addcmd(add_afi(wentry, afi), "aces")
@@ -227,8 +258,12 @@ class Acls(ResourceModule):
"remarks",
negate=True,
)
- else: # remove extra aces
- self.addcmd(add_afi(hseq, afi), "aces", negate=True)
+ hseq.pop("remarks")
+ self.addcmd(
+ add_afi(hseq, afi),
+ "aces",
+ negate=True,
+ ) # deal with the rest of ace entry
def sanitize_protocol_options(self, wace, hace):
"""handles protocol and protocol options as optional attribute"""
@@ -262,7 +297,7 @@ class Acls(ResourceModule):
def list_to_dict(self, param):
"""converts list attributes to dict"""
- temp, count = dict(), 0
+ temp = dict()
if param:
for each in param: # ipv4 and ipv6 acl
temp_acls = {}
@@ -271,7 +306,9 @@ class Acls(ResourceModule):
temp_aces = {}
if acl.get("aces"):
rem_idx = 0 # remarks if defined in an ace
- for ace in acl.get("aces"): # each ace turned to dict
+ for count, ace in enumerate(
+ acl.get("aces"),
+ ): # each ace turned to dict
if (
ace.get("destination")
and ace.get("destination", {}).get(
@@ -311,13 +348,14 @@ class Acls(ResourceModule):
# temp_rem.extend(ace.pop("remarks"))
for remks in ace.get("remarks"):
rem_ace[remks.replace(" ", "_")] = remks
- rem_idx += 1
ace["remarks"] = rem_ace
if ace.get("sequence"):
temp_aces.update({ace.get("sequence"): ace})
+ elif ace.get("remarks"):
+ temp_aces.update({"__{0}".format(rem_idx): ace})
+ rem_idx += 1
elif ace:
- count += 1
temp_aces.update({"_" + to_text(count): ace})
# if temp_rem: # add remarks to the temp ace
@@ -325,7 +363,12 @@ class Acls(ResourceModule):
if acl.get("acl_type"): # update acl dict with req info
temp_acls.update(
- {acl.get("name"): {"aces": temp_aces, "acl_type": acl["acl_type"]}},
+ {
+ acl.get("name"): {
+ "aces": temp_aces,
+ "acl_type": acl["acl_type"],
+ },
+ },
)
else: # if no acl type then here eg: ipv6
temp_acls.update({acl.get("name"): {"aces": temp_aces}})
diff --git a/plugins/module_utils/network/ios/config/bgp_global/bgp_global.py b/plugins/module_utils/network/ios/config/bgp_global/bgp_global.py
index c48cac9..77112ff 100644
--- a/plugins/module_utils/network/ios/config/bgp_global/bgp_global.py
+++ b/plugins/module_utils/network/ios/config/bgp_global/bgp_global.py
@@ -61,6 +61,8 @@ class Bgp_global(ResourceModule):
"route_server_context.description",
"synchronization",
"table_map",
+ "template.peer_policy",
+ "template.peer_session",
"timers",
"bgp.additional_paths",
"bgp.advertise_best_external",
@@ -79,6 +81,8 @@ class Bgp_global(ResourceModule):
"bgp.consistency_checker.auto_repair",
"bgp.consistency_checker.error_message",
"bgp.dampening",
+ "bgp.default.ipv4_unicast",
+ "bgp.default.route_target.filter",
"bgp.deterministic_med",
"bgp.dmzlink_bw",
"bgp.enforce_first_as",
@@ -168,7 +172,10 @@ class Bgp_global(ResourceModule):
if self.state == "deleted":
# deleted, clean up global params
if not self.want or (self.have.get("as_number") == self.want.get("as_number")):
- self._compare(want={}, have=self.have)
+ if "as_number" not in self.want:
+ self.want["as_number"] = self.have.get("as_number")
+ self._set_bgp_defaults(self.want)
+ self._compare(self.want, have=self.have)
elif self.state == "purged":
# delete as_number takes down whole bgp config
@@ -190,10 +197,16 @@ class Bgp_global(ResourceModule):
for the Bgp_global network resource.
"""
self.generic_list_parsers = ["distributes", "aggregate_addresses", "networks"]
+
if self._has_bgp_inject_maps(want):
self.generic_list_parsers.insert(0, "inject_maps")
cmd_len = len(self.commands) # holds command length to add as_number
+
+ # for clean bgp global setup
+ if not have.get("bgp", {}).get("default"):
+ self._set_bgp_defaults(have)
+
# for dict type attributes
self.compare(parsers=self.parsers, want=want, have=have)
@@ -206,17 +219,40 @@ class Bgp_global(ResourceModule):
_parse,
)
else:
- self._compare_generic_lists(want.get(_parse, {}), have.get(_parse, {}), _parse)
+ self._compare_generic_lists(
+ want.get(_parse, {}),
+ have.get(_parse, {}),
+ _parse,
+ )
# for neighbors
- self._compare_neighbor_lists(want.get("neighbors", {}), have.get("neighbors", {}))
+ self._compare_neighbor_lists(
+ want.get("neighbors", {}),
+ have.get("neighbors", {}),
+ )
# for redistribute
- self._compare_redistribute_lists(want.get("redistribute", {}), have.get("redistribute", {}))
+ self._compare_redistribute_lists(
+ want.get("redistribute", {}),
+ have.get("redistribute", {}),
+ )
- # add as_number in the begining fo command set if commands generated
+ # add as_number in the beginning of commands set if commands generated
if len(self.commands) != cmd_len or (not have and want):
- self.commands.insert(0, self._tmplt.render(want or have, "as_number", False))
+ self.commands.insert(
+ 0,
+ self._tmplt.render(want or have, "as_number", False),
+ )
+
+ def _set_bgp_defaults(self, bgp_dict):
+ bgp_dict.setdefault("bgp", {}).setdefault("default", {}).setdefault(
+ "ipv4_unicast",
+ True,
+ )
+ bgp_dict.setdefault("bgp", {}).setdefault("default", {}).setdefault(
+ "route_target",
+ {},
+ ).setdefault("filter", True)
def _has_bgp_inject_maps(self, want):
if want.get("bgp", {}).get("inject_maps", {}):
@@ -324,10 +360,21 @@ class Bgp_global(ResourceModule):
]
for name, w_neighbor in want.items():
+ handle_shutdown_default = False
have_nbr = have.pop(name, {})
want_route = w_neighbor.pop("route_maps", {})
have_route = have_nbr.pop("route_maps", {})
+ if (
+ not w_neighbor.get("shutdown", {}).get("set")
+ and have_nbr.get("shutdown", {}).get("set")
+ and self.state in ["merged", "replaced", "overridden"]
+ ):
+ neig_parses.remove("shutdown")
+ handle_shutdown_default = True
self.compare(parsers=neig_parses, want=w_neighbor, have=have_nbr)
+ if handle_shutdown_default:
+ self.addcmd(have_nbr, "shutdown", True)
+
if want_route:
for k_rmps, w_rmps in want_route.items():
have_rmps = have_route.pop(k_rmps, {})
diff --git a/plugins/module_utils/network/ios/config/l3_interfaces/l3_interfaces.py b/plugins/module_utils/network/ios/config/l3_interfaces/l3_interfaces.py
index b4b874d..b862ac4 100644
--- a/plugins/module_utils/network/ios/config/l3_interfaces/l3_interfaces.py
+++ b/plugins/module_utils/network/ios/config/l3_interfaces/l3_interfaces.py
@@ -29,7 +29,6 @@ from ansible_collections.cisco.ios.plugins.module_utils.network.ios.rm_templates
)
from ansible_collections.cisco.ios.plugins.module_utils.network.ios.utils.utils import (
normalize_interface,
- validate_ipv6,
validate_n_expand_ipv4,
)
@@ -48,12 +47,18 @@ class L3_interfaces(ResourceModule):
tmplt=L3_interfacesTemplate(),
)
self.parsers = [
+ "mac_address",
"ipv4.address",
"ipv4.pool",
"ipv4.dhcp",
+ "ipv4.source_interface",
"ipv6.address",
"ipv6.autoconfig",
"ipv6.dhcp",
+ "ipv6.enable",
+ ]
+ self.gen_parsers = [
+ "autostate",
]
def execute_module(self):
@@ -101,10 +106,16 @@ class L3_interfaces(ResourceModule):
self._compare(want={}, have=have)
for k, want in wantd.items():
- self._compare(want=want, have=haved.pop(k, {}))
+ have = haved.pop(k, {})
+ # New interface (doesn't use fact file)
+ if k[:4] == "Vlan":
+ have.setdefault("autostate", True)
+ want.setdefault("autostate", True)
+ self._compare(want=want, have=have)
def _compare(self, want, have):
begin = len(self.commands)
+ self.compare(parsers=self.gen_parsers, want=want, have=have)
self._compare_lists(want=want, have=have)
if len(self.commands) != begin:
self.commands.insert(begin, self._tmplt.render(want or have, "name", False))
@@ -141,7 +152,12 @@ class L3_interfaces(ResourceModule):
# hacl is set as primary, if wacls has no other primary entry we must keep
# this entry as primary (so we'll compare entry to hacl and not
# generate commands)
- if list(filter(lambda w: w.get("secondary", False) is False, wacls.values())):
+ if list(
+ filter(
+ lambda w: w.get("secondary", False) is False,
+ wacls.values(),
+ ),
+ ):
# another primary is in wacls
hacl = {}
self.validate_ips(afi, want=entry, have=hacl)
@@ -168,17 +184,11 @@ class L3_interfaces(ResourceModule):
v4_addr = validate_n_expand_ipv4(self._module, want) if want.get("address") else {}
if v4_addr:
want["address"] = v4_addr
- elif afi == "ipv6" and want:
- if want.get("address"):
- validate_ipv6(want["address"], self._module)
if afi == "ipv4" and have:
v4_addr_h = validate_n_expand_ipv4(self._module, have) if have.get("address") else {}
if v4_addr_h:
have["address"] = v4_addr_h
- elif afi == "ipv6" and have:
- if have.get("address"):
- validate_ipv6(have["address"], self._module)
def list_to_dict(self, param):
if param:
diff --git a/plugins/module_utils/network/ios/config/snmp_server/snmp_server.py b/plugins/module_utils/network/ios/config/snmp_server/snmp_server.py
index 187d077..d61a70a 100644
--- a/plugins/module_utils/network/ios/config/snmp_server/snmp_server.py
+++ b/plugins/module_utils/network/ios/config/snmp_server/snmp_server.py
@@ -237,39 +237,20 @@ class Snmp_server(ResourceModule):
def _compare_lists_attrs(self, want, have):
"""Compare list of dict"""
for _parser in self.list_parsers:
- if _parser == "users":
- i_want = want.get(_parser, {})
- i_have = have.get(_parser, {})
- for key, wanting in iteritems(i_want):
- wanting_compare = deepcopy(wanting)
- if (
- "authentication" in wanting_compare
- and "password" in wanting_compare["authentication"]
- ):
- wanting_compare["authentication"].pop("password")
- if (
- "encryption" in wanting_compare
- and "password" in wanting_compare["encryption"]
- ):
- wanting_compare["encryption"].pop("password")
- haveing = i_have.pop(key, {})
- if wanting_compare != haveing:
- if haveing and self.state in ["overridden", "replaced"]:
+ i_want = want.get(_parser, {})
+ i_have = have.get(_parser, {})
+ for key, wanting in iteritems(i_want):
+ haveing = i_have.pop(key, {})
+ if wanting != haveing:
+ if haveing and self.state in ["overridden", "replaced"]:
+ if not (
+ _parser == "users"
+ and wanting.get("username") == haveing.get("username")
+ ):
self.addcmd(haveing, _parser, negate=True)
- self.addcmd(wanting, _parser)
- for key, haveing in iteritems(i_have):
- self.addcmd(haveing, _parser, negate=True)
- else:
- i_want = want.get(_parser, {})
- i_have = have.get(_parser, {})
- for key, wanting in iteritems(i_want):
- haveing = i_have.pop(key, {})
- if wanting != haveing:
- if haveing and self.state in ["overridden", "replaced"]:
- self.addcmd(haveing, _parser, negate=True)
- self.addcmd(wanting, _parser)
- for key, haveing in iteritems(i_have):
- self.addcmd(haveing, _parser, negate=True)
+ self.addcmd(wanting, _parser)
+ for key, haveing in iteritems(i_have):
+ self.addcmd(haveing, _parser, negate=True)
def _snmp_list_to_dict(self, data):
"""Convert all list of dicts to dicts of dicts"""
diff --git a/plugins/module_utils/network/ios/config/vlans/vlans.py b/plugins/module_utils/network/ios/config/vlans/vlans.py
index ad95b68..d195c31 100644
--- a/plugins/module_utils/network/ios/config/vlans/vlans.py
+++ b/plugins/module_utils/network/ios/config/vlans/vlans.py
@@ -1,62 +1,60 @@
#
# -*- coding: utf-8 -*-
-# Copyright 2019 Red Hat
+# Copyright 2024 Red Hat
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
-"""
-The ios_vlans class
-It is in this file where the current configuration (as dict)
-is compared to the provided configuration (as dict) and the command set
-necessary to bring the current configuration to it's desired end-state is
-created
-"""
+#
from __future__ import absolute_import, division, print_function
__metaclass__ = type
+"""
+The ios_vlans config file.
+It is in this file where the current configuration (as dict)
+is compared to the provided configuration (as dict) and the command set
+necessary to bring the current configuration to its desired end-state is
+created.
+"""
+
-from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.cfg.base import (
- ConfigBase,
+from ansible.module_utils.six import iteritems
+from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.rm_base.resource_module import (
+ ResourceModule,
)
from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
- remove_empties,
- to_list,
+ dict_merge,
)
from ansible_collections.cisco.ios.plugins.module_utils.network.ios.facts.facts import Facts
-from ansible_collections.cisco.ios.plugins.module_utils.network.ios.utils.utils import dict_to_set
+from ansible_collections.cisco.ios.plugins.module_utils.network.ios.rm_templates.vlans import (
+ VlansTemplate,
+)
-class Vlans(ConfigBase):
+class Vlans(ResourceModule):
"""
- The ios_vlans class
+ The ios_vlans config class
"""
- gather_subset = ["!all", "!min"]
-
- gather_network_resources = ["vlans"]
-
def __init__(self, module):
- super(Vlans, self).__init__(module)
-
- def get_vlans_facts(self, data=None):
- """Get the 'facts' (the current configuration)
-
- :rtype: A dictionary
- :returns: The current configuration as a dictionary
- """
-
- facts, _warnings = Facts(self._module).get_facts(
- self.gather_subset,
- self.gather_network_resources,
- data=data,
+ super(Vlans, self).__init__(
+ empty_fact_val={},
+ facts_module=Facts(module),
+ module=module,
+ resource="vlans",
+ tmplt=VlansTemplate(),
)
- vlans_facts = facts["ansible_network_resources"].get("vlans")
- if not vlans_facts:
- return []
- return vlans_facts
+ self.parsers = [
+ "name",
+ "state",
+ "mtu",
+ "remote_span",
+ "private_vlan.type",
+ "private_vlan.associated",
+ "member",
+ ]
def execute_module(self):
"""Execute the module
@@ -64,394 +62,106 @@ class Vlans(ConfigBase):
:rtype: A dictionary
:returns: The result from module execution
"""
- result = {"changed": False}
- commands = list()
- warnings = list()
- self.have_now = list()
- self.configuration = self._module.params["configuration"]
- if not self.configuration:
- self.vlan_parent = "vlan {0}"
- else:
- self.vlan_parent = "vlan configuration {0}"
- if self.state in self.ACTION_STATES:
- existing_vlans_facts = self.get_vlans_facts()
- else:
- existing_vlans_facts = []
-
- if self.state in self.ACTION_STATES or self.state == "rendered":
- commands.extend(self.set_config(existing_vlans_facts))
- if commands and self.state in self.ACTION_STATES:
- if not self._module.check_mode:
- self._connection.edit_config(commands)
- result["changed"] = True
- if self.state in self.ACTION_STATES:
- result["commands"] = commands
-
- if self.state in self.ACTION_STATES or self.state == "gathered":
- changed_vlans_facts = self.get_vlans_facts()
- elif self.state == "rendered":
- result["rendered"] = commands
- elif self.state == "parsed":
- running_config = self._module.params["running_config"]
- if not running_config:
- self._module.fail_json(
- msg="value of running_config parameter must not be empty for state parsed",
+ if self.state not in ["parsed", "gathered"]:
+ self.segregate_resource()
+ self.run_commands()
+ return self.result
+
+ def segregate_resource(self):
+ self.want_vlan_config = []
+ self.have_vlan_config = []
+ for vlan_data in self.want:
+ if vlan_data.get("member"):
+ self.want_vlan_config.append(
+ {
+ "vlan_id": vlan_data.get("vlan_id"),
+ "member": vlan_data.pop("member"),
+ },
)
- result["parsed"] = self.get_vlans_facts(data=running_config)
- else:
- changed_vlans_facts = []
-
- if self.state in self.ACTION_STATES:
- result["before"] = existing_vlans_facts
- if result["changed"]:
- result["after"] = changed_vlans_facts
- elif self.state == "gathered":
- result["gathered"] = changed_vlans_facts
-
- result["warnings"] = warnings
- return result
-
- def set_config(self, existing_vlans_facts):
- """Collect the configuration from the args passed to the module,
- collect the current configuration (as a dict from facts)
-
- :rtype: A list
- :returns: the commands necessary to migrate the current configuration
- to the desired configuration
- """
- want = []
- if self._module.params.get("config"):
- for cfg in self._module.params["config"]:
- want.append(remove_empties(cfg))
- have = existing_vlans_facts
- resp = self.set_state(want, have)
- return to_list(resp)
-
- def set_state(self, want, have):
- """Select the appropriate function based on the state provided
-
- :param want: the desired configuration as a dictionary
- :param have: the current configuration as a dictionary
- :rtype: A list
- :returns: the commands necessary to migrate the current configuration
- to the desired configuration
- """
-
- if self.state in ("overridden", "merged", "replaced", "rendered") and not want:
- self._module.fail_json(
- msg="value of config parameter must not be empty for state {0}".format(self.state),
- )
-
- if self.state == "overridden":
- commands = self._state_overridden(want, have)
- elif self.state == "deleted":
- commands = self._state_deleted(want, have)
- elif self.state in ("merged", "rendered"):
- commands = self._state_merged(want, have)
- elif self.state == "replaced":
- commands = self._state_replaced(want, have)
- return commands
-
- def _state_replaced(self, want, have):
- """The command generator when state is replaced
-
- :rtype: A list
- :returns: the commands necessary to migrate the current configuration
- to the desired configuration
- """
- commands = []
-
- check = False
- for each in want:
- for every in have:
- if every["vlan_id"] == each["vlan_id"]:
- check = True
- break
- continue
- if check:
- commands.extend(self._set_config(each, every))
- else:
- commands.extend(self._set_config(each, dict()))
-
- return commands
-
- def _state_overridden(self, want, have):
- """The command generator when state is overridden
-
- :rtype: A list
- :returns: the commands necessary to migrate the current configuration
- to the desired configuration
- """
- commands = []
-
- want_local = want
- self.have_now = have.copy()
- for each in have:
- count = 0
- for every in want_local:
- if each["vlan_id"] == every["vlan_id"]:
- break
- count += 1
else:
- # We didn't find a matching desired state, which means we can
- # pretend we received an empty desired state.
- commands.extend(self._clear_config(every, each))
- continue
- commands.extend(self._set_config(every, each))
- # as the pre-existing VLAN are now configured by
- # above set_config call, deleting the respective
- # VLAN entry from the want_local list
- del want_local[count]
-
- # Iterating through want_local list which now only have new VLANs to be
- # configured
- for each in want_local:
- commands.extend(self._set_config(each, dict()))
-
- return commands
-
- def _state_merged(self, want, have):
- """The command generator when state is merged
-
- :rtype: A list
- :returns: the commands necessary to merge the provided into
- the current configuration
- """
- commands = []
-
- check = False
- for each in want:
- for every in have:
- if each.get("vlan_id") == every.get("vlan_id"):
- check = True
- break
- continue
- if check:
- commands.extend(self._set_config(each, every))
+ self.want_vlan_config.append(
+ {"vlan_id": vlan_data.get("vlan_id")},
+ )
+ for vlan_data in self.have:
+ if vlan_data.get("member"):
+ self.have_vlan_config.append(
+ {
+ "vlan_id": vlan_data.get("vlan_id"),
+ "member": vlan_data.pop("member"),
+ },
+ )
else:
- commands.extend(self._set_config(each, dict()))
-
- return commands
-
- def _state_deleted(self, want, have):
- """The command generator when state is deleted
+ self.have_vlan_config.append(
+ {"vlan_id": vlan_data.get("vlan_id")},
+ )
+ if self.want or self.have:
+ self.generate_commands(self.want, self.have, "vlans")
+ if self.want_vlan_config or self.have_vlan_config:
+ self.generate_commands(
+ self.want_vlan_config,
+ self.have_vlan_config,
+ "vlan_configuration",
+ )
- :rtype: A list
- :returns: the commands necessary to remove the current configuration
- of the provided objects
+ def generate_commands(self, conf_want, conf_have, resource=None):
+ """Generate configuration commands to send based on
+ want, have and desired state.
"""
- commands = []
-
- if want:
- check = False
- for each in want:
- for every in have:
- if each.get("vlan_id") == every.get("vlan_id"):
- check = True
- break
- check = False
- continue
- if check:
- commands.extend(self._clear_config(each, every))
+ wantd = {entry["vlan_id"]: entry for entry in conf_want}
+ haved = {entry["vlan_id"]: entry for entry in conf_have}
+
+ # if state is merged, merge want onto have and then compare
+ if self.state == "merged":
+ wantd = dict_merge(haved, wantd)
+
+ # if state is deleted, empty out wantd and set haved to wantd
+ if self.state == "deleted":
+ haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd}
+ wantd = {}
+
+ # if state is deleted, empty out wantd and set haved to wantd
+ if self.state in ["deleted", "purged"]:
+ haved = {k: v for k, v in iteritems(haved) if k in wantd or not wantd}
+ wantd = {}
+
+ # remove superfluous config for overridden and deleted
+ if self.state in ["overridden", "deleted"]:
+ for k, have in iteritems(haved):
+ if k not in wantd:
+ self._compare(want={}, have=have, resource=resource)
+
+ if self.state == "purged":
+ for k, have in iteritems(haved):
+ self.purge(have, resource)
else:
- for each in have:
- commands.extend(self._clear_config(dict(), each))
-
- return commands
-
- def remove_command_from_config_list(self, vlan_id, cmd, commands):
- if vlan_id not in commands and cmd != "vlan":
- commands.insert(0, vlan_id)
- elif cmd == "vlan":
- commands.append("no %s" % vlan_id)
- return commands
- commands.append("no %s" % cmd)
- return commands
-
- def add_command_to_config_list(self, vlan_id, cmd, commands):
- if vlan_id not in commands:
- commands.insert(0, vlan_id)
- if cmd not in commands:
- commands.append(cmd)
-
- def _set_config(self, want, have):
- # Set the interface config based on the want and have config
- commands = []
-
- vlan = self.vlan_parent.format(want.get("vlan_id"))
-
- def negate_have_config(want_diff, have_diff, vlan, commands):
- name = dict(have_diff).get("name")
- if name and not dict(want_diff).get("name"):
- self.remove_command_from_config_list(vlan, "name {0}".format(name), commands)
- state = dict(have_diff).get("state")
- if state and not dict(want_diff).get("state"):
- self.remove_command_from_config_list(vlan, "state {0}".format(state), commands)
- shutdown = dict(have_diff).get("shutdown")
- if shutdown and not dict(want_diff).get("shutdown"):
- self.remove_command_from_config_list(vlan, "shutdown", commands)
- mtu = dict(have_diff).get("mtu")
- if mtu and not dict(want_diff).get("mtu"):
- self.remove_command_from_config_list(vlan, "mtu {0}".format(mtu), commands)
- remote_span = dict(have_diff).get("remote_span")
- if remote_span and not dict(want_diff).get("remote_span"):
- self.remove_command_from_config_list(vlan, "remote-span", commands)
- private_vlan = dict(have_diff).get("private_vlan")
- if private_vlan and not dict(want_diff).get("private_vlan"):
- private_vlan_type = dict(private_vlan).get("type")
- self.remove_command_from_config_list(
- vlan,
- "private-vlan {0}".format(private_vlan_type),
- commands,
- )
- if private_vlan_type == "primary" and dict(private_vlan).get("associated"):
- self.remove_command_from_config_list(vlan, "private-vlan association", commands)
-
- # Get the diff b/w want n have
-
- want_dict = dict_to_set(want, sort_dictionary=True)
- have_dict = dict_to_set(have, sort_dictionary=True)
- diff = want_dict - have_dict
- have_diff = have_dict - want_dict
-
- if diff:
- if have_diff and (self.state == "replaced" or self.state == "overridden"):
- negate_have_config(diff, have_diff, vlan, commands)
-
- if not self.configuration:
- name = dict(diff).get("name")
- state = dict(diff).get("state")
- shutdown = dict(diff).get("shutdown")
- mtu = dict(diff).get("mtu")
- remote_span = dict(diff).get("remote_span")
- private_vlan = dict(diff).get("private_vlan")
-
- if name:
- self.add_command_to_config_list(vlan, "name {0}".format(name), commands)
- if state:
- self.add_command_to_config_list(vlan, "state {0}".format(state), commands)
- if mtu:
- self.add_command_to_config_list(vlan, "mtu {0}".format(mtu), commands)
- if remote_span:
- self.add_command_to_config_list(vlan, "remote-span", commands)
-
- if private_vlan:
- private_vlan_type = dict(private_vlan).get("type")
- private_vlan_associated = dict(private_vlan).get("associated")
- if private_vlan_type:
- self.add_command_to_config_list(
- vlan,
- "private-vlan {0}".format(private_vlan_type),
- commands,
- )
- if private_vlan_associated:
- associated_list = ",".join(
- str(e) for e in private_vlan_associated
- ) # Convert python list to string with elements separated by a comma
- self.add_command_to_config_list(
- vlan,
- "private-vlan association {0}".format(associated_list),
- commands,
- )
- if shutdown == "enabled":
- self.add_command_to_config_list(vlan, "shutdown", commands)
- elif shutdown == "disabled":
- self.add_command_to_config_list(vlan, "no shutdown", commands)
+ for k, want in iteritems(wantd):
+ self._compare(want=want, have=haved.pop(k, {}), resource=resource)
+
+ def _compare(self, want, have, resource=None):
+ """Leverages the base class `compare()` method and
+ populates the list of commands to be run by comparing
+ the `want` and `have` data with the `parsers` defined
+ for the Vlans network resource.
+ """
+ begin = len(self.commands)
+ self.compare(parsers=self.parsers, want=want, have=have)
+ if want.get("shutdown") != have.get("shutdown"):
+ if want.get("shutdown"):
+ self.addcmd(want, "shutdown", True)
else:
- member_dict = dict(diff).get("member")
- if member_dict:
- member_dict = dict(member_dict)
- member_vni = member_dict.get("vni")
- member_evi = member_dict.get("evi")
- commands.extend(
- self._remove_vlan_vni_evi_mapping(
- want,
- ),
- )
- commands.extend(
- [
- vlan,
- self._get_member_cmds(member_dict),
- ],
- )
-
- elif have_diff and (self.state == "replaced" or self.state == "overridden"):
- negate_have_config(diff, have_diff, vlan, commands)
- return commands
-
- def _clear_config(self, want, have):
- # Delete the interface config based on the want and have config
- commands = []
- vlan = self.vlan_parent.format(have.get("vlan_id"))
-
- if (
- have.get("vlan_id")
- and "default" not in have.get("name", "")
- and (have.get("vlan_id") != want.get("vlan_id") or self.state == "deleted")
- ):
- self.remove_command_from_config_list(vlan, "vlan", commands)
- if self.configuration and self.state == "overridden":
- self.have_now.remove(have)
- elif "default" not in have.get("name", ""):
- if not self.configuration:
- if have.get("mtu") != want.get("mtu"):
- self.remove_command_from_config_list(vlan, "mtu", commands)
- if have.get("remote_span") != want.get("remote_span") and want.get("remote_span"):
- self.remove_command_from_config_list(vlan, "remote-span", commands)
- if have.get("shutdown") != want.get("shutdown") and want.get("shutdown"):
- self.remove_command_from_config_list(vlan, "shutdown", commands)
- if have.get("state") != want.get("state") and want.get("state"):
- self.remove_command_from_config_list(vlan, "state", commands)
- return commands
-