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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2022, Cisco Systems
# 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
__author__ = ("Madhan Sankaranarayanan, Abhishek Maheshwari")
DOCUMENTATION = r"""
---
module: inventory_intent
short_description: Resource module for Network Device
description:
- Manage operations create, update and delete of the resource Network Device.
- Adds the device with given credential.
- Deletes the network device for the given Id.
- Sync the devices provided as input.
version_added: '6.8.0'
extends_documentation_fragment:
- cisco.dnac.intent_params
author: Abhishek Maheshwari (@abmahesh)
Madhan Sankaranarayanan (@madhansansel)
options:
config_verify:
description: Set to True to verify the Cisco Catalyst Center config after applying the playbook config.
type: bool
default: False
state:
description: The state of Cisco Catalyst Center after module completion.
type: str
choices: [ merged, deleted ]
default: merged
config:
description: List of devices with credentails to perform Add/Update/Delete/Resync operation
type: list
elements: dict
required: True
suboptions:
type:
description: Select Device's type from NETWORK_DEVICE, COMPUTE_DEVICE, MERAKI_DASHBOARD, THIRD_PARTY_DEVICE, FIREPOWER_MANAGEMENT_SYSTEM.
NETWORK_DEVICE - This refers to traditional networking equipment such as routers, switches, access points, and firewalls. These devices
are responsible for routing, switching, and providing connectivity within the network.
COMPUTE_DEVICE - These are computing resources such as servers, virtual machines, or containers that are part of the network infrastructure.
Cisco Catalyst Center can integrate with compute devices to provide visibility and management capabilities, ensuring that the network and
compute resources work together seamlessly to support applications and services.
MERAKI_DASHBOARD - It is cloud-based platform used to manage Meraki networking devices, including wireless access points, switches, security
appliances, and cameras.
THIRD_PARTY_DEVICE - This category encompasses devices from vendors other than Cisco or Meraki. Cisco Catalyst Center is designed to support
integration with third-party devices through open standards and APIs. This allows organizations to manage heterogeneous network
environments efficiently using Cisco Catalyst Center's centralized management and automation capabilities.
FIREPOWER_MANAGEMENT_SYSTEM - It is a centralized management console used to manage Cisco's Firepower Next-Generation Firewall (NGFW) devices.
It provides features such as policy management, threat detection, and advanced security analytics.
type: str
default: "NETWORK_DEVICE"
cli_transport:
description: The essential prerequisite for adding Network devices is the specification of the transport
protocol (either ssh or telnet) used by the device.
type: str
compute_device:
description: Indicates whether a device is a compute device.
type: bool
password:
description: Password for accessing the device and for file encryption during device export. Required for
adding Network Device. Also needed for file encryption while exporting device in a csv file.
type: str
enable_password:
description: Password required for enabling configurations on the device.
type: str
extended_discovery_info:
description: Additional discovery information for the device.
type: str
http_password:
description: HTTP password required for adding compute, Meraki, and Firepower Management Devices.
type: str
http_port:
description: HTTP port number required for adding compute and Firepower Management Devices.
type: str
http_secure:
description: Flag indicating HTTP security.
type: bool
http_username:
description: HTTP username required for adding compute and Firepower Management Devices.
type: str
ip_address_list:
description: A list of the IP addresses for the devices. It is required for tasks such as adding, updating, deleting,
or resyncing devices, with Meraki devices being the exception.
elements: str
type: list
hostname_list:
description: "A list of hostnames representing devices. Operations such as updating, deleting, resyncing, or rebooting
can be performed as alternatives to using IP addresses."
type: list
elements: str
serial_number_list:
description: A list of serial numbers representing devices. Operations such as updating, deleting, resyncing, or rebooting
can be performed as alternatives to using IP addresses.
type: list
elements: str
mac_address_list:
description: "A list of MAC addresses representing devices. Operations such as updating, deleting, resyncing, or rebooting
can be performed as alternatives to using IP addresses."
type: list
elements: str
netconf_port:
description: Specifies the port number for connecting to devices using the Netconf protocol. Netconf (Network Configuration Protocol)
is used for managing network devices. Ensure that the provided port number corresponds to the Netconf service port configured
on your network devices.
NETCONF with user privilege 15 is mandatory for enabling Wireless Services on Wireless capable devices such as Catalyst 9000 series
Switches and C9800 Series Wireless Controllers. The NETCONF credentials are required to connect to C9800 Series Wireless Controllers
as the majority of data collection is done using NETCONF for these Devices.
type: str
username:
description: Username for accessing the device. Required for Adding Network Device.
type: str
snmp_auth_passphrase:
description: SNMP authentication passphrase required for adding network, compute, and third-party devices.
type: str
snmp_auth_protocol:
description: SNMP authentication protocol.
SHA (Secure Hash Algorithm) - cryptographic hash function commonly used for data integrity verification and authentication purposes.
type: str
default: "SHA"
snmp_mode:
description: Device's snmp Mode refer to different SNMP (Simple Network Management Protocol) versions and their corresponding security levels.
NOAUTHNOPRIV - This mode provides no authentication or encryption for SNMP messages. It means that devices communicating using SNMPv1 do
not require any authentication (username/password) or encryption (data confidentiality). This makes it the least secure option.
AUTHNOPRIV - This mode provides authentication but no encryption for SNMP messages. Authentication involves validating the source of the
SNMP messages using a community string (similar to a password). However, the data transmitted between devices is not encrypted,
so it's susceptible to eavesdropping.
AUTHPRIV - This mode provides both authentication and encryption for SNMP messages. It offers the highest level of security among the three
options. Authentication ensures that the source of the messages is genuine, and encryption ensures that the data exchanged between
devices is confidential and cannot be intercepted by unauthorized parties.
type: str
snmp_priv_passphrase:
description: SNMP private passphrase required for adding network, compute, and third-party devices.
type: str
snmp_priv_protocol:
description: SNMP private protocol required for adding network, compute, and third-party devices.
type: str
snmp_ro_community:
description: SNMP Read-Only community required for adding V2C devices.
type: str
snmp_rw_community:
description: SNMP Read-Write community required for adding V2C devices.
type: str
snmp_retry:
description: SNMP retry count.
type: int
default: 3
snmp_timeout:
description: SNMP timeout duration.
type: int
default: 5
snmp_username:
description: SNMP username required for adding network, compute, and third-party devices.
type: str
snmp_version:
description: It is a standard protocol used for managing and monitoring network devices.
v2 - In this communication between the SNMP manager (such as Cisco Catalyst) and the managed devices
(such as routers, switches, or access points) is based on community strings.Community strings serve
as form of authentication and they are transmitted in clear text, providing no encryption.
v3 - It is the most secure version of SNMP, providing authentication, integrity, and encryption features.
It allows for the use of usernames, authentication passwords, and encryption keys, providing stronger
security compared to v2.
type: str
update_mgmt_ipaddresslist:
description: List of updated management IP addresses for network devices.
type: list
elements: dict
suboptions:
exist_mgmt_ipaddress:
description: Device's existing Mgmt IpAddress.
type: str
new_mgmt_ipaddress:
description: Device's new Mgmt IpAddress.
type: str
force_sync:
description: If forcesync is true then device sync would run in high priority thread if available, else the sync will fail.
type: bool
default: False
device_resync:
description: Make this as true needed for the resyncing of device.
type: bool
default: False
reboot_device:
description: Make this as true needed for the Rebooting of Access Points.
type: bool
default: False
credential_update:
description: Make this as true needed for the updation of device credentials and other device details.
type: bool
default: False
clean_config:
description: Required if need to delete the Provisioned device by clearing current configuration.
type: bool
default: False
role:
description: Role of device which can be ACCESS, CORE, DISTRIBUTION, BORDER ROUTER, UNKNOWN.
ALL - This role typically represents all devices within the network, regardless of their specific roles or functions.
UNKNOWN - This role is assigned to devices whose roles or functions have not been identified or classified within Cisco Catalsyt Center.
This could happen if the platform is unable to determine the device's role based on available information.
ACCESS - This role typically represents switches or access points that serve as access points for end-user devices to connect to the network.
These devices are often located at the edge of the network and provide connectivity to end-user devices.
BORDER ROUTER - These are devices that connect different network domains or segments together. They often serve as
gateways between different networks, such as connecting an enterprise network to the internet or connecting
multiple branch offices.
DISTRIBUTION - This role represents function as distribution switches or routers in hierarchical network designs. They aggregate traffic
from access switches and route it toward the core of the network or toward other distribution switches.
CORE - This role typically represents high-capacity switches or routers that form the backbone of the network. They handle large volumes
of traffic and provide connectivity between different parts of network, such as connecting distribution switches or
providing interconnection between different network segments.
type: str
add_user_defined_field:
description: This operation will take dictionary as a parameter and in this we give details to
create/update/delete/assign multiple UDF to a device.
type: dict
suboptions:
name:
description: Name of Global User Defined Field. Required for creating/deleting UDF and then assigning it to device.
type: str
description:
description: Info about the global user defined field. Also used while updating interface details.
type: str
value:
description: Value to assign to tag with or without the same user defined field name.
type: str
update_interface_details:
description: This operation will take dictionary as a parameter and in this we give details to update interface details of device.
type: dict
suboptions:
description:
description: Specifies the description of the interface of the device.
type: str
interface_name:
description: Specify the list of interface names to update the details of the device interface.
(For example, GigabitEthernet1/0/11, FortyGigabitEthernet1/1/2)
type: list
elements: str
vlan_id:
description: Unique Id number assigned to a VLAN within a network used only while updating interface details.
type: int
voice_vlan_id:
description: Identifier used to distinguish a specific VLAN that is dedicated to voice traffic used only while updating interface details.
type: int
deployment_mode:
description: Preview/Deploy [Preview means the configuration is not pushed to the device. Deploy makes the configuration pushed to the device]
type: str
default: "Deploy"
clear_mac_address_table:
description: Set this to true if you need to clear the MAC address table for a specific device's interface. It's a boolean type,
with a default value of False.
type: bool
default: False
admin_status:
description: Status of Interface of a device, it can be (UP/DOWN).
type: str
export_device_list:
description: This operation take dictionary as parameter and export the device details as well as device credentials
details in a csv file.
type: dict
suboptions:
password:
description: Specifies the password for the encryption of file while exporting the device credentails into the file.
type: str
site_name:
description: Indicates the exact location where the wired device will be provisioned. This is a string value that should
represent the complete hierarchical path of the site (For example, "Global/USA/San Francisco/BGL_18/floor_pnp").
type: str
operation_enum:
description: enum(CREDENTIALDETAILS, DEVICEDETAILS) 0 to export Device Credential Details Or 1 to export Device Details.
CREDENTIALDETAILS - Used for exporting device credentials details like snpm credntials, device crdentails etc.
DEVICEDETAILS - Used for exporting device specific details like device hostname, serial number, type, family etc.
type: str
parameters:
description: List of device parameters that needs to be exported to file.(For example, ["componentName", "SerialNumber", "Last Sync Status"])
type: list
elements: str
provision_wired_device:
description: This parameter takes a list of dictionaries. Each dictionary provides the IP address of a wired device and
the name of the site where the device will be provisioned.
type: list
elements: dict
suboptions:
device_ip:
description: Specifies the IP address of the wired device. This is a string value that should be in the format of
standard IPv4 or IPv6 addresses.
type: str
version_added: 6.12.0
site_name:
description: Indicates the exact location where the wired device will be provisioned. This is a string value that should
represent the complete hierarchical path of the site (For example, "Global/USA/San Francisco/BGL_18/floor_pnp").
type: str
resync_retry_count:
description: Determines the total number of retry attempts for checking if the device has reached a managed state during
the provisioning process. If unspecified, the default value is set to 200 retries.
type: int
default: 200
version_added: 6.12.0
resync_retry_interval:
description: Sets the interval, in seconds, at which the system will recheck the device status throughout the provisioning
process. If unspecified, the system will check the device status every 2 seconds by default.
type: int
default: 2
version_added: 6.12.0
requirements:
- dnacentersdk >= 2.7.1
- python >= 3.9
seealso:
- name: Cisco Catalyst Center documentation for Devices AddDevice2
description: Complete reference of the AddDevice2 API.
link: https://developer.cisco.com/docs/dna-center/#!add-device
- name: Cisco Catalyst Center documentation for Devices DeleteDeviceById
description: Complete reference of the DeleteDeviceById API.
link: https://developer.cisco.com/docs/dna-center/#!delete-device-by-id
- name: Cisco Catalyst Center documentation for Devices SyncDevices2
description: Complete reference of the SyncDevices2 API.
link: https://developer.cisco.com/docs/dna-center/#!sync-devices
notes:
- SDK Method used are
devices.Devices.add_device,
devices.Devices.delete_device_by_id,
devices.Devices.sync_devices,
- Paths used are
post /dna/intent/api/v1/network-device,
delete /dna/intent/api/v1/network-device/{id},
put /dna/intent/api/v1/network-device,
- Removed 'managementIpAddress' options in v4.3.0.
- Renamed argument 'ip_address' to 'ip_address_list' option in v6.12.0.
- Removed 'serial_number', 'device_added', 'role_source', options in v6.12.0.
- Added 'add_user_defined_field', 'update_interface_details', 'export_device_list' options in v6.13.1.
- Removed 'provision_wireless_device', 'reprovision_wired_device' options in v6.13.1.
- Added the parameter 'admin_status' options in v6.13.1.
- Removed 'device_updated' options in v6.13.1.
"""
EXAMPLES = r"""
- name: Add new device in Inventory with full credentials
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- cli_transport: ssh
compute_device: False
password: Test@123
enable_password: Test@1234
extended_discovery_info: test
http_username: "testuser"
http_password: "test"
http_port: "443"
http_secure: False
ip_address_list: ["1.1.1.1", "2.2.2.2"]
netconf_port: 830
snmp_auth_passphrase: "Lablab@12"
snmp_auth_protocol: SHA
snmp_mode: AUTHPRIV
snmp_priv_passphrase: "Lablab@123"
snmp_priv_protocol: AES256
snmp_retry: 3
snmp_timeout: 5
snmp_username: v3Public
snmp_version: v3
type: NETWORK_DEVICE
username: cisco
- name: Add new Compute device in Inventory with full credentials.Inputs needed for Compute Device
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
http_username: "testuser"
http_password: "test"
http_port: "443"
snmp_auth_passphrase: "Lablab@12"
snmp_auth_protocol: SHA
snmp_mode: AUTHPRIV
snmp_priv_passphrase: "Lablab@123"
snmp_priv_protocol: AES256
snmp_retry: 3
snmp_timeout: 5
snmp_username: v3Public
compute_device: True
username: cisco
type: "COMPUTE_DEVICE"
- name: Add new Meraki device in Inventory with full credentials.Inputs needed for Meraki Device.
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- http_password: "test"
type: "MERAKI_DASHBOARD"
- name: Add new Firepower Management device in Inventory with full credentials.Input needed to add Device.
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
http_username: "testuser"
http_password: "test"
http_port: "443"
type: "FIREPOWER_MANAGEMENT_SYSTEM"
- name: Add new Third Party device in Inventory with full credentials.Input needed to add Device.
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
snmp_auth_passphrase: "Lablab@12"
snmp_auth_protocol: SHA
snmp_mode: AUTHPRIV
snmp_priv_passphrase: "Lablab@123"
snmp_priv_protocol: AES256
snmp_retry: 3
snmp_timeout: 5
snmp_username: v3Public
type: "THIRD_PARTY_DEVICE"
- name: Update device details or credentails in Inventory
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- cli_transport: telnet
compute_device: False
password: newtest123
enable_password: newtest1233
ip_address_list: ["1.1.1.1", "2.2.2.2"]
type: NETWORK_DEVICE
credential_update: True
- name: Update new management IP address of device in inventory
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- ip_address_list: ["1.1.1.1"]
credential_update: True
update_mgmt_ipaddresslist:
- exist_mgmt_ipaddress: "1.1.1.1"
new_mgmt_ipaddress: "12.12.12.12"
- name: Associate Wired Devices to site and Provisioned it in Inventory
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- provision_wired_device:
- device_ip: "1.1.1.1"
site_name: "Global/USA/San Francisco/BGL_18/floor_pnp"
resync_retry_count: 200
resync_retry_interval: 2
- device_ip: "2.2.2.2"
site_name: "Global/USA/San Francisco/BGL_18/floor_test"
resync_retry_count: 200
resync_retry_interval: 2
- name: Update Device Role with IP Address
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
role: ACCESS
- name: Update Interface details with IP Address
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
update_interface_details:
description: "Testing for updating interface details"
admin_status: "UP"
vlan_id: 23
voice_vlan_id: 45
deployment_mode: "Deploy"
interface_name: ["GigabitEthernet1/0/11", FortyGigabitEthernet1/1/1]
clear_mac_address_table: True
- name: Export Device Details in a CSV file Interface details with IP Address
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
export_device_list:
password: "File_password"
operation_enum: "0"
parameters: ["componentName", "SerialNumber", "Last Sync Status"]
- name: Create Global User Defined with IP Address
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
add_user_defined_field:
- name: Test123
description: "Added first udf for testing"
value: "value123"
- name: Test321
description: "Added second udf for testing"
value: "value321"
- name: Resync Device with IP Addresses
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
device_resync: True
force_sync: False
- name: Reboot AP Devices with IP Addresses
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: merged
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
reboot_device: True
- name: Delete Provision/Unprovision Devices by IP Address
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log: False
dnac_log_level: "{{dnac_log_level}}"
state: deleted
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
clean_config: False
- name: Delete Global User Defined Field with name
cisco.dnac.inventory_intent:
dnac_host: "{{dnac_host}}"
dnac_username: "{{dnac_username}}"
dnac_password: "{{dnac_password}}"
dnac_verify: "{{dnac_verify}}"
dnac_port: "{{dnac_port}}"
dnac_version: "{{dnac_version}}"
dnac_debug: "{{dnac_debug}}"
dnac_log_level: "{{dnac_log_level}}"
dnac_log: False
state: deleted
config:
- ip_address_list: ["1.1.1.1", "2.2.2.2"]
add_user_defined_field:
- name: Test123
- name: Test321
"""
RETURN = r"""
dnac_response:
description: A dictionary or list with the response returned by the Cisco Catalyst Center Python SDK
returned: always
type: dict
sample: >
{
"response": {
"taskId": "string",
"url": "string"
},
"version": "string"
}
"""
# common approach when a module relies on optional dependencies that are not available during the validation process.
try:
import pyzipper
HAS_PYZIPPER = True
except ImportError:
HAS_PYZIPPER = False
pyzipper = None
import csv
import time
from datetime import datetime
from io import BytesIO, StringIO
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.cisco.dnac.plugins.module_utils.dnac import (
DnacBase,
validate_list_of_dicts,
)
# Defer this feature as API issue is there once it's fixed we will addresses it in upcoming release iac2.0
support_for_provisioning_wireless = False
class DnacDevice(DnacBase):
"""Class containing member attributes for Inventory intent module"""
def __init__(self, module):
super().__init__(module)
self.supported_states = ["merged", "deleted"]
def validate_input(self):
"""
Validate the fields provided in the playbook.
Checks the configuration provided in the playbook against a predefined specification
to ensure it adheres to the expected structure and data types.
Parameters:
self: The instance of the class containing the 'config' attribute to be validated.
Returns:
The method returns an instance of the class with updated attributes:
- self.msg: A message describing the validation result.
- self.status: The status of the validation (either 'success' or 'failed').
- self.validated_config: If successful, a validated version of the 'config' parameter.
Example:
To use this method, create an instance of the class and call 'validate_input' on it.
If the validation succeeds, 'self.status' will be 'success' and 'self.validated_config'
will contain the validated configuration. If it fails, 'self.status' will be 'failed', and
'self.msg' will describe the validation issues.
"""
temp_spec = {
'cli_transport': {'type': 'str'},
'compute_device': {'type': 'bool'},
'enable_password': {'type': 'str'},
'extended_discovery_info': {'type': 'str'},
'http_password': {'type': 'str'},
'http_port': {'type': 'str'},
'http_secure': {'type': 'bool'},
'http_username': {'type': 'str'},
'ip_address_list': {'type': 'list', 'elements': 'str'},
'hostname_list': {'type': 'list', 'elements': 'str'},
'serial_number_list': {'type': 'list', 'elements': 'str'},
'mac_address_list': {'type': 'list', 'elements': 'str'},
'netconf_port': {'type': 'str'},
'password': {'type': 'str'},
'snmp_auth_passphrase': {'type': 'str'},
'snmp_auth_protocol': {'default': "SHA", 'type': 'str'},
'snmp_mode': {'type': 'str'},
'snmp_priv_passphrase': {'type': 'str'},
'snmp_priv_protocol': {'type': 'str'},
'snmp_ro_community': {'type': 'str'},
'snmp_rw_community': {'type': 'str'},
'snmp_retry': {'default': 3, 'type': 'int'},
'snmp_timeout': {'default': 5, 'type': 'int'},
'snmp_username': {'type': 'str'},
'snmp_version': {'type': 'str'},
'update_mgmt_ipaddresslist': {'type': 'list', 'elements': 'dict'},
'username': {'type': 'str'},
'role': {'type': 'str'},
'device_resync': {'type': 'bool'},
'reboot_device': {'type': 'bool'},
'credential_update': {'type': 'bool'},
'force_sync': {'type': 'bool'},
'clean_config': {'type': 'bool'},
'add_user_defined_field': {
'type': 'list',
'elements': 'dict',
'name': {'type': 'str'},
'description': {'type': 'str'},
'value': {'type': 'str'},
},
'update_interface_details': {
'type': 'dict',
'description': {'type': 'str'},
'vlan_id': {'type': 'int'},
'voice_vlan_id': {'type': 'int'},
'interface_name': {'type': 'list', 'elements': 'str'},
'deployment_mode': {'default': 'Deploy', 'type': 'str'},
'clear_mac_address_table': {'default': False, 'type': 'bool'},
'admin_status': {'type': 'str'},
},
'export_device_list': {
'type': 'dict',
'password': {'type': 'str'},
'operation_enum': {'type': 'str'},
'parameters': {'type': 'list', 'elements': 'str'},
},
'provision_wired_device': {
'type': 'list',
'elements': 'dict',
'device_ip': {'type': 'str'},
'site_name': {'type': 'str'},
'resync_retry_count': {'default': 200, 'type': 'int'},
'resync_retry_interval': {'default': 2, 'type': 'int'},
}
}
# Validate device params
valid_temp, invalid_params = validate_list_of_dicts(
self.config, temp_spec
)
if invalid_params:
self.msg = "Invalid parameters in playbook: {0}".format(invalid_params)
self.log(self.msg, "ERROR")
self.status = "failed"
return self
self.validated_config = valid_temp
self.msg = "Successfully validated playbook configuration parameters using 'validate_input': {0}".format(str(valid_temp))
self.log(self.msg, "INFO")
self.status = "success"
return self
def get_device_ips_from_config_priority(self):
"""
Retrieve device IPs based on the configuration.
Parameters:
- self (object): An instance of a class used for interacting with Cisco Cisco Catalyst Center.
Returns:
list: A list containing device IPs.
Description:
This method retrieves device IPs based on the priority order specified in the configuration.
It first checks if device IPs are available. If not, it checks hostnames, serial numbers,
and MAC addresses in order and retrieves IPs based on availability.
If none of the information is available, an empty list is returned.
"""
# Retrieve device IPs from the configuration
device_ips = self.config[0].get("ip_address_list")
if device_ips:
return device_ips
# If device IPs are not available, check hostnames
device_hostnames = self.config[0].get("hostname_list")
if device_hostnames:
return self.get_device_ips_from_hostname(device_hostnames)
# If hostnames are not available, check serial numbers
device_serial_numbers = self.config[0].get("serial_number_list")
if device_serial_numbers:
return self.get_device_ips_from_serial_number(device_serial_numbers)
# If serial numbers are not available, check MAC addresses
device_mac_addresses = self.config[0].get("mac_address_list")
if device_mac_addresses:
return self.get_device_ips_from_mac_address(device_mac_addresses)
# If no information is available, return an empty list
return []
def device_exists_in_dnac(self):
"""
Check which devices already exists in Cisco Catalyst Center and return both device_exist and device_not_exist in dnac.
Parameters:
self (object): An instance of a class used for interacting with Cisco Cisco Catalyst Center.
Returns:
list: A list of devices that exist in Cisco Catalyst Center.
Description:
Queries Cisco Catalyst Center to check which devices are already present in Cisco Catalyst Center and store
its management IP address in the list of devices that exist.
Example:
To use this method, create an instance of the class and call 'device_exists_in_dnac' on it,
The method returns a list of management IP addressesfor devices that exist in Cisco Catalyst Center.
"""
device_in_dnac = []
try:
response = self.dnac._exec(
family="devices",
function='get_device_list',
)
except Exception as e:
error_message = "Error while fetching device from Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "CRITICAL")
raise Exception(error_message)
if response:
self.log("Received API response from 'get_device_list': {0}".format(str(response)), "DEBUG")
response = response.get("response")
for ip in response:
device_ip = ip["managementIpAddress"]
device_in_dnac.append(device_ip)
return device_in_dnac
def is_udf_exist(self, field_name):
"""
Check if a Global User Defined Field exists in Cisco Catalyst Center based on its name.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
field_name (str): The name of the Global User Defined Field.
Returns:
bool: True if the Global User Defined Field exists, False otherwise.
Description:
The function sends a request to Cisco Catalyst Center to retrieve all Global User Defined Fields
with the specified name. If matching field is found, the function returns True, indicating that
the field exists else returns False.
"""
response = self.dnac._exec(
family="devices",
function='get_all_user_defined_fields',
op_modifies=True,
params={"name": field_name},
)
self.log("Received API response from 'get_all_user_defined_fields': {0}".format(str(response)), "DEBUG")
udf = response.get("response")
if (len(udf) == 1):
return True
message = "Global User Defined Field with name '{0}' doesnot exist in Cisco Catalyst Center".format(field_name)
self.log(message, "INFO")
return False
def create_user_defined_field(self, udf):
"""
Create a Global User Defined Field in Cisco Catalyst Center based on the provided configuration.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
udf (dict): A dictionary having the payload for the creation of user defined field(UDF) in Cisco Catalyst Center.
Returns:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Description:
The function retrieves the configuration for adding a user-defined field from the configuration object,
sends the request to Cisco Catalyst Center to create the field, and logs the response.
"""
try:
response = self.dnac._exec(
family="devices",
function='create_user_defined_field',
op_modifies=True,
params=udf,
)
self.log("Received API response from 'create_user_defined_field': {0}".format(str(response)), "DEBUG")
response = response.get("response")
field_name = udf.get('name')
self.log("Global User Defined Field with name '{0}' created successfully".format(field_name), "INFO")
self.status = "success"
except Exception as e:
error_message = "Error while creating Global UDF(User Defined Field) in Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "ERROR")
return self
def add_field_to_devices(self, device_ids, udf):
"""
Add a Global user-defined field with specified details to a list of devices in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ids (list): A list of device IDs to which the user-defined field will be added.
udf (dict): A dictionary having the user defined field details including name and value.
Returns:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Description:
The function retrieves the details of the user-defined field from the configuration object,
including the field name and default value then iterates over list of device IDs, creating a payload for
each device and sending the request to Cisco Catalyst Center to add the user-defined field.
"""
# field_details = self.config[0].get('add_user_defined_field')
field_name = udf.get('name')
field_value = udf.get('value', '1')
for device_id in device_ids:
payload = {}
payload['name'] = field_name
payload['value'] = field_value
udf_param_dict = {
'payload': [payload],
'device_id': device_id
}
try:
response = self.dnac._exec(
family="devices",
function='add_user_defined_field_to_device',
op_modifies=True,
params=udf_param_dict,
)
self.log("Received API response from 'add_user_defined_field_to_device': {0}".format(str(response)), "DEBUG")
response = response.get("response")
self.status = "success"
self.result['changed'] = True
except Exception as e:
self.status = "failed"
error_message = "Error while adding Global UDF to device in Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "ERROR")
self.result['changed'] = False
return self
def trigger_export_api(self, payload_params):
"""
Triggers the export API to generate a CSV file containing device details based on the given payload parameters.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
payload_params (dict): A dictionary containing parameters required for the export API.
Returns:
dict: The response from the export API, including information about the task and file ID.
If the export is successful, the CSV file can be downloaded using the file ID.
Description:
The function initiates the export API in Cisco Catalyst Center to generate a CSV file containing detailed information
about devices.The response from the API includes task details and a file ID.
"""
response = self.dnac._exec(
family="devices",
function='export_device_list',
op_modifies=True,
params=payload_params,
)
self.log("Received API response from 'export_device_list': {0}".format(str(response)), "DEBUG")
response = response.get("response")
task_id = response.get("taskId")
while True:
execution_details = self.get_task_details(task_id)
if execution_details.get("additionalStatusURL"):
file_id = execution_details.get("additionalStatusURL").split("/")[-1]
break
elif execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "Could not get the File ID because of {0} so can't export device details in csv file".format(failure_reason)
else:
self.msg = "Could not get the File ID so can't export device details in csv file"
self.log(self.msg, "ERROR")
return response
# With this File ID call the Download File by FileID API and process the response
response = self.dnac._exec(
family="file",
function='download_a_file_by_fileid',
op_modifies=True,
params={"file_id": file_id},
)
self.log("Received API response from 'download_a_file_by_fileid': {0}".format(str(response)), "DEBUG")
return response
def decrypt_and_read_csv(self, response, password):
"""
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
response (requests.Response): HTTP response object containing the encrypted CSV file.
password (str): Password used for decrypting the CSV file.
Returns:
csv.DictReader: A CSV reader object for the decrypted content, allowing iteration over rows as dictionaries.
Description:
Decrypts and reads a CSV-like file from the given HTTP response using the provided password.
"""
zip_data = BytesIO(response.data)
if not HAS_PYZIPPER:
self.msg = "pyzipper is required for this module. Install pyzipper to use this functionality."
self.log(self.msg, "CRITICAL")
self.status = "failed"
return self
snmp_protocol = self.config[0].get('snmp_priv_protocol', 'AES128')
encryption_dict = {
'AES128': 'pyzipper.WZ_AES128',
'AES192': 'pyzipper.WZ_AES192',
'AES256': 'pyzipper.WZ_AES',
'CISCOAES128': 'pyzipper.WZ_AES128',
'CISCOAES192': 'pyzipper.WZ_AES192',
'CISCOAES256': 'pyzipper.WZ_AES'
}
try:
encryption_method = encryption_dict.get(snmp_protocol)
except Exception as e:
self.log("Given SNMP protcol '{0}' not present".format(snmp_protocol), "WARNING")
if not encryption_method:
self.msg = "Invalid SNMP protocol '{0}' specified for encryption.".format(snmp_protocol)
self.log(self.msg, "ERROR")
self.status = "failed"
return self
# Create a PyZipper object with the password
with pyzipper.AESZipFile(zip_data, 'r', compression=pyzipper.ZIP_LZMA, encryption=encryption_method) as zip_ref:
# Assuming there is a single file in the zip archive
file_name = zip_ref.namelist()[0]
# Extract the content of the file with the provided password
file_content_binary = zip_ref.read(file_name, pwd=password.encode('utf-8'))
# Now 'file_content_binary' contains the binary content of the decrypted file
# Since the content is text, so we can decode it
file_content_text = file_content_binary.decode('utf-8')
# Now 'file_content_text' contains the text content of the decrypted file
self.log("Text content of decrypted file: {0}".format(file_content_text), "DEBUG")
# Parse the CSV-like string into a list of dictionaries
csv_reader = csv.DictReader(StringIO(file_content_text))
return csv_reader
def export_device_details(self):
"""
Export device details from Cisco Catalyst Center into a CSV file.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Returns:
self (object): An instance of the class with updated result, status, and log.
Description:
This function exports device details from Cisco Catalyst Center based on the provided IP addresses in the configuration.
It retrieves the device UUIDs, calls the export device list API, and downloads the exported data of both device details and
and device credentials with an encrtypted zip file with password into CSV format.
The CSV data is then parsed and written to a file.
"""
device_ips = self.get_device_ips_from_config_priority()
if not device_ips:
self.status = "failed"
self.msg = "Cannot export device details as no devices are specified in the playbook"
self.log(self.msg, "ERROR")
return self
try:
device_uuids = self.get_device_ids(device_ips)
if not device_uuids:
self.status = "failed"
self.result['changed'] = False
self.msg = "Could not find device UUIDs for exporting device details"
self.log(self.msg, "ERROR")
return self
# Now all device UUID get collected so call the export device list API
export_device_list = self.config[0].get('export_device_list')
password = export_device_list.get("password")
if not self.is_valid_password(password):
self.status = "failed"
detailed_msg = """Invalid password. Min password length is 8 and it should contain atleast one lower case letter,
one uppercase letter, one digit and one special characters from -=\\;,./~!@#$%^&*()_+{}[]|:?"""
formatted_msg = ' '.join(line.strip() for line in detailed_msg.splitlines())
self.msg = formatted_msg
self.log(formatted_msg, "INFO")
return self
payload_params = {
"deviceUuids": device_uuids,
"password": password,
"operationEnum": export_device_list.get("operation_enum", "0"),
"parameters": export_device_list.get("parameters")
}
response = self.trigger_export_api(payload_params)
self.check_return_status()
if payload_params["operationEnum"] == "0":
temp_file_name = response.filename
output_file_name = temp_file_name.split(".")[0] + ".csv"
csv_reader = self.decrypt_and_read_csv(response, password)
self.check_return_status()
else:
decoded_resp = response.data.decode(encoding='utf-8')
self.log("Decoded response of Export Device Credential file: {0}".format(str(decoded_resp)), "DEBUG")
# Parse the CSV-like string into a list of dictionaries
csv_reader = csv.DictReader(StringIO(decoded_resp))
current_date = datetime.now()
formatted_date = current_date.strftime("%m-%d-%Y")
output_file_name = "devices-" + str(formatted_date) + ".csv"
device_data = []
for row in csv_reader:
device_data.append(row)
# Write the data to a CSV file
with open(output_file_name, 'w', newline='') as csv_file:
fieldnames = device_data[0].keys()
csv_writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
csv_writer.writeheader()
csv_writer.writerows(device_data)
self.msg = "Device Details Exported Successfully to the CSV file: {0}".format(output_file_name)
self.log(self.msg, "INFO")
self.status = "success"
self.result['changed'] = True
self.result['response'] = self.msg
except Exception as e:
self.msg = "Error while exporting device details into CSV file for device(s): '{0}'".format(str(device_ips))
self.log(self.msg, "ERROR")
self.status = "failed"
return self
def get_ap_devices(self, device_ips):
"""
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ip (str): The management IP address of the device for which the response is to be retrieved.
Returns:
list: A list containing Access Point device IP's obtained from the Cisco Catalyst Center.
Description:
This method communicates with Cisco Catalyst Center to retrieve the details of a device with the specified
management IP address and check if device family matched to Unified AP. It executes the 'get_device_list'
API call with the provided device IP address, logs the response, and returns list containing ap device ips.
"""
ap_device_list = []
for device_ip in device_ips:
try:
response = self.dnac._exec(
family="devices",
function='get_device_list',
op_modifies=True,
params={"managementIpAddress": device_ip}
)
response = response.get('response', [])
if response and response[0].get('family', '') == "Unified AP":
ap_device_list.append(device_ip)
except Exception as e:
error_message = "Error while getting the response of device from Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "CRITICAL")
raise Exception(error_message)
return ap_device_list
def resync_devices(self):
"""
Resync devices in Cisco Catalyst Center.
This function performs the Resync operation for the devices specified in the playbook.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Returns:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Description:
The function expects the following parameters in the configuration:
- "ip_address_list": List of device IP addresses to be resynced.
- "force_sync": (Optional) Whether to force sync the devices. Defaults to "False".
"""
# Code for triggers the resync operation using the retrieved device IDs and force sync parameter.
device_ips = self.get_device_ips_from_config_priority()
input_device_ips = device_ips.copy()
device_in_dnac = self.device_exists_in_dnac()
for device_ip in input_device_ips:
if device_ip not in device_in_dnac:
input_device_ips.remove(device_ip)
ap_devices = self.get_ap_devices(input_device_ips)
self.log("AP Devices from the playbook input are: {0}".format(str(ap_devices)), "INFO")
if ap_devices:
for ap_ip in ap_devices:
input_device_ips.remove(ap_ip)
self.log("Following devices {0} are AP, so can't perform resync operation.".format(str(ap_devices)), "WARNING")
if not input_device_ips:
self.msg = "Cannot perform the Resync operation as the device(s) with IP(s) {0} are not present in Cisco Catalyst Center".format(str(device_ips))
self.status = "success"
self.result['changed'] = False
self.result['response'] = self.msg
self.log(self.msg, "WARNING")
return self
device_ids = self.get_device_ids(input_device_ips)
try:
force_sync = self.config[0].get("force_sync", False)
resync_param_dict = {
'payload': device_ids,
'force_sync': force_sync
}
response = self.dnac._exec(
family="devices",
function='sync_devices_using_forcesync',
op_modifies=True,
params=resync_param_dict,
)
self.log("Received API response from 'sync_devices_using_forcesync': {0}".format(str(response)), "DEBUG")
if response and isinstance(response, dict):
task_id = response.get('response').get('taskId')
while True:
execution_details = self.get_task_details(task_id)
if 'Synced' in execution_details.get("progress"):
self.status = "success"
self.result['changed'] = True
self.result['response'] = execution_details
self.msg = "Devices have been successfully resynced. Devices resynced: {0}".format(str(input_device_ips))
self.log(self.msg, "INFO")
break
elif execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "Device resynced get failed because of {0}".format(failure_reason)
else:
self.msg = "Device resynced get failed."
self.log(self.msg, "ERROR")
break
except Exception as e:
self.status = "failed"
error_message = "Error while resyncing device in Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "ERROR")
return self
def reboot_access_points(self):
"""
Reboot access points in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Returns:
self (object): An instance of the class with updated result, status, and log.
Description:
This function performs a reboot operation on access points in Cisco Catalyst Center based on the provided IP addresses
in the configuration. It retrieves the AP devices' MAC addresses, calls the reboot access points API, and monitors
the progress of the reboot operation.
"""
device_ips = self.get_device_ips_from_config_priority()
input_device_ips = device_ips.copy()
if input_device_ips:
ap_devices = self.get_ap_devices(input_device_ips)
self.log("AP Devices from the playbook input are: {0}".format(str(ap_devices)), "INFO")
for device_ip in input_device_ips:
if device_ip not in ap_devices:
input_device_ips.remove(device_ip)
if not input_device_ips:
self.msg = "No AP Devices IP given in the playbook so can't perform reboot operation"
self.status = "success"
self.result['changed'] = False
self.result['response'] = self.msg
self.log(self.msg, "WARNING")
return self
# Get and store the apEthernetMacAddress of given devices
ap_mac_address_list = []
for device_ip in input_device_ips:
response = self.dnac._exec(
family="devices",
function='get_device_list',
op_modifies=True,
params={"managementIpAddress": device_ip}
)
response = response.get('response')
if not response:
continue
response = response[0]
ap_mac_address = response.get('apEthernetMacAddress')
if ap_mac_address is not None:
ap_mac_address_list.append(ap_mac_address)
if not ap_mac_address_list:
self.status = "success"
self.result['changed'] = False
self.msg = "Cannot find the AP devices for rebooting"
self.result['response'] = self.msg
self.log(self.msg, "INFO")
return self
# Now call the Reboot Access Point API
reboot_params = {
"apMacAddresses": ap_mac_address_list
}
response = self.dnac._exec(
family="wireless",
function='reboot_access_points',
op_modifies=True,
params=reboot_params,
)
self.log(str(response))
if response and isinstance(response, dict):
task_id = response.get('response').get('taskId')
while True:
execution_details = self.get_task_details(task_id)
if 'url' in execution_details.get("progress"):
self.status = "success"
self.result['changed'] = True
self.result['response'] = execution_details
self.msg = "AP Device(s) {0} successfully rebooted!".format(str(input_device_ips))
self.log(self.msg, "INFO")
break
elif execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "AP Device Rebooting get failed because of {0}".format(failure_reason)
else:
self.msg = "AP Device Rebooting get failed"
self.log(self.msg, "ERROR")
break
return self
def handle_successful_provisioning(self, device_ip, execution_details, device_type):
"""
Handle successful provisioning of Wired/Wireless device.
Parameters:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
- device_ip (str): The IP address of the provisioned device.
- execution_details (str): Details of the provisioning execution.
- device_type (str): The type or category of the provisioned device(Wired/Wireless).
Return:
None
Description:
This method updates the status, result, and logs the successful provisioning of a device.
"""
self.status = "success"
self.result['changed'] = True
self.result['response'] = execution_details
self.log("{0} Device {1} provisioned successfully!!".format(device_type, device_ip), "INFO")
def handle_failed_provisioning(self, device_ip, execution_details, device_type):
"""
Handle failed provisioning of Wired/Wireless device.
Parameters:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
- device_ip (str): The IP address of the device that failed provisioning.
- execution_details (dict): Details of the failed provisioning execution in key "failureReason" indicating reason for failure.
- device_type (str): The type or category of the provisioned device(Wired/Wireless).
Return:
None
Description:
This method updates the status, result, and logs the failure of provisioning for a device.
"""
self.status = "failed"
failure_reason = execution_details.get("failureReason", "Unknown failure reason")
self.msg = "{0} Device Provisioning failed for {1} because of {2}".format(device_type, device_ip, failure_reason)
self.log(self.msg, "WARNING")
def handle_provisioning_exception(self, device_ip, exception, device_type):
"""
Handle an exception during the provisioning process of Wired/Wireless device..
Parameters:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
- device_ip (str): The IP address of the device involved in provisioning.
- exception (Exception): The exception raised during provisioning.
- device_type (str): The type or category of the provisioned device(Wired/Wireless).
Return:
None
Description:
This method logs an error message indicating an exception occurred during the provisioning process for a device.
"""
error_message = "Error while Provisioning the {0} device {1} in Cisco Catalyst Center: {2}".format(device_type, device_ip, str(exception))
self.log(error_message, "ERROR")
def handle_all_already_provisioned(self, device_ips, device_type):
"""
Handle successful provisioning for all devices(Wired/Wireless).
Parameters:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
- device_type (str): The type or category of the provisioned device(Wired/Wireless).
Return:
None
Description:
This method updates the status, result, and logs the successful provisioning for all devices(Wired/Wireless).
"""
self.status = "success"
self.msg = "All the {0} Devices '{1}' given in the playbook are already Provisioned".format(device_type, str(device_ips))
self.log(self.msg, "INFO")
self.result['response'] = self.msg
self.result['changed'] = False
def handle_all_provisioned(self, device_type):
"""
Handle successful provisioning for all devices(Wired/Wireless).
Parameters:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
- device_type (str): The type or category of the provisioned devices(Wired/Wireless).
Return:
None
Description:
This method updates the status, result, and logs the successful provisioning for all devices(Wired/Wireless).
"""
self.status = "success"
self.result['changed'] = True
self.log("All {0} Devices provisioned successfully!!".format(device_type), "INFO")
def handle_all_failed_provision(self, device_type):
"""
Handle failure of provisioning for all devices(Wired/Wireless).
Parameters:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
- device_type (str): The type or category of the devices(Wired/Wireless).
Return:
None
Description:
This method updates the status and logs a failure message indicating that
provisioning failed for all devices of a specific type.
"""
self.status = "failed"
self.msg = "{0} Device Provisioning failed for all devices".format(device_type)
self.log(self.msg, "INFO")
def handle_partially_provisioned(self, provision_count, device_type):
"""
Handle partial success in provisioning for devices(Wired/Wireless).
Parameters:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
- provision_count (int): The count of devices that were successfully provisioned.
- device_type (str): The type or category of the provisioned devices(Wired/Wireless).
Return:
None
Description:
This method updates the status, result, and logs a partial success message indicating that provisioning was successful
for a certain number of devices(Wired/Wireless).
"""
self.status = "success"
self.result['changed'] = True
self.log("{0} Devices provisioned successfully partially for {1} devices".format(device_type, provision_count), "INFO")
def provisioned_wired_device(self):
"""
Provision wired devices in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Returns:
self (object): An instance of the class with updated result, status, and log.
Description:
This function provisions wired devices in Cisco Catalyst Center based on the configuration provided.
It retrieves the site name and IP addresses of the devices from the list of configuration,
attempts to provision each device with site, and monitors the provisioning process.
"""
provision_wired_list = self.config[0]['provision_wired_device']
total_devices_to_provisioned = len(provision_wired_list)
device_ip_list = []
provision_count, already_provision_count = 0, 0
for prov_dict in provision_wired_list:
managed_flag = False
device_ip = prov_dict['device_ip']
device_ip_list.append(device_ip)
site_name = prov_dict['site_name']
device_type = "Wired"
resync_retry_count = prov_dict.get("resync_retry_count", 200)
# This resync retry interval will be in seconds which will check device status at given interval
resync_retry_interval = prov_dict.get("resync_retry_interval", 2)
if not site_name or not device_ip:
self.status = "failed"
self.msg = "Site and Device IP are required for Provisioning of Wired Devices."
self.log(self.msg, "ERROR")
self.result['response'] = self.msg
return self
provision_wired_params = {
'deviceManagementIpAddress': device_ip,
'siteNameHierarchy': site_name
}
# Check the provisioning status of device
device_prov_status = self.get_provision_wired_device(device_ip)
if device_prov_status == 2:
self.status = "success"
already_provision_count += 1
self.result['changed'] = False
self.msg = "Device '{0}' is already provisioned in the Cisco Catalyst Center".format(device_ip)
self.log(self.msg, "INFO")
continue
if device_prov_status == 3:
self.status = "failed"
error_msg = "Cannot do Provisioning for device {0}.".format(device_ip)
self.log(error_msg, "ERROR")
continue
# Check till device comes into managed state
while resync_retry_count:
response = self.get_device_response(device_ip)
self.log("Device is in {0} state waiting for Managed State.".format(response['managementState']), "DEBUG")
if (
response.get('managementState') == "Managed"
and response.get('collectionStatus') == "Managed"
and response.get("hostname")
):
msg = """Device '{0}' comes to managed state and ready for provisioning with the resync_retry_count
'{1}' left having resync interval of {2} seconds""".format(device_ip, resync_retry_count, resync_retry_interval)
self.log(msg, "INFO")
managed_flag = True
break
if response.get('collectionStatus') == "Partial Collection Failure" or response.get('collectionStatus') == "Could Not Synchronize":
device_status = response.get('collectionStatus')
msg = """Device '{0}' comes to '{1}' state and never goes for provisioning with the resync_retry_count
'{2}' left having resync interval of {3} seconds""".format(device_ip, device_status, resync_retry_count, resync_retry_interval)
self.log(msg, "INFO")
managed_flag = False
break
time.sleep(resync_retry_interval)
resync_retry_count = resync_retry_count - 1
if not managed_flag:
self.log("""Device {0} is not transitioning to the managed state, so provisioning operation cannot
be performed.""".format(device_ip), "WARNING")
continue
try:
response = self.dnac._exec(
family="sda",
function='provision_wired_device',
op_modifies=True,
params=provision_wired_params,
)
if response.get("status") == "failed":
description = response.get("description")
error_msg = "Cannot do Provisioning for device {0} beacuse of {1}".format(device_ip, description)
self.log(error_msg, "ERROR")
continue
task_id = response.get("taskId")
while True:
execution_details = self.get_task_details(task_id)
progress = execution_details.get("progress")
if 'TASK_PROVISION' in progress:
self.handle_successful_provisioning(device_ip, execution_details, device_type)
provision_count += 1
break
elif execution_details.get("isError"):
self.handle_failed_provisioning(device_ip, execution_details, device_type)
break
except Exception as e:
# Not returning from here as there might be possiblity that for some devices it comes into exception
# but for others it gets provision successfully or If some devices are already provsioned
self.handle_provisioning_exception(device_ip, e, device_type)
# Check If all the devices are already provsioned, return from here only
if already_provision_count == total_devices_to_provisioned:
self.handle_all_already_provisioned(device_ip_list, device_type)
elif provision_count == total_devices_to_provisioned:
self.handle_all_provisioned(device_type)
elif provision_count == 0:
self.handle_all_failed_provision(device_type)
else:
self.handle_partially_provisioned(provision_count, device_type)
return self
def get_wireless_param(self, prov_dict):
"""
Get wireless provisioning parameters for a device.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
prov_dict (dict): A dictionary containing configuration parameters for wireless provisioning.
Returns:
wireless_param (list of dict): A list containing a dictionary with wireless provisioning parameters.
Description:
This function constructs a list containing a dictionary with wireless provisioning parameters based on the
configuration provided in the playbook. It validates the managed AP locations, ensuring they are of type "floor."
The function then queries Cisco Catalyst Center to get network device details using the provided device IP.
If the device is not found, the function returns the class instance with appropriate status and log messages and
returns the wireless provisioning parameters containing site information, managed AP
locations, dynamic interfaces, and device name.
"""
try:
device_ip_address = prov_dict['device_ip']
site_name = prov_dict['site_name']
wireless_param = [
{
'site': site_name,
'managedAPLocations': prov_dict['managed_ap_locations'],
}
]
for ap_loc in wireless_param[0]["managedAPLocations"]:
if self.get_site_type(site_name=ap_loc) != "floor":
self.status = "failed"
self.msg = "Managed AP Location must be a floor"
self.log(self.msg, "ERROR")
return self
wireless_param[0]["dynamicInterfaces"] = []
for interface in prov_dict.get("dynamic_interfaces"):
interface_dict = {
"interfaceIPAddress": interface.get("interface_ip_address"),
"interfaceNetmaskInCIDR": interface.get("interface_netmask_in_cidr"),
"interfaceGateway": interface.get("interface_gateway"),
"lagOrPortNumber": interface.get("lag_or_port_number"),
"vlanId": interface.get("vlan_id"),
"interfaceName": interface.get("interface_name")
}
wireless_param[0]["dynamicInterfaces"].append(interface_dict)
response = self.dnac_apply['exec'](
family="devices",
function='get_network_device_by_ip',
params={"ip_address": device_ip_address}
)
if not response:
self.status = "failed"
self.msg = "Device Host name is not present in the Cisco Catalyst Center"
self.log(self.msg, "INFO")
return self
response = response.get("response")
wireless_param[0]["deviceName"] = response.get("hostname")
self.wireless_param = wireless_param
self.status = "success"
self.log("Successfully collected all the parameters required for Wireless Provisioning", "DEBUG")
except Exception as e:
self.msg = """An exception occured while fetching the details for wireless provisioning of
device '{0}' due to - {1}""".format(device_ip_address, str(e))
self.log(self.msg, "ERROR")
return self
def get_site_type(self, site_name):
"""
Get the type of a site in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
site_name (str): The name of the site for which to retrieve the type.
Returns:
site_type (str or None): The type of the specified site, or None if the site is not found.
Description:
This function queries Cisco Catalyst Center to retrieve the type of a specified site. It uses the
get_site API with the provided site name, extracts the site type from the response, and returns it.
If the specified site is not found, the function returns None, and an appropriate log message is generated.
"""
try:
site_type = None
response = self.dnac_apply['exec'](
family="sites",
function='get_site',
params={"name": site_name},
)
if not response:
self.msg = "Site '{0}' not found".format(site_name)
self.log(self.msg, "INFO")
return site_type
self.log("Received API response from 'get_site': {0}".format(str(response)), "DEBUG")
site = response.get("response")
site_additional_info = site[0].get("additionalInfo")
for item in site_additional_info:
if item["nameSpace"] == "Location":
site_type = item.get("attributes").get("type")
except Exception as e:
self.msg = "Error while fetching the site '{0}' and the specified site was not found in Cisco Catalyst Center.".format(site_name)
self.module.fail_json(msg=self.msg, response=[self.msg])
return site_type
def provisioned_wireless_devices(self):
"""
Provision Wireless devices in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Returns:
self (object): An instance of the class with updated result, status, and log.
Description:
This function performs wireless provisioning for the provided list of device IP addresses.
It iterates through each device, retrieves provisioning parameters using the get_wireless_param function,
and then calls the Cisco Catalyst Center API for wireless provisioning. If all devices are already provisioned,
it returns success with a relevant message.
"""
provision_count, already_provision_count = 0, 0
device_type = "Wireless"
device_ip_list = []
provision_wireless_list = self.config[0]['provision_wireless_device']
for prov_dict in provision_wireless_list:
try:
# Collect the device parameters from the playbook to perform wireless provisioing
self.get_wireless_param(prov_dict).check_return_status()
device_ip = prov_dict['device_ip']
device_ip_list.append(device_ip)
provisioning_params = self.wireless_param
resync_retry_count = prov_dict.get("resync_retry_count", 200)
# This resync retry interval will be in seconds which will check device status at given interval
resync_retry_interval = prov_dict.get("resync_retry_interval", 2)
managed_flag = True
# Check till device comes into managed state
while resync_retry_count:
response = self.get_device_response(device_ip)
self.log("Device is in {0} state waiting for Managed State.".format(response['managementState']), "DEBUG")
if (
response.get('managementState') == "Managed"
and response.get('collectionStatus') == "Managed"
and response.get("hostname")
):
msg = """Device '{0}' comes to managed state and ready for provisioning with the resync_retry_count
'{1}' left having resync interval of {2} seconds""".format(device_ip, resync_retry_count, resync_retry_interval)
self.log(msg, "INFO")
managed_flag = True
break
if response.get('collectionStatus') == "Partial Collection Failure" or response.get('collectionStatus') == "Could Not Synchronize":
device_status = response.get('collectionStatus')
msg = """Device '{0}' comes to '{1}' state and never goes for provisioning with the resync_retry_count
'{2}' left having resync interval of {3} seconds""".format(device_ip, device_status, resync_retry_count, resync_retry_interval)
self.log(msg, "INFO")
managed_flag = False
break
time.sleep(resync_retry_interval)
resync_retry_count = resync_retry_count - 1
if not managed_flag:
self.log("""Device {0} is not transitioning to the managed state, so provisioning operation cannot
be performed.""".format(device_ip), "WARNING")
continue
# Now we have provisioning_param so we can do wireless provisioning
response = self.dnac_apply['exec'](
family="wireless",
function="provision",
op_modifies=True,
params=provisioning_params,
)
if response.get("status") == "failed":
description = response.get("description")
error_msg = "Cannot do Provisioning for Wireless device {0} beacuse of {1}".format(device_ip, description)
self.log(error_msg, "ERROR")
continue
task_id = response.get("taskId")
while True:
execution_details = self.get_task_details(task_id)
progress = execution_details.get("progress")
if 'TASK_PROVISION' in progress:
self.handle_successful_provisioning(device_ip, execution_details, device_type)
provision_count += 1
break
elif execution_details.get("isError"):
self.handle_failed_provisioning(device_ip, execution_details, device_type)
break
except Exception as e:
# Not returning from here as there might be possiblity that for some devices it comes into exception
# but for others it gets provision successfully or If some devices are already provsioned
self.handle_provisioning_exception(device_ip, e, device_type)
if "already provisioned" in str(e):
self.msg = "Device '{0}' already provisioned".format(device_ip)
self.log(self.msg, "INFO")
already_provision_count += 1
# Check If all the devices are already provsioned, return from here only
if already_provision_count == len(device_ip_list):
self.handle_all_already_provisioned(device_ip_list, device_type)
elif provision_count == len(device_ip_list):
self.handle_all_provisioned(device_type)
elif provision_count == 0:
self.handle_all_failed_provision(device_type)
else:
self.handle_partially_provisioned(provision_count, device_type)
return self
def get_udf_id(self, field_name):
"""
Get the ID of a Global User Defined Field in Cisco Catalyst Center based on its name.
Parameters:
self (object): An instance of a class used for interacting with Cisco Cisco Catalyst Center.
field_name (str): The name of the Global User Defined Field.
Returns:
str: The ID of the Global User Defined Field.
Description:
The function sends a request to Cisco Catalyst Center to retrieve all Global User Defined Fields
with the specified name and extracts the ID of the first matching field.If successful, it returns
the ID else returns None.
"""
try:
udf_id = None
response = self.dnac._exec(
family="devices",
function='get_all_user_defined_fields',
op_modifies=True,
params={"name": field_name},
)
self.log("Received API response from 'get_all_user_defined_fields': {0}".format(str(response)), "DEBUG")
udf = response.get("response")
if udf:
udf_id = udf[0].get("id")
except Exception as e:
error_message = "Exception occurred while getting Global User Defined Fields(UDF) ID from Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "ERROR")
return udf_id
def mandatory_parameter(self, device_to_add_in_ccc):
"""
Check for and validate mandatory parameters for adding network devices in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Cisco Catalyst Center.
device_to_add_in_ccc(list): List to device ip addresses to be added in Cisco Catalyst Center.
Returns:
dict: The input `config` dictionary if all mandatory parameters are present.
Description:
It will check the mandatory parameters for adding the devices in Cisco Catalyst Center.
"""
device_type = self.config[0].get("type", "NETWORK_DEVICE")
params_dict = {
"NETWORK_DEVICE": ["ip_address_list", "password", "username"],
"COMPUTE_DEVICE": ["ip_address_list", "http_username", "http_password", "http_port"],
"MERAKI_DASHBOARD": ["http_password"],
"FIREPOWER_MANAGEMENT_SYSTEM": ["ip_address_list", "http_username", "http_password"],
"THIRD_PARTY_DEVICE": ["ip_address_list"]
}
params_list = params_dict.get(device_type, [])
mandatory_params_absent = []
for param in params_list:
if param not in self.config[0]:
mandatory_params_absent.append(param)
if mandatory_params_absent:
self.status = "failed"
self.msg = "Required parameters {0} for adding devices '{1}' are not present".format(str(mandatory_params_absent), str(device_to_add_in_ccc))
self.result['msg'] = self.msg
self.log(self.msg, "ERROR")
else:
self.status = "success"
self.msg = "Required parameters for adding the devices '{0}' to inventory are present.".format(str(device_to_add_in_ccc))
self.log(self.msg, "INFO")
return self
def get_have(self, config):
"""
Retrieve and check device information with Cisco Catalyst Center to determine if devices already exist.
Parameters:
self (object): An instance of a class used for interacting with Cisco Cisco Catalyst Center.
config (dict): A dictionary containing the configuration details of devices to be checked.
Returns:
dict: A dictionary containing information about the devices in the playbook, devices that exist in
Cisco Catalyst Center, and devices that are not present in Cisco Catalyst Center.
Description:
This function checks the specified devices in the playbook against the devices existing in Cisco Catalyst Center with following keys:
- "want_device": A list of devices specified in the playbook.
- "device_in_dnac": A list of devices that already exist in Cisco Catalyst Center.
- "device_not_in_dnac": A list of devices that are not present in Cisco Catalyst Center.
"""
have = {}
want_device = self.get_device_ips_from_config_priority()
# Get the list of device that are present in Cisco Catalyst Center
device_in_dnac = self.device_exists_in_dnac()
device_not_in_dnac, devices_in_playbook = [], []
for ip in want_device:
devices_in_playbook.append(ip)
if ip not in device_in_dnac:
device_not_in_dnac.append(ip)
if self.config[0].get('provision_wired_device'):
provision_wired_list = self.config[0].get('provision_wired_device')
for prov_dict in provision_wired_list:
device_ip_address = prov_dict['device_ip']
if device_ip_address not in want_device:
devices_in_playbook.append(device_ip_address)
if device_ip_address not in device_in_dnac:
device_not_in_dnac.append(device_ip_address)
if support_for_provisioning_wireless:
if self.config[0].get('provision_wireless_device'):
provision_wireless_list = self.config[0].get('provision_wireless_device')
for prov_dict in provision_wireless_list:
device_ip_address = prov_dict['device_ip']
if device_ip_address not in want_device and device_ip_address not in devices_in_playbook:
devices_in_playbook.append(device_ip_address)
if device_ip_address not in device_in_dnac and device_ip_address not in device_not_in_dnac:
device_not_in_dnac.append(device_ip_address)
self.log("Device(s) {0} exists in Cisco Catalyst Center".format(str(device_in_dnac)), "INFO")
have["want_device"] = want_device
have["device_in_dnac"] = device_in_dnac
have["device_not_in_dnac"] = device_not_in_dnac
have["devices_in_playbook"] = devices_in_playbook
self.have = have
self.log("Current State (have): {0}".format(str(self.have)), "INFO")
return self
def get_device_params(self, params):
"""
Extract and store device parameters from the playbook for device processing in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
params (dict): A dictionary containing device parameters retrieved from the playbook.
Returns:
dict: A dictionary containing the extracted device parameters.
Description:
This function will extract and store parameters in dictionary for adding, updating, editing, or deleting devices Cisco Catalyst Center.
"""
device_param = {
"cliTransport": params.get("cli_transport"),
"enablePassword": params.get("enable_password"),
"password": params.get("password"),
"ipAddress": params.get("ip_address_list"),
"snmpAuthPassphrase": params.get("snmp_auth_passphrase"),
"snmpAuthProtocol": params.get("snmp_auth_protocol"),
"snmpMode": params.get("snmp_mode"),
"snmpPrivPassphrase": params.get("snmp_priv_passphrase"),
"snmpPrivProtocol": params.get("snmp_priv_protocol"),
"snmpROCommunity": params.get("snmp_ro_community"),
"snmpRWCommunity": params.get("snmp_rw_community"),
"snmpRetry": params.get("snmp_retry"),
"snmpTimeout": params.get("snmp_timeout"),
"snmpUserName": params.get("snmp_username"),
"userName": params.get("username"),
"computeDevice": params.get("compute_device"),
"extendedDiscoveryInfo": params.get("extended_discovery_info"),
"httpPassword": params.get("http_password"),
"httpPort": params.get("http_port"),
"httpSecure": params.get("http_secure"),
"httpUserName": params.get("http_username"),
"netconfPort": params.get("netconf_port"),
"snmpVersion": params.get("snmp_version"),
"type": params.get("type"),
"updateMgmtIPaddressList": params.get("update_mgmt_ipaddresslist"),
"forceSync": params.get("force_sync"),
"cleanConfig": params.get("clean_config")
}
if device_param.get("updateMgmtIPaddressList"):
device_mngmt_dict = device_param.get("updateMgmtIPaddressList")[0]
device_param["updateMgmtIPaddressList"][0] = {}
device_param["updateMgmtIPaddressList"][0].update(
{
"existMgmtIpAddress": device_mngmt_dict.get("exist_mgmt_ipaddress"),
"newMgmtIpAddress": device_mngmt_dict.get("new_mgmt_ipaddress")
})
return device_param
def get_device_ids(self, device_ips):
"""
Get the list of unique device IDs for list of specified management IP addresses of devices in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ips (list): The management IP addresses of devices for which you want to retrieve the device IDs.
Returns:
list: The list of unique device IDs for the specified devices.
Description:
Queries Cisco Catalyst Center to retrieve the unique device ID associated with a device having the specified
IP address. If the device is not found in Cisco Catalyst Center, then print the log message with error severity.
"""
device_ids = []
for device_ip in device_ips:
try:
response = self.dnac._exec(
family="devices",
function='get_device_list',
op_modifies=True,
params={"managementIpAddress": device_ip}
)
if response:
self.log("Received API response from 'get_device_list': {0}".format(str(response)), "DEBUG")
response = response.get("response")
if not response:
continue
device_id = response[0]["id"]
device_ids.append(device_id)
except Exception as e:
error_message = "Error while fetching device '{0}' from Cisco Catalyst Center: {1}".format(device_ip, str(e))
self.log(error_message, "ERROR")
return device_ids
def get_device_ips_from_hostname(self, hostname_list):
"""
Get the list of unique device IPs for list of specified hostnames of devices in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
hostname_list (list): The hostnames of devices for which you want to retrieve the device IPs.
Returns:
list: The list of unique device IPs for the specified devices hostname list.
Description:
Queries Cisco Catalyst Center to retrieve the unique device IP's associated with a device having the specified
list of hostnames. If a device is not found in Cisco Catalyst Center, an error log message is printed.
"""
device_ips = []
for hostname in hostname_list:
try:
response = self.dnac._exec(
family="devices",
function='get_device_list',
op_modifies=True,
params={"hostname": hostname}
)
if response:
self.log("Received API response from 'get_device_list': {0}".format(str(response)), "DEBUG")
response = response.get("response")
if response:
device_ip = response[0]["managementIpAddress"]
if device_ip:
device_ips.append(device_ip)
except Exception as e:
error_message = "Exception occurred while fetching device from Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "ERROR")
return device_ips
def get_device_ips_from_serial_number(self, serial_number_list):
"""
Get the list of unique device IPs for a specified list of serial numbers in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
serial_number_list (list): The list of serial number of devices for which you want to retrieve the device IPs.
Returns:
list: The list of unique device IPs for the specified devices with serial numbers.
Description:
Queries Cisco Catalyst Center to retrieve the unique device IPs associated with a device having the specified
serial numbers.If a device is not found in Cisco Catalyst Center, an error log message is printed.
"""
device_ips = []
for serial_number in serial_number_list:
try:
response = self.dnac._exec(
family="devices",
function='get_device_list',
op_modifies=True,
params={"serialNumber": serial_number}
)
if response:
self.log("Received API response from 'get_device_list': {0}".format(str(response)), "DEBUG")
response = response.get("response")
if response:
device_ip = response[0]["managementIpAddress"]
if device_ip:
device_ips.append(device_ip)
except Exception as e:
error_message = "Exception occurred while fetching device from Cisco Catalyst Center - {0}".format(str(e))
self.log(error_message, "ERROR")
return device_ips
def get_device_ips_from_mac_address(self, mac_address_list):
"""
Get the list of unique device IPs for list of specified mac address of devices in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
mac_address_list (list): The list of mac address of devices for which you want to retrieve the device IPs.
Returns:
list: The list of unique device IPs for the specified devices.
Description:
Queries Cisco Catalyst Center to retrieve the unique device IPs associated with a device having the specified
mac addresses. If a device is not found in Cisco Catalyst Center, an error log message is printed.
"""
device_ips = []
for mac_address in mac_address_list:
try:
response = self.dnac._exec(
family="devices",
function='get_device_list',
op_modifies=True,
params={"macAddress": mac_address}
)
if response:
self.log("Received API response from 'get_device_list': {0}".format(str(response)), "DEBUG")
response = response.get("response")
if response:
device_ip = response[0]["managementIpAddress"]
if device_ip:
device_ips.append(device_ip)
except Exception as e:
error_message = "Exception occurred while fetching device from Cisco Catalyst Center - {0}".format(str(e))
self.log(error_message, "ERROR")
return device_ips
def get_interface_from_id_and_name(self, device_id, interface_name):
"""
Retrieve the interface ID for a device in Cisco Catalyst Center based on device id and interface name.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_id (str): The id of the device.
interface_name (str): Name of the interface for which details need to be collected.
Returns:
str: The interface ID for the specified device and interface name.
Description:
The function sends a request to Cisco Catalyst Center to retrieve the interface information
for the device with the provided device id and interface name and extracts the interface ID from the
response, and returns the interface ID.
"""
try:
interface_detail_params = {
'device_id': device_id,
'name': interface_name
}
response = self.dnac._exec(
family="devices",
function='get_interface_details',
op_modifies=True,
params=interface_detail_params
)
self.log("Received API response from 'get_interface_details': {0}".format(str(response)), "DEBUG")
response = response.get("response")
if response:
self.status = "success"
interface_id = response["id"]
self.log("""Successfully fetched interface ID ({0}) by using device id {1} and interface name {2}."""
.format(interface_id, device_id, interface_name), "INFO")
return interface_id
except Exception as e:
self.status = "failed"
self.msg = "Failed to retrieve interface ID for interface({0}) from Cisco Catalyst Center: {1}".format(interface_name, str(e))
self.log(self.msg, "ERROR")
return self
def get_interface_from_ip(self, device_ip):
"""
Get the interface ID for a device in Cisco Catalyst Center based on its IP address.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ip (str): The IP address of the device.
Returns:
str: The interface ID for the specified device.
Description:
The function sends a request to Cisco Catalyst Center to retrieve the interface information
for the device with the provided IP address and extracts the interface ID from the
response, and returns the interface ID.
"""
try:
response = self.dnac._exec(
family="devices",
function='get_interface_by_ip',
op_modifies=True,
params={"ip_address": device_ip}
)
self.log("Received API response from 'get_interface_by_ip': {0}".format(str(response)), "DEBUG")
response = response.get("response")
if response:
interface_id = response[0]["id"]
self.log("Successfully retrieved Interface Id '{0}' for device '{1}'.".format(interface_id, device_ip), "DEBUG")
return interface_id
except Exception as e:
error_message = "Error while fetching Interface Id for device '{0}' from Cisco Catalyst Center: {1}".format(device_ip, str(e))
self.log(error_message, "ERROR")
raise Exception(error_message)
def get_device_response(self, device_ip):
"""
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ip (str): The management IP address of the device for which the response is to be retrieved.
Returns:
dict: A dictionary containing details of the device obtained from the Cisco Catalyst Center.
Description:
This method communicates with Cisco Catalyst Center to retrieve the details of a device with the specified
management IP address. It executes the 'get_device_list' API call with the provided device IP address,
logs the response, and returns a dictionary containing information about the device.
"""
try:
response = self.dnac._exec(
family="devices",
function='get_device_list',
op_modifies=True,
params={"managementIpAddress": device_ip}
)
response = response.get('response')[0]
except Exception as e:
error_message = "Error while getting the response of device from Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "ERROR")
raise Exception(error_message)
return response
def check_device_role(self, device_ip):
"""
Checks if the device role and role source for a device in Cisco Catalyst Center match the specified values in the configuration.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ip (str): The management IP address of the device for which the device role is to be checked.
Returns:
bool: True if the device role and role source match the specified values, False otherwise.
Description:
This method retrieves the device role and role source for a device in Cisco Catalyst Center using the
'get_device_response' method and compares the retrieved values with specified values in the configuration
for updating device roles.
"""
role = self.config[0].get('role')
response = self.get_device_response(device_ip)
return response.get('role') == role
def check_interface_details(self, device_ip, interface_name):
"""
Checks if the interface details for a device in Cisco Catalyst Center match the specified values in the configuration.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ip (str): The management IP address of the device for which interface details are to be checked.
Returns:
bool: True if the interface details match the specified values, False otherwise.
Description:
This method retrieves the interface details for a device in Cisco Catalyst Center using the 'get_interface_by_ip' API call.
It then compares the retrieved details with the specified values in the configuration for updating interface details.
If all specified parameters match the retrieved values or are not provided in the playbook parameters, the function
returns True, indicating successful validation.
"""
device_id = self.get_device_ids([device_ip])
if not device_id:
self.log("""Error: Device with IP '{0}' not found in Cisco Catalyst Center.Unable to update interface details."""
.format(device_ip), "ERROR")
return False
interface_detail_params = {
'device_id': device_id[0],
'name': interface_name
}
response = self.dnac._exec(
family="devices",
function='get_interface_details',
op_modifies=True,
params=interface_detail_params
)
self.log("Received API response from 'get_interface_details': {0}".format(str(response)), "DEBUG")
response = response.get("response")
if not response:
self.log("No response received from the API 'get_interface_details'.", "DEBUG")
return False
response_params = {
'description': response.get('description'),
'adminStatus': response.get('adminStatus'),
'voiceVlanId': response.get('voiceVlan'),
'vlanId': int(response.get('vlanId'))
}
interface_playbook_params = self.config[0].get('update_interface_details')
playbook_params = {
'description': interface_playbook_params.get('description', ''),
'adminStatus': interface_playbook_params.get('admin_status'),
'voiceVlanId': interface_playbook_params.get('voice_vlan_id', ''),
'vlanId': interface_playbook_params.get('vlan_id')
}
for key, value in playbook_params.items():
if not value:
continue
elif response_params[key] != value:
return False
return True
def check_credential_update(self):
"""
Checks if the credentials for devices in the configuration match the updated values in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Returns:
bool: True if the credentials match the updated values, False otherwise.
Description:
This method triggers the export API in Cisco Catalyst Center to obtain the updated credential details for
the specified devices. It then decrypts and reads the CSV file containing the updated credentials,
comparing them with the credentials specified in the configuration.
"""
device_ips = self.get_device_ips_from_config_priority()
device_uuids = self.get_device_ids(device_ips)
password = "Testing@123"
payload_params = {"deviceUuids": device_uuids, "password": password, "operationEnum": "0"}
response = self.trigger_export_api(payload_params)
self.check_return_status()
csv_reader = self.decrypt_and_read_csv(response, password)
self.check_return_status()
device_data = next(csv_reader, None)
if not device_data:
return False
csv_data_dict = {
'snmp_retry': device_data['snmp_retries'],
'username': device_data['cli_username'],
'password': device_data['cli_password'],
'enable_password': device_data['cli_enable_password'],
'snmp_username': device_data['snmpv3_user_name'],
'snmp_auth_protocol': device_data['snmpv3_auth_type'],
}
config = self.config[0]
for key in csv_data_dict:
if key in config and csv_data_dict[key] is not None:
if key == "snmp_retry" and int(csv_data_dict[key]) != int(config[key]):
return False
elif csv_data_dict[key] != config[key]:
return False
return True
def get_provision_wired_device(self, device_ip):
"""
Retrieves the provisioning status of a wired device with the specified management IP address in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ip (str): The management IP address of the wired device for which provisioning status is to be retrieved.
Returns:
bool: True if the device is provisioned successfully, False otherwise.
Description:
This method communicates with Cisco Catalyst Center to check the provisioning status of a wired device.
It executes the 'get_provisioned_wired_device' API call with the provided device IP address and
logs the response.
"""
try:
flag = 3
response = self.dnac._exec(
family="sda",
function='get_provisioned_wired_device',
op_modifies=True,
params={"device_management_ip_address": device_ip}
)
if response.get("status") == "success" and "Wired Provisioned device detail retrieved successfully." in response.get("description"):
flag = 2
self.log("Wired device '{0}' already provisioned in the Cisco Catalyst Center.".format(device_ip), "INFO")
except Exception as e:
if "not provisioned to any site" in str(e):
flag = 1
return flag
def clear_mac_address(self, interface_id, deploy_mode, interface_name):
"""
Clear the MAC address table on a specific interface of a device.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
interface_id (str): The UUID of the interface where the MAC addresses will be cleared.
deploy_mode (str): The deployment mode of the device.
interface_name(str): The name of the interface for which the MAC addresses will be cleared.
Returns:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Description:
This function clears the MAC address table on a specific interface of a device.
The 'deploy_mode' parameter specifies the deployment mode of the device.
If the operation is successful, the function returns the response from the API call.
If an error occurs during the operation, the function logs the error details and updates the status accordingly.
"""
try:
payload = {
"operation": "ClearMacAddress",
"payload": {}
}
clear_mac_address_payload = {
'payload': payload,
'interface_uuid': interface_id,
'deployment_mode': deploy_mode
}
response = self.dnac._exec(
family="devices",
function='clear_mac_address_table',
op_modifies=True,
params=clear_mac_address_payload,
)
self.log("Received API response from 'clear_mac_address_table': {0}".format(str(response)), "DEBUG")
if not (response and isinstance(response, dict)):
self.status = "failed"
self.msg = """Received an empty response from the API 'clear_mac_address_table'. This indicates a failure to clear
the Mac address table for the interface '{0}'""".format(interface_name)
self.log(self.msg, "ERROR")
self.result['response'] = self.msg
return self
task_id = response.get('response').get('taskId')
while True:
execution_details = self.get_task_details(task_id)
if execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "Failed to clear the Mac address table for the interface '{0}' due to {1}".format(interface_name, failure_reason)
else:
self.msg = "Failed to clear the Mac address table for the interface '{0}'".format(interface_name)
self.log(self.msg, "ERROR")
self.result['response'] = self.msg
break
elif 'clear mac address-table' in execution_details.get("data"):
self.status = "success"
self.result['changed'] = True
self.result['response'] = execution_details
self.msg = "Successfully executed the task of clearing the Mac address table for interface '{0}'".format(interface_name)
self.log(self.msg, "INFO")
break
except Exception as e:
error_msg = """An exception occurred during the process of clearing the MAC address table for interface {0}, due to -
{1}""".format(interface_name, str(e))
self.log(error_msg, "WARNING")
self.result['changed'] = False
self.result['response'] = error_msg
return self
def update_interface_detail_of_device(self, device_to_update):
"""
Update interface details for a device in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_to_update (list): A list of IP addresses of devices to be updated.
Returns:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Description:
This method updates interface details for devices in Cisco Catalyst Center.
It iterates over the list of devices to be updated, retrieves interface parameters from the configuration,
calls the update interface details API with the required parameters, and checks the execution response.
If the update is successful, it sets the status to 'success' and logs an informational message.
"""
# Call the Get interface details by device IP API and fetch the interface Id
is_update_occurred = False
response_list = []
for device_ip in device_to_update:
interface_params = self.config[0].get('update_interface_details')
interface_names_list = interface_params.get('interface_name')
for interface_name in interface_names_list:
device_id = self.get_device_ids([device_ip])
interface_details = self.get_interface_from_id_and_name(device_id[0], interface_name)
# Check if interface_details is None or does not contain the 'id' key.
if interface_details is None or not interface_details.get('id'):
self.status = "failed"
self.msg = """Failed to retrieve interface details or the 'id' is missing for the device with identifier
'{0}' and interface '{1}'""".format(device_id[0], interface_name)
self.log(self.msg, "WARNING")
return self
interface_id = interface_details['id']
self.check_return_status()
# Now we call update interface details api with required parameter
try:
interface_params = self.config[0].get('update_interface_details')
clear_mac_address_table = interface_params.get("clear_mac_address_table", False)
if clear_mac_address_table:
response = self.get_device_response(device_ip)
if response.get('role').upper() != "ACCESS":
self.msg = "The action to clear the MAC Address table is only supported for devices with the ACCESS role."
self.log(self.msg, "WARNING")
response_list.append(self.msg)
self.result['changed'] = False
else:
deploy_mode = interface_params.get('deployment_mode', 'Deploy')
self.clear_mac_address(interface_id, deploy_mode, interface_name).check_return_status()
temp_params = {
'description': interface_params.get('description', ''),
'adminStatus': interface_params.get('admin_status'),
'voiceVlanId': interface_params.get('voice_vlan_id'),
'vlanId': interface_params.get('vlan_id')
}
payload_params = {}
for key, value in temp_params.items():
if value is not None:
payload_params[key] = value
# Check if interface need update or not here
interface_needs_update = False
for key, value in payload_params.items():
if key == "voiceVlanId":
if str(value) != interface_details['voiceVlan']:
interface_needs_update = True
else:
if str(value) != str(interface_details.get(key)):
interface_needs_update = True
if not interface_needs_update:
self.status = "success"
self.result['changed'] = False
self.msg = """Interface details for the given interface '{0}' are already updated in the Cisco Catalyst Center for the
device '{1}'.""".format(interface_name, device_ip)
self.log(self.msg, "INFO")
self.result['response'] = self.msg
continue
update_interface_params = {
'payload': payload_params,
'interface_uuid': interface_id,
'deployment_mode': interface_params.get('deployment_mode', 'Deploy')
}
response = self.dnac._exec(
family="devices",
function='update_interface_details',
op_modifies=True,
params=update_interface_params,
)
self.log("Received API response from 'update_interface_details': {0}".format(str(response)), "DEBUG")
if response and isinstance(response, dict):
response = response.get('response')
if not response:
self.status = "failed"
self.msg = "Failed to update the interface because the 'update_interface_details' API returned an empty response."
self.log(self.msg, "ERROR")
continue
task_id = response.get('taskId')
while True:
execution_details = self.get_task_details(task_id)
if 'SUCCESS' in execution_details.get("progress"):
self.status = "success"
is_update_occurred = True
self.msg = "Successfully updated the Interface Details for device '{0}'.".format(device_ip)
response_list.append(self.msg)
self.log(self.msg, "INFO")
break
elif execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "Interface Updation get failed because of {0}".format(failure_reason)
else:
self.msg = "Interface Updation get failed"
self.log(self.msg, "ERROR")
break
except Exception as e:
error_message = "Error while updating interface details in Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "INFO")
self.status = "success"
self.result['changed'] = False
self.msg = "Port actions are only supported on user facing/access ports as it's not allowed or No Updation required"
self.log(self.msg, "INFO")
response_list.append(self.msg)
self.result['changed'] = is_update_occurred
self.result['response'] = response_list
return self
def check_managementip_execution_response(self, response, device_ip, new_mgmt_ipaddress):
"""
Check the execution response of a management IP update task.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
response (dict): The response received after initiating the management IP update task.
device_ip (str): The IP address of the device for which the management IP was updated.
new_mgmt_ipaddress (str): The new management IP address of the device.
Returns:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Description:
This method checks the execution response of a management IP update task in Cisco Catalyst Center.
It continuously queries the task details until the task is completed or an error occurs.
If the task is successful, it sets the status to 'success' and logs an informational message.
If the task fails, it sets the status to 'failed' and logs an error message with the failure reason, if available.
"""
task_id = response.get('response').get('taskId')
while True:
execution_details = self.get_task_details(task_id)
if execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "Device new management IP updation for device '{0}' get failed due to {1}".format(device_ip, failure_reason)
else:
self.msg = "Device new management IP updation for device '{0}' get failed".format(device_ip)
self.log(self.msg, "ERROR")
break
elif execution_details.get("endTime"):
self.status = "success"
self.result['changed'] = True
self.msg = """Device '{0}' present in Cisco Catalyst Center and new management ip '{1}' have been
updated successfully""".format(device_ip, new_mgmt_ipaddress)
self.result['response'] = self.msg
self.log(self.msg, "INFO")
break
return self
def check_device_update_execution_response(self, response, device_ip):
"""
Check the execution response of a device update task.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
response (dict): The response received after initiating the device update task.
device_ip (str): The IP address of the device for which the update is performed.
Returns:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Description:
This method checks the execution response of a device update task in Cisco Catalyst Center.
It continuously queries the task details until the task is completed or an error occurs.
If the task is successful, it sets the status to 'success' and logs an informational message.
If the task fails, it sets the status to 'failed' and logs an error message with the failure reason, if available.
"""
task_id = response.get('response').get('taskId')
while True:
execution_details = self.get_task_details(task_id)
if execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "Device Updation for device '{0}' get failed due to {1}".format(device_ip, failure_reason)
else:
self.msg = "Device Updation for device '{0}' get failed".format(device_ip)
self.log(self.msg, "ERROR")
break
elif execution_details.get("endTime"):
self.status = "success"
self.result['changed'] = True
self.msg = "Device '{0}' present in Cisco Catalyst Center and have been updated successfully".format(device_ip)
self.result['response'] = self.msg
self.log(self.msg, "INFO")
break
return self
def is_device_exist_in_ccc(self, device_ip):
"""
Check if a device with the given IP exists in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_ip (str): The IP address of the device to check.
Returns:
bool: True if the device exists, False otherwise.
Description:
This method queries Cisco Catalyst Center to check if a device with the specified
management IP address exists. If the device exists, it returns True; otherwise,
it returns False. If an error occurs during the process, it logs an error message
and raises an exception.
"""
try:
response = self.dnac._exec(
family="devices",
function='get_device_list',
op_modifies=True,
params={"managementIpAddress": device_ip}
)
response = response.get('response')
if not response:
self.log("Device with given IP '{0}' is not present in Cisco Catalyst Center".format(device_ip), "INFO")
return False
return True
except Exception as e:
error_message = "Error while getting the response of device '{0}' from Cisco Catalyst Center: {1}".format(device_ip, str(e))
self.log(error_message, "ERROR")
raise Exception(error_message)
def is_device_exist_for_update(self, device_to_update):
"""
Check if the device(s) exist in Cisco Catalyst Center for update operation.
Args:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
device_to_update (list): A list of device(s) to be be checked present in Cisco Catalyst Center.
Returns:
bool: True if at least one of the devices to be updated exists in Cisco Catalyst Center,
False otherwise.
Description:
This function checks if any of the devices specified in the 'device_to_update' list
exists in Cisco Catalyst Center. It iterates through the list of devices and compares
each device with the list of devices present in Cisco Catalyst Center obtained from
'self.have.get("device_in_ccc")'. If a match is found, it sets 'device_exist' to True
and breaks the loop.
"""
# First check if device present in Cisco Catalyst Center or not
device_exist = False
for device in device_to_update:
if device in self.have.get("device_in_ccc"):
device_exist = True
break
return device_exist
def get_want(self, config):
"""
Get all the device related information from playbook that is needed to be
add/update/delete/resync device in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
config (dict): A dictionary containing device-related information from the playbook.
Returns:
dict: A dictionary containing the extracted device parameters and other relevant information.
Description:
Retrieve all the device-related information from the playbook needed for adding, updating, deleting,
or resyncing devices in Cisco Catalyst Center.
"""
want = {}
device_params = self.get_device_params(config)
want["device_params"] = device_params
self.want = want
self.msg = "Successfully collected all parameters from the playbook "
self.status = "success"
self.log("Desired State (want): {0}".format(str(self.want)), "INFO")
return self
def get_diff_merged(self, config):
"""
Merge and process differences between existing devices and desired device configuration in Cisco Catalyst Center.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center.
config (dict): A dictionary containing the desired device configuration and relevant information from the playbook.
Returns:
object: An instance of the class with updated results and status based on the processing of differences.
Description:
The function processes the differences and, depending on the changes required, it may add, update,
or resynchronize devices in Cisco Catalyst Center.
The updated results and status are stored in the class instance for further use.
"""
devices_to_add = self.have["device_not_in_dnac"]
device_type = self.config[0].get("type", "NETWORK_DEVICE")
device_resynced = self.config[0].get("device_resync", False)
device_reboot = self.config[0].get("reboot_device", False)
credential_update = self.config[0].get("credential_update", False)
config['type'] = device_type
config['ip_address_list'] = devices_to_add
if device_type == "FIREPOWER_MANAGEMENT_SYSTEM":
config['http_port'] = self.config[0].get("http_port", "443")
if self.config[0].get('provision_wired_device'):
provision_wired_list = self.config[0]['provision_wired_device']
device_not_available = []
device_in_ccc = self.device_exists_in_dnac()
for prov_dict in provision_wired_list:
device_ip = prov_dict['device_ip']
if device_ip not in device_in_ccc:
device_not_available.append(device_ip)
if device_not_available:
self.status = "failed"
self.msg = """Unable to Provision Wired Device(s) because the device(s) listed: {0} are not present in the
Cisco Catalyst Center.""".format(str(device_not_available))
self.result['response'] = self.msg
self.log(self.msg, "ERROR")
return self
if self.config[0].get('update_mgmt_ipaddresslist'):
device_ip = self.config[0].get('update_mgmt_ipaddresslist')[0].get('existMgmtIpAddress')
is_device_exists = self.is_device_exist_in_ccc(device_ip)
if not is_device_exists:
self.status = "failed"
self.msg = """Unable to update the Management IP address because the device with IP '{0}' is not
found in Cisco Catalyst Center.""".format(device_ip)
self.log(self.msg, "ERROR")
return self
if self.config[0].get('update_interface_details'):
device_to_update = self.get_device_ips_from_config_priority()
device_exist = self.is_device_exist_for_update(device_to_update)
if not device_exist:
self.msg = """Unable to update interface details because the device(s) listed: {0} are not present in the
Cisco Catalyst Center.""".format(str(device_to_update))
self.status = "failed"
self.result['response'] = self.msg
self.log(self.msg, "ERROR")
return self
if self.config[0].get('role'):
devices_to_update_role = self.get_device_ips_from_config_priority()
device_exist = self.is_device_exist_for_update(devices_to_update_role)
if not device_exist:
self.msg = """Unable to update device role because the device(s) listed: {0} are not present in the Cisco
Catalyst Center.""".format(str(devices_to_update_role))
self.status = "failed"
self.result['response'] = self.msg
self.log(self.msg, "ERROR")
return self
if credential_update:
device_to_update = self.get_device_ips_from_config_priority()
device_exist = self.is_device_exist_for_update(device_to_update)
if not device_exist:
self.msg = """Unable to edit device credentials/details because the device(s) listed: {0} are not present in the
Cisco Catalyst Center.""".format(str(device_to_update))
self.status = "failed"
self.result['response'] = self.msg
self.log(self.msg, "ERROR")
return self
if not config['ip_address_list']:
self.msg = "Devices '{0}' already present in Cisco Catalyst Center".format(self.have['devices_in_playbook'])
self.log(self.msg, "INFO")
self.result['changed'] = False
self.result['response'] = self.msg
else:
# To add the devices in inventory
input_params = self.want.get("device_params")
device_params = input_params.copy()
if not device_params['snmpVersion']:
device_params['snmpVersion'] = "v3"
device_params['ipAddress'] = config['ip_address_list']
if device_params['snmpVersion'] == "v2":
params_to_remove = ["snmpAuthPassphrase", "snmpAuthProtocol", "snmpMode", "snmpPrivPassphrase", "snmpPrivProtocol", "snmpUserName"]
for param in params_to_remove:
device_params.pop(param, None)
if not device_params['snmpROCommunity']:
self.status = "failed"
self.msg = "Required parameter 'snmpROCommunity' for adding device with snmmp version v2 is not present"
self.result['msg'] = self.msg
self.log(self.msg, "ERROR")
return self
else:
if not device_params['snmpMode']:
device_params['snmpMode'] = "AUTHPRIV"
if not device_params['cliTransport']:
device_params['cliTransport'] = "ssh"
if not device_params['snmpPrivProtocol']:
device_params['snmpPrivProtocol'] = "AES128"
if device_params['snmpPrivProtocol'] == "AES192":
device_params['snmpPrivProtocol'] = "CISCOAES192"
elif device_params['snmpPrivProtocol'] == "AES256":
device_params['snmpPrivProtocol'] = "CISCOAES256"
if device_params['snmpMode'] == "NOAUTHNOPRIV":
device_params.pop('snmpAuthPassphrase', None)
device_params.pop('snmpPrivPassphrase', None)
device_params.pop('snmpPrivProtocol', None)
device_params.pop('snmpAuthProtocol', None)
elif device_params['snmpMode'] == "AUTHNOPRIV":
device_params.pop('snmpPrivPassphrase', None)
device_params.pop('snmpPrivProtocol', None)
device_to_add_in_ccc = device_params['ipAddress']
self.mandatory_parameter(device_to_add_in_ccc).check_return_status()
try:
response = self.dnac._exec(
family="devices",
function='add_device',
op_modifies=True,
params=device_params,
)
self.log("Received API response from 'add_device': {0}".format(str(response)), "DEBUG")
if response and isinstance(response, dict):
task_id = response.get('response').get('taskId')
while True:
execution_details = self.get_task_details(task_id)
if '/task/' in execution_details.get("progress"):
self.status = "success"
self.result['response'] = execution_details
if len(devices_to_add) > 0:
self.result['changed'] = True
self.msg = "Device(s) '{0}' added to Cisco Catalyst Center".format(str(devices_to_add))
self.log(self.msg, "INFO")
self.result['msg'] = self.msg
break
self.msg = "Device(s) '{0}' already present in Cisco Catalyst Center".format(str(self.config[0].get("ip_address_list")))
self.log(self.msg, "INFO")
self.result['msg'] = self.msg
break
elif execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "Device addition get failed because of {0}".format(failure_reason)
else:
self.msg = "Device addition get failed"
self.log(self.msg, "ERROR")
self.result['msg'] = self.msg
return self
except Exception as e:
error_message = "Error while adding device in Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "ERROR")
raise Exception(error_message)
# Update the role of devices having the role source as Manual
if self.config[0].get('role'):
devices_to_update_role = self.get_device_ips_from_config_priority()
device_role = self.config[0].get('role')
role_update_count = 0
role_updated_list = []
for device_ip in devices_to_update_role:
device_id = self.get_device_ids([device_ip])
# Check if the same role of device is present in dnac then no need to change the state
response = self.dnac._exec(
family="devices",
function='get_device_list',
op_modifies=True,
params={"managementIpAddress": device_ip}
)
response = response.get('response')[0]
if response.get('role') == device_role:
self.status = "success"
self.result['changed'] = False
role_update_count += 1
log_msg = "The device role '{0}' is already set in Cisco Catalyst Center, no update is needed.".format(device_role)
self.log(log_msg, "INFO")
continue
device_role_params = {
'role': device_role,
'roleSource': "MANUAL",
'id': device_id[0]
}
try:
response = self.dnac._exec(
family="devices",
function='update_device_role',
op_modifies=True,
params=device_role_params,
)
self.log("Received API response from 'update_device_role': {0}".format(str(response)), "DEBUG")
if response and isinstance(response, dict):
task_id = response.get('response').get('taskId')
while True:
execution_details = self.get_task_details(task_id)
progress = execution_details.get("progress")
if 'successfully' in progress or 'succesfully' in progress:
self.status = "success"
self.log("Device '{0}' role updated successfully to '{1}'".format(device_ip, device_role), "INFO")
role_updated_list.append(device_ip)
break
elif execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "Device role updation get failed because of {0}".format(failure_reason)
else:
self.msg = "Device role updation get failed"
self.log(self.msg, "ERROR")
self.result['response'] = self.msg
break
except Exception as e:
error_message = "Error while updating device role '{0}' in Cisco Catalyst Center: {1}".format(device_role, str(e))
self.log(error_message, "ERROR")
if role_update_count == len(devices_to_update_role):
self.status = "success"
self.result['changed'] = False
self.msg = """The device role '{0}' is already set in Cisco Catalyst Center, no device role update is needed for the
device(s) {1}.""".format(device_role, str(devices_to_update_role))
self.log(self.msg, "INFO")
self.result['response'] = self.msg
if role_updated_list:
self.status = "success"
self.result['changed'] = True
self.msg = "Device(s) '{0}' role updated successfully to '{1}'".format(str(role_updated_list), device_role)
self.result['response'] = self.msg
self.log(self.msg, "INFO")
if credential_update:
device_to_update = self.get_device_ips_from_config_priority()
# Update Device details and credentails
device_uuids = self.get_device_ids(device_to_update)
password = "Testing@123"
export_payload = {"deviceUuids": device_uuids, "password": password, "operationEnum": "0"}
export_response = self.trigger_export_api(export_payload)
self.check_return_status()
csv_reader = self.decrypt_and_read_csv(export_response, password)
self.check_return_status()
device_details = {}
for row in csv_reader:
ip_address = row['ip_address']
device_details[ip_address] = row
for device_ip in device_to_update:
playbook_params = self.want.get("device_params").copy()
playbook_params['ipAddress'] = [device_ip]
device_data = device_details[device_ip]
if device_data['snmpv3_privacy_password'] == ' ':
device_data['snmpv3_privacy_password'] = None
if device_data['snmpv3_auth_password'] == ' ':
device_data['snmpv3_auth_password'] = None
if not playbook_params['snmpMode']:
if device_data['snmpv3_privacy_password']:
playbook_params['snmpMode'] = "AUTHPRIV"
elif device_data['snmpv3_auth_password']:
playbook_params['snmpMode'] = "AUTHNOPRIV"
else:
playbook_params['snmpMode'] = "NOAUTHNOPRIV"
if not playbook_params['cliTransport']:
if device_data['protocol'] == "ssh2":
playbook_params['cliTransport'] = "ssh"
else:
playbook_params['cliTransport'] = device_data['protocol']
if not playbook_params['snmpPrivProtocol']:
playbook_params['snmpPrivProtocol'] = device_data['snmpv3_privacy_type']
csv_data_dict = {
'username': device_data['cli_username'],
'password': device_data['cli_password'],
'enable_password': device_data['cli_enable_password'],
'netconf_port': device_data['netconf_port'],
}
if device_data['snmp_version'] == '3':
csv_data_dict['snmp_username'] = device_data['snmpv3_user_name']
if device_data['snmpv3_privacy_password']:
csv_data_dict['snmp_auth_passphrase'] = device_data['snmpv3_auth_password']
csv_data_dict['snmp_priv_passphrase'] = device_data['snmpv3_privacy_password']
else:
csv_data_dict['snmp_username'] = None
device_key_mapping = {
'username': 'userName',
'password': 'password',
'enable_password': 'enablePassword',
'snmp_username': 'snmpUserName',
'netconf_port': 'netconfPort'
}
device_update_key_list = ["username", "password", "enable_password", "snmp_username", "netconf_port"]
for key in device_update_key_list:
mapped_key = device_key_mapping[key]
if playbook_params[mapped_key] is None:
playbook_params[mapped_key] = csv_data_dict[key]
if playbook_params['snmpMode'] == "AUTHPRIV":
if not playbook_params['snmpAuthPassphrase']:
playbook_params['snmpAuthPassphrase'] = csv_data_dict['snmp_auth_passphrase']
if not playbook_params['snmpPrivPassphrase']:
playbook_params['snmpPrivPassphrase'] = csv_data_dict['snmp_priv_passphrase']
if playbook_params['snmpPrivProtocol'] == "AES192":
playbook_params['snmpPrivProtocol'] = "CISCOAES192"
elif playbook_params['snmpPrivProtocol'] == "AES256":
playbook_params['snmpPrivProtocol'] = "CISCOAES256"
if playbook_params['snmpMode'] == "NOAUTHNOPRIV":
playbook_params.pop('snmpAuthPassphrase', None)
playbook_params.pop('snmpPrivPassphrase', None)
playbook_params.pop('snmpPrivProtocol', None)
playbook_params.pop('snmpAuthProtocol', None)
elif playbook_params['snmpMode'] == "AUTHNOPRIV":
playbook_params.pop('snmpPrivPassphrase', None)
playbook_params.pop('snmpPrivProtocol', None)
if playbook_params['netconfPort'] == " ":
playbook_params['netconfPort'] = None
if playbook_params['enablePassword'] == " ":
playbook_params['enablePassword'] = None
if playbook_params['netconfPort'] and playbook_params['cliTransport'] == "telnet":
self.log("""Updating the device cli transport from ssh to telnet with netconf port '{0}' so make
netconf port as None to perform the device update task""".format(playbook_params['netconfPort']), "DEBUG")
playbook_params['netconfPort'] = None
if not playbook_params['snmpVersion']:
if device_data['snmp_version'] == '3':
playbook_params['snmpVersion'] = "v3"
else:
playbook_params['snmpVersion'] = "v2"
if playbook_params['snmpVersion'] == 'v2':
params_to_remove = ["snmpAuthPassphrase", "snmpAuthProtocol", "snmpMode", "snmpPrivPassphrase", "snmpPrivProtocol", "snmpUserName"]
for param in params_to_remove:
playbook_params.pop(param, None)
if not playbook_params['snmpROCommunity']:
playbook_params['snmpROCommunity'] = device_data.get('snmp_community', None)
if not playbook_params['snmpRWCommunity']:
playbook_params['snmpRWCommunity'] = device_data.get('snmp_write_community', None)
if not playbook_params['httpUserName']:
playbook_params['httpUserName'] = device_data.get('http_config_username', None)
if not playbook_params['httpPassword']:
playbook_params['httpPassword'] = device_data.get('http_config_password', None)
if not playbook_params['httpPort']:
playbook_params['httpPort'] = device_data.get('http_port', None)
for key, value in playbook_params.items():
if value == " ":
playbook_params[key] = None
try:
if playbook_params['updateMgmtIPaddressList']:
new_mgmt_ipaddress = playbook_params['updateMgmtIPaddressList'][0]['newMgmtIpAddress']
if new_mgmt_ipaddress in self.have['device_in_dnac']:
self.status = "failed"
self.msg = "Device with IP address '{0}' already exists in inventory".format(new_mgmt_ipaddress)
self.log(self.msg, "ERROR")
self.result['response'] = self.msg
else:
self.log("Playbook parameter for updating device new management ip address: {0}".format(str(playbook_params)), "DEBUG")
response = self.dnac._exec(
family="devices",
function='sync_devices',
op_modifies=True,
params=playbook_params,
)
self.log("Received API response from 'sync_devices': {0}".format(str(response)), "DEBUG")
if response and isinstance(response, dict):
self.check_managementip_execution_response(response, device_ip, new_mgmt_ipaddress)
self.check_return_status()
else:
self.log("Playbook parameter for updating devices: {0}".format(str(playbook_params)), "DEBUG")
response = self.dnac._exec(
family="devices",
function='sync_devices',
op_modifies=True,
params=playbook_params,
)
self.log("Received API response from 'sync_devices': {0}".format(str(response)), "DEBUG")
if response and isinstance(response, dict):
self.check_device_update_execution_response(response, device_ip)
self.check_return_status()
except Exception as e:
error_message = "Error while updating device in Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "ERROR")
raise Exception(error_message)
# Update list of interface details on specific or list of devices.
if self.config[0].get('update_interface_details'):
device_to_update = self.get_device_ips_from_config_priority()
self.update_interface_detail_of_device(device_to_update).check_return_status()
# If User defined field(UDF) not present then create it and add multiple udf to specific or list of devices
if self.config[0].get('add_user_defined_field'):
udf_field_list = self.config[0].get('add_user_defined_field')
for udf in udf_field_list:
field_name = udf.get('name')
if field_name is None:
self.status = "failed"
self.msg = "Error: The mandatory parameter 'name' for the User Defined Field is missing. Please provide the required information."
self.log(self.msg, "ERROR")
self.result['response'] = self.msg
return self
# Check if the Global User defined field exist if not then create it with given field name
udf_exist = self.is_udf_exist(field_name)
if not udf_exist:
# Create the Global UDF
self.log("Global User Defined Field '{0}' does not present in Cisco Catalyst Center, we need to create it".format(field_name), "DEBUG")
self.create_user_defined_field(udf).check_return_status()
# Get device Id based on config priority
device_ips = self.get_device_ips_from_config_priority()
device_ids = self.get_device_ids(device_ips)
if len(device_ids) == 0:
self.status = "failed"
self.msg = """Unable to assign Global User Defined Field: No devices found in Cisco Catalyst Center.
Please add devices to proceed."""
self.log(self.msg, "INFO")
self.result['changed'] = False
return self
# Now add code for adding Global UDF to device with Id
self.add_field_to_devices(device_ids, udf).check_return_status()
self.result['changed'] = True
self.msg = "Global User Defined Field(UDF) named '{0}' has been successfully added to the device.".format(field_name)
self.log(self.msg, "INFO")
# Once Wired device get added we will assign device to site and Provisioned it
if self.config[0].get('provision_wired_device'):
self.provisioned_wired_device().check_return_status()
# Once Wireless device get added we will assign device to site and Provisioned it
# Defer this feature as API issue is there once it's fixed we will addresses it in upcoming release iac2.0
if support_for_provisioning_wireless:
if self.config[0].get('provision_wireless_device'):
self.provisioned_wireless_devices().check_return_status()
if device_resynced:
self.resync_devices().check_return_status()
if device_reboot:
self.reboot_access_points().check_return_status()
if self.config[0].get('export_device_list'):
self.export_device_details().check_return_status()
return self
def get_diff_deleted(self, config):
"""
Delete devices in Cisco Catalyst Center based on device IP Address.
Parameters:
self (object): An instance of a class used for interacting with Cisco Catalyst Center
config (dict): A dictionary containing the list of device IP addresses to be deleted.
Returns:
object: An instance of the class with updated results and status based on the deletion operation.
Description:
This function is responsible for removing devices from the Cisco Catalyst Center inventory and
also unprovsioned and removed wired provsion devices from the Inventory page and also delete
the Global User Defined Field that are associated to the devices.
"""
device_to_delete = self.get_device_ips_from_config_priority()
self.result['msg'] = []
if self.config[0].get('add_user_defined_field'):
udf_field_list = self.config[0].get('add_user_defined_field')
for udf in udf_field_list:
field_name = udf.get('name')
udf_id = self.get_udf_id(field_name)
if udf_id is None:
self.status = "success"
self.msg = "Global UDF '{0}' is not present in Cisco Catalyst Center".format(field_name)
self.log(self.msg, "INFO")
self.result['changed'] = False
self.result['msg'] = self.msg
self.result['response'] = self.msg
return self
try:
response = self.dnac._exec(
family="devices",
function='delete_user_defined_field',
op_modifies=True,
params={"id": udf_id},
)
if response and isinstance(response, dict):
self.log("Received API response from 'delete_user_defined_field': {0}".format(str(response)), "DEBUG")
task_id = response.get('response').get('taskId')
while True:
execution_details = self.get_task_details(task_id)
if 'success' in execution_details.get("progress"):
self.status = "success"
self.msg = "Global UDF '{0}' deleted successfully from Cisco Catalyst Center".format(field_name)
self.log(self.msg, "INFO")
self.result['changed'] = True
self.result['response'] = execution_details
break
elif execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "Failed to delete Global User Defined Field(UDF) due to: {0}".format(failure_reason)
else:
self.msg = "Global UDF deletion get failed."
self.log(self.msg, "ERROR")
break
except Exception as e:
error_message = "Error while deleting Global UDF from Cisco Catalyst Center: {0}".format(str(e))
self.log(error_message, "ERROR")
raise Exception(error_message)
return self
for device_ip in device_to_delete:
if device_ip not in self.have.get("device_in_dnac"):
self.status = "success"
self.result['changed'] = False
self.msg = "Device '{0}' is not present in Cisco Catalyst Center so can't perform delete operation".format(device_ip)
self.result['msg'].append(self.msg)
self.result['response'] = self.msg
self.log(self.msg, "INFO")
continue
try:
provision_params = {
"device_management_ip_address": device_ip
}
prov_respone = self.dnac._exec(
family="sda",
function='get_provisioned_wired_device',
op_modifies=True,
params=provision_params,
)
if prov_respone.get("status") == "success":
response = self.dnac._exec(
family="sda",
function='delete_provisioned_wired_device',
op_modifies=True,
params=provision_params,
)
executionid = response.get("executionId")
while True:
execution_details = self.get_execution_details(executionid)
if execution_details.get("status") == "SUCCESS":
self.result['changed'] = True
self.msg = execution_details.get("bapiName")
self.log(self.msg, "INFO")
self.result['response'].append(self.msg)
break
elif execution_details.get("bapiError"):
self.msg = execution_details.get("bapiError")
self.log(self.msg, "ERROR")
self.result['response'].append(self.msg)
break
except Exception as e:
device_id = self.get_device_ids([device_ip])
delete_params = {
"id": device_id[0],
"clean_config": self.config[0].get("clean_config", False)
}
response = self.dnac._exec(
family="devices",
function='delete_device_by_id',
op_modifies=True,
params=delete_params,
)
if response and isinstance(response, dict):
task_id = response.get('response').get('taskId')
while True:
execution_details = self.get_task_details(task_id)
if 'success' in execution_details.get("progress"):
self.status = "success"
self.msg = "Device '{0}' was successfully deleted from Cisco Catalyst Center".format(device_ip)
self.log(self.msg, "INFO")
self.result['changed'] = True
self.result['response'] = execution_details
break
elif execution_details.get("isError"):
self.status = "failed"
failure_reason = execution_details.get("failureReason")
if failure_reason:
self.msg = "Device '{0}' deletion get failed due to: {1}".format(device_ip, failure_reason)
else:
self.msg = "Device '{0}' deletion get failed.".format(device_ip)
self.log(self.msg, "ERROR")
break
self.result['msg'].append(self.msg)
return self
def verify_diff_merged(self, config):
"""
Verify the merged status(Addition/Updation) of Devices in Cisco Catalyst Center.
Parameters:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
- config (dict): The configuration details to be verified.
Return:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Description:
This method checks the merged status of a configuration in Cisco Catalyst Center by retrieving the current state
(have) and desired state (want) of the configuration, logs the states, and validates whether the specified
site exists in the Catalyst Center configuration.
The function performs the following verifications:
- Checks for devices added to Cisco Catalyst Center and logs the status.
- Verifies updated device roles and logs the status.
- Verifies updated interface details and logs the status.
- Verifies updated device credentials and logs the status.
- Verifies the creation of a global User Defined Field (UDF) and logs the status.
- Verifies the provisioning of wired devices and logs the status.
"""
self.get_have(config)
self.log("Current State (have): {0}".format(str(self.have)), "INFO")
self.log("Desired State (want): {0}".format(str(self.want)), "INFO")
devices_to_add = self.have["device_not_in_dnac"]
credential_update = self.config[0].get("credential_update", False)
device_type = self.config[0].get("type", "NETWORK_DEVICE")
device_ips = self.get_device_ips_from_config_priority()
if not devices_to_add:
self.status = "success"
msg = """Requested device(s) '{0}' have been successfully added to the Cisco Catalyst Center and their
addition has been verified.""".format(str(self.have['devices_in_playbook']))
self.log(msg, "INFO")
else:
self.log("""Playbook's input does not match with Cisco Catalyst Center, indicating that the device addition
task may not have executed successfully.""", "INFO")
if self.config[0].get('update_interface_details'):
interface_update_flag = True
interface_names_list = self.config[0].get('update_interface_details').get('interface_name')
for device_ip in device_ips:
for interface_name in interface_names_list:
if not self.check_interface_details(device_ip, interface_name):
interface_update_flag = False
break
if interface_update_flag:
self.status = "success"
msg = "Interface details updated and verified successfully for devices {0}.".format(device_ips)
self.log(msg, "INFO")
else:
self.log("""Playbook's input does not match with Cisco Catalyst Center, indicating that the update
interface details task may not have executed successfully.""", "INFO")
if credential_update and device_type == "NETWORK_DEVICE":
credential_update_flag = self.check_credential_update()
if credential_update_flag:
self.status = "success"
msg = "Device credentials and details updated and verified successfully in Cisco Catalyst Center."
self.log(msg, "INFO")
else:
self.log("Playbook parameter does not match with Cisco Catalyst Center, meaning device updation task not executed properly.", "INFO")
elif device_type != "NETWORK_DEVICE":
self.log("""Unable to compare the parameter for device type '{0}' in the playbook with the one in Cisco Catalyst Center."""
.format(device_type), "WARNING")
if self.config[0].get('add_user_defined_field'):
udf_field_list = self.config[0].get('add_user_defined_field')
for udf in udf_field_list:
field_name = udf.get('name')
udf_exist = self.is_udf_exist(field_name)
if udf_exist:
self.status = "success"
msg = "Global UDF {0} created and verified successfully".format(field_name)
self.log(msg, "INFO")
else:
self.log("""Mismatch between playbook parameter and Cisco Catalyst Center detected, indicating that
the task of creating Global UDF may not have executed successfully.""", "INFO")
if self.config[0].get('role'):
device_role_flag = True
for device_ip in device_ips:
if not self.check_device_role(device_ip):
device_role_flag = False
break
if device_role_flag:
self.status = "success"
msg = "Device roles updated and verified successfully."
self.log(msg, "INFO")
else:
self.log("""Mismatch between playbook parameter 'role' and Cisco Catalyst Center detected, indicating the
device role update task may not have executed successfully.""", "INFO")
if self.config[0].get('provision_wired_device'):
provision_wired_list = self.config[0].get('provision_wired_device')
provision_wired_flag = True
provision_device_list = []
for prov_dict in provision_wired_list:
device_ip = prov_dict['device_ip']
provision_device_list.append(device_ip)
device_prov_status = self.get_provision_wired_device(device_ip)
if device_prov_status == 1 or device_prov_status == 3:
provision_wired_flag = False
break
if provision_wired_flag:
self.status = "success"
msg = "Wired devices {0} get provisioned and verified successfully.".format(provision_device_list)
self.log(msg, "INFO")
else:
self.log("""Mismatch between playbook's input and Cisco Catalyst Center detected, indicating that
the provisioning task may not have executed successfully.""", "INFO")
return self
def verify_diff_deleted(self, config):
"""
Verify the deletion status of Device and Global UDF in Cisco Catalyst Center.
Parameters:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
- config (dict): The configuration details to be verified.
Return:
- self (object): An instance of a class used for interacting with Cisco Catalyst Center.
Description:
This method checks the deletion status of a configuration in Cisco Catalyst Center.
It validates whether the specified Devices or Global UDF deleted from Cisco Catalyst Center.
"""
self.get_have(config)
self.log("Current State (have): {0}".format(str(self.have)), "INFO")
self.log("Desired State (want): {0}".format(str(self.want)), "INFO")
input_devices = self.have["want_device"]
device_in_dnac = self.device_exists_in_dnac()
if self.config[0].get('add_user_defined_field'):
udf_field_list = self.config[0].get('add_user_defined_field')
for udf in udf_field_list:
field_name = udf.get('name')
udf_id = self.get_udf_id(field_name)
if udf_id is None:
self.status = "success"
msg = """Global UDF named '{0}' has been successfully deleted from Cisco Catalyst Center and the deletion
has been verified.""".format(field_name)
self.log(msg, "INFO")
return self
device_delete_flag = True
for device_ip in input_devices:
if device_ip in device_in_dnac:
device_after_deletion = device_ip
device_delete_flag = False
break
if device_delete_flag:
self.status = "success"
self.msg = "Requested device(s) '{0}' deleted from Cisco Catalyst Center and the deletion has been verified.".format(str(input_devices))
self.log(self.msg, "INFO")
else:
self.log("""Mismatch between playbook parameter device({0}) and Cisco Catalyst Center detected, indicating that
the device deletion task may not have executed successfully.""".format(device_after_deletion), "INFO")
return self
def main():
""" main entry point for module execution
"""
element_spec = {'dnac_host': {'type': 'str', 'required': True, },
'dnac_port': {'type': 'str', 'default': '443'},
'dnac_username': {'type': 'str', 'default': 'admin', 'aliases': ['user']},
'dnac_password': {'type': 'str', 'no_log': True},
'dnac_verify': {'type': 'bool', 'default': 'True'},
'dnac_version': {'type': 'str', 'default': '2.2.3.3'},
'dnac_debug': {'type': 'bool', 'default': False},
'dnac_log_level': {'type': 'str', 'default': 'WARNING'},
"dnac_log_file_path": {"type": 'str', "default": 'dnac.log'},
"dnac_log_append": {"type": 'bool', "default": True},
'dnac_log': {'type': 'bool', 'default': False},
'validate_response_schema': {'type': 'bool', 'default': True},
'config_verify': {'type': 'bool', "default": False},
'dnac_api_task_timeout': {'type': 'int', "default": 1200},
'dnac_task_poll_interval': {'type': 'int', "default": 2},
'config': {'required': True, 'type': 'list', 'elements': 'dict'},
'state': {'default': 'merged', 'choices': ['merged', 'deleted']}
}
module = AnsibleModule(argument_spec=element_spec,
supports_check_mode=False)
dnac_device = DnacDevice(module)
state = dnac_device.params.get("state")
if state not in dnac_device.supported_states:
dnac_device.status = "invalid"
dnac_device.msg = "State {0} is invalid".format(state)
dnac_device.check_return_status()
dnac_device.validate_input().check_return_status()
config_verify = dnac_device.params.get("config_verify")
for config in dnac_device.validated_config:
dnac_device.reset_values()
dnac_device.get_want(config).check_return_status()
dnac_device.get_have(config).check_return_status()
dnac_device.get_diff_state_apply[state](config).check_return_status()
if config_verify:
dnac_device.verify_diff_state_apply[state](config).check_return_status()
module.exit_json(**dnac_device.result)
if __name__ == '__main__':
main()
|