forked from cisco-en-programmability/dnacenter-ansible
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathdevice_credential_playbook_config_generator.py
More file actions
2233 lines (2067 loc) · 98.4 KB
/
Copy pathdevice_credential_playbook_config_generator.py
File metadata and controls
2233 lines (2067 loc) · 98.4 KB
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
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2026, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
"""
Ansible module for brownfield YAML playbook generation of device credentials.
This module automates the extraction of device credential configurations from Cisco
Catalyst Center infrastructure, transforming them into YAML playbooks compatible
with device_credential_workflow_manager module. It retrieves global device
credentials (CLI, HTTPS Read/Write, SNMPv2c Read/Write, SNMPv3) and site-specific
credential assignments via REST APIs, applies optional component-based filters for
targeted extraction, masks sensitive fields with Jinja2 variable placeholders, and
generates formatted YAML files for configuration documentation, credential auditing,
disaster recovery, and multi-site credential standardization workflows.
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
__author__ = "Vivek Raj, Madhan Sankaranarayanan"
DOCUMENTATION = r"""
---
module: device_credential_playbook_config_generator
short_description: Generate YAML configurations playbook for 'device_credential_workflow_manager' module.
description:
- Automates brownfield YAML playbook generation for device credential
configurations deployed in Cisco Catalyst Center infrastructure.
- Extracts global device credentials (CLI, HTTPS Read/Write, SNMPv2c Read/Write,
SNMPv3) and site-specific credential assignments via REST APIs.
- Generates YAML files compatible with device_credential_workflow_manager module
for configuration documentation, credential auditing, disaster recovery, and
multi-site credential standardization.
- Supports auto-discovery mode for complete credential infrastructure extraction
or component-based filtering for targeted extraction (global credentials,
site assignments).
- Masks sensitive fields (passwords, community strings, auth credentials) with
Jinja2 variable placeholders for secure playbook generation.
- Transforms camelCase API responses to snake_case YAML format with comprehensive
header comments and metadata.
version_added: 6.44.0
extends_documentation_fragment:
- cisco.dnac.workflow_manager_params
author:
- Vivek Raj (@vivekraj2000)
- Madhan Sankaranarayanan (@madhansansel)
options:
state:
description:
- Desired state for YAML playbook generation workflow.
- Only 'gathered' state supported for brownfield credential extraction.
type: str
choices: [gathered]
default: gathered
file_path:
description:
- Absolute or relative path for YAML configuration file output.
- If not provided, generates default filename in current working directory
with pattern
C(device_credential_playbook_config_<YYYY-MM-DD_HH-MM-SS>.yml).
- Example default filename
C(device_credential_playbook_config_2026-01-24_12-33-20.yml).
- Directory created automatically if path does not exist.
- Supports YAML file extension (.yml or .yaml).
type: str
required: false
file_mode:
description:
- Controls how config is written to the YAML file.
- C(overwrite) replaces existing file content.
- C(append) appends generated YAML content to the existing file.
type: str
choices: ["overwrite", "append"]
default: "overwrite"
required: false
config:
description:
- Top-level configuration block that controls the
scope and filtering of the generated YAML playbook
for the C(device_credential_workflow_manager) module.
- Contains C(component_specific_filters) to select
which credential components (global credentials,
site assignments) and which individual credentials
are included in the output.
- If C(config) is not provided or is empty, all global
credentials and all site credential assignments are
extracted (auto-discovery mode).
- This is useful for complete brownfield infrastructure
discovery and documentation.
type: dict
required: false
suboptions:
component_specific_filters:
description:
- Container for all component-level and credential-level
filters that control what is included in the generated
YAML playbook.
- Holds C(components_list) to select which top-level
components to extract, and optional per-component
filters (C(global_credential_details),
C(assign_credentials_to_site)) for fine-grained
credential or site selection.
- If C(components_list) is specified, only the listed
components are included regardless of other filters.
- If per-component filters are provided without
explicitly including them in C(components_list),
those components are automatically added to
C(components_list).
- At least one of C(components_list) or per-component
filters must be provided.
type: dict
suboptions:
components_list:
description:
- Selector that determines which top-level
credential components are extracted from
Catalyst Center and written to the YAML
playbook.
- Valid values are C(global_credential_details)
for global credentials and
C(assign_credentials_to_site) for site-specific
credential assignments.
- If specified, only the listed components are
included in the generated YAML file.
- If not specified but per-component filters
(C(global_credential_details) or
C(assign_credentials_to_site)) are provided,
those components are automatically added to
this list.
- If neither C(components_list) nor any
per-component filters are provided, an error
is raised.
type: list
choices:
- global_credential_details
- assign_credentials_to_site
elements: str
global_credential_details:
description:
- List of credential filter entries for global device credential extraction.
- Each entry specifies a credential C(type) and an optional C(description).
- C(description) is a list of strings; each value must match a Catalyst
Center credential description exactly (case-sensitive).
- If C(description) is omitted (or empty) for a given C(type), all
credentials of that type are extracted.
- When multiple entries with different C(type) values are provided,
each type is filtered independently (AND logic across types).
- If C(global_credential_details) is omitted entirely but
C(global_credential_details) is present in C(components_list),
all credentials of all types are extracted without filtering.
- 'For example, [{"type": "cli_credential", "description": ["WLC", "Router_CLI"]},
{"type": "https_read"}, {"type": "snmp_v3", "description": ["SNMPv3_Admin"]}]'
type: list
elements: dict
required: false
suboptions:
type:
description:
- Credential type to filter.
- Must be one of cli_credential, https_read, https_write,
snmp_v2c_read, snmp_v2c_write, snmp_v3.
type: str
required: true
choices:
- cli_credential
- https_read
- https_write
- snmp_v2c_read
- snmp_v2c_write
- snmp_v3
description:
description:
- Human-readable labels assigned to credentials
in Catalyst Center, used here as filter
values to select specific credentials of the
given C(type).
- Each value must match a Catalyst Center
credential description exactly
(case-sensitive).
- If omitted or empty, all credentials of the
specified C(type) are extracted.
- When multiple entries share the same C(type),
their C(description) lists are merged
(union).
- 'For example: ["WLC", "Router_CLI"]'
type: list
elements: str
required: false
assign_credentials_to_site:
description:
- Site-level credential assignments that map global
credentials to specific sites in the Catalyst
Center site hierarchy.
- This parameter accepts a list of site
hierarchical path strings to control which site
assignments are extracted into the generated
YAML playbook.
- Each string must be a full hierarchical site
path starting from "Global"
(e.g., "Global/Region/Building").
- Site names are case-sensitive and must match
exact paths configured in Catalyst Center.
- If not specified when component is included in
C(components_list), extracts all site credential
assignments.
- 'For example:
["Global/India/Assam", "Global/India/Haryana"]'
type: list
elements: str
required: false
requirements:
- dnacentersdk >= 2.10.10
- python >= 3.9
- PyYAML >= 5.1
notes:
- SDK methods utilized - discovery.get_all_global_credentials,
site_design.get_sites, network_settings.get_device_credential_settings_for_a_site
- API paths utilized - GET /dna/intent/api/v2/global-credential,
GET /dna/intent/api/v1/sites, GET /dna/intent/api/v1/sites/${id}/deviceCredentials
- Module is idempotent; multiple runs generate identical YAML content except
timestamp in header comments.
- Check mode supported; validates parameters without file generation.
- Sensitive credential fields (passwords, community strings, auth credentials)
masked with Jinja2 variable placeholders (e.g., {{ cli_credential_wlc_password }}).
- Generated YAML uses OrderedDumper for consistent key ordering enabling version
control.
- Description-based filtering is case-sensitive and requires exact matches.
- Site hierarchical paths must match exact Catalyst Center site structure.
- 'Auto-population of components_list:
If component-specific filters (such as global_credential_details or assign_credentials_to_site) are provided
without explicitly including them in components_list, those components will be
automatically added to components_list. This simplifies configuration by eliminating
the need to redundantly specify components in both places.'
- 'Example of auto-population behavior:
If you provide filters for global_credential_details without including global_credential_details in components_list,
the module will automatically add global_credential_details to components_list before processing.
This allows you to write more concise playbooks.'
- 'Validation requirements:
If component_specific_filters is provided, at least one of the following must be true -
(1) components_list contains at least one component, OR
(2) Component-specific filters (e.g., global_credential_details, assign_credentials_to_site) are provided.
If neither condition is met, the module will fail with a validation error.'
seealso:
- module: cisco.dnac.device_credential_workflow_manager
description: Module for managing device credential workflows in Cisco Catalyst Center.
"""
EXAMPLES = r"""
- name: Generate YAML playbook for device credential workflow manager
which includes all global credentials and site assignments
cisco.dnac.device_credential_playbook_config_generator:
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: true
dnac_log_level: DEBUG
state: gathered
file_mode: "overwrite"
- name: Generate YAML Configuration with File Path specified
cisco.dnac.device_credential_playbook_config_generator:
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: true
dnac_log_level: DEBUG
state: gathered
file_mode: "append"
file_path: "device_credential_config.yml"
- name: Generate YAML Configuration with specific component global credential filters
cisco.dnac.device_credential_playbook_config_generator:
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: true
dnac_log_level: DEBUG
state: gathered
file_path: "device_credential_config.yml"
file_mode: "overwrite"
config:
component_specific_filters:
components_list: ["global_credential_details"]
global_credential_details:
- type: cli_credential
description:
- WLC
- Router_CLI
- type: https_read
description:
- http_read
- type: https_write
description:
- http_write
- type: snmp_v2c_read
- type: snmp_v2c_write
- type: snmp_v3
- name: Generate YAML Configuration with specific component assign credentials to site filters
cisco.dnac.device_credential_playbook_config_generator:
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: true
dnac_log_level: DEBUG
state: gathered
file_path: "device_credential_config.yml"
file_mode: "append"
config:
component_specific_filters:
components_list: ["assign_credentials_to_site"]
assign_credentials_to_site:
- "Global/India/Assam"
- "Global/India/Haryana"
- name: Generate YAML with aggregated duplicate type filters
cisco.dnac.device_credential_playbook_config_generator:
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: true
dnac_log_level: DEBUG
state: gathered
file_path: "device_credential_config.yml"
config:
component_specific_filters:
components_list:
- global_credential_details
global_credential_details:
# Two entries for same type — descriptions are merged
- type: cli_credential
description:
- WLC
- type: cli_credential
description:
- Router_CLI
# Omitting description extracts all of this type
- type: snmp_v3
- name: Generate YAML Configuration with both global credential and assign credentials to site filters
cisco.dnac.device_credential_playbook_config_generator:
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: true
dnac_log_level: DEBUG
state: gathered
file_path: "device_credential_config.yml"
file_mode: "append"
config:
component_specific_filters:
components_list: ["global_credential_details", "assign_credentials_to_site"]
global_credential_details:
- type: cli_credential
description:
- WLC
- type: https_read
description:
- http_read
- type: https_write # No description filter — extracts all
assign_credentials_to_site:
- "Global/India/Assam"
- "Global/India/TamilNadu"
"""
RETURN = r"""
# Case_1: Successful YAML Generation
response_1:
description:
- Response returned when YAML configuration generation completes successfully
with all requested credentials and site assignments extracted and written to
file.
- Includes operation summary with component counts, configuration counts, and
file path details.
- Generated YAML file contains formatted playbook compatible with
C(device_credential_workflow_manager) module.
returned: always
type: dict
sample:
response:
status: success
message: >-
YAML configuration file generated successfully for module
'device_credential_workflow_manager'
file_path: device_credential_config.yml
components_processed: 2
components_skipped: 0
configurations_count: 2
msg:
status: success
message: >-
YAML configuration file generated successfully for module
'device_credential_workflow_manager'
file_path: device_credential_config.yml
components_processed: 2
components_skipped: 0
configurations_count: 2
status: success
# Case_2: No Configurations Found
response_2:
description:
- Response returned when no device credentials or site assignments are found
matching the specified filters or in the Catalyst Center system.
- Operation status is C(ok) indicating successful execution but no data
available to generate.
- No YAML file is created when no configurations are found.
- C(components_attempted) shows which components were requested for extraction.
returned: always
type: dict
sample:
response:
status: ok
message: >-
No configurations found for module 'device_credential_workflow_manager'.
Verify filters and component availability. Components attempted:
['global_credential_details', 'assign_credentials_to_site']
components_attempted: 2
components_processed: 0
components_skipped: 2
msg:
status: ok
message: >-
No configurations found for module 'device_credential_workflow_manager'.
Verify filters and component availability. Components attempted:
['global_credential_details', 'assign_credentials_to_site']
components_attempted: 2
components_processed: 0
components_skipped: 2
status: ok
# Case_3: Validation Error
response_3:
description:
- Response returned when playbook configuration parameters fail validation
before YAML generation begins.
- Occurs when invalid filter parameters, incorrect data types, or unsupported
component names are provided.
- No API calls executed and no file generation attempted.
- Error message provides specific validation failure details and allowed
parameter values.
returned: always
type: dict
sample:
response: >-
Validation Error: 'component_specific_filters' must be
provided with 'components_list' key when 'generate_all_configurations'
is set to False.
msg: >-
Validation Error: 'component_specific_filters' must be
provided with 'components_list' key when 'generate_all_configurations'
is set to False.
status: failed
msg:
description:
- Human-readable message describing the operation result.
- Indicates success, failure, or informational status of YAML generation.
- Provides high-level summary with file path and configuration counts for
success scenarios.
- Provides error details for validation or generation failures.
returned: always
type: str
sample: >-
YAML configuration file generated successfully for module
'device_credential_workflow_manager'
"""
import time
from collections import OrderedDict
# Third-party imports
try:
import yaml
HAS_YAML = True
except ImportError:
HAS_YAML = False
yaml = None
from ansible.module_utils.basic import AnsibleModule
# Local application/library-specific imports
from ansible_collections.cisco.dnac.plugins.module_utils.brownfield_helper import (
BrownFieldHelper,
)
from ansible_collections.cisco.dnac.plugins.module_utils.dnac import (
DnacBase,
)
if HAS_YAML:
class OrderedDumper(yaml.Dumper):
def represent_dict(self, data):
return self.represent_mapping("tag:yaml.org,2002:map", data.items())
OrderedDumper.add_representer(OrderedDict, OrderedDumper.represent_dict)
else:
OrderedDumper = None
class DeviceCredentialPlaybookConfigGenerator(DnacBase, BrownFieldHelper):
"""
Brownfield playbook generator for Cisco Catalyst Center device credentials.
This class orchestrates automated YAML playbook generation for device credential
configurations by extracting existing settings from Cisco Catalyst Center via
REST APIs and transforming them into Ansible playbooks compatible with the
device_credential_workflow_manager module.
The generator supports both auto-discovery mode (extracting all configured
credentials and site assignments) and targeted extraction mode (filtering by
credential types and site names) to facilitate brownfield infrastructure
documentation, configuration backup, migration planning, and multi-site
deployment standardization workflows.
Key Capabilities:
- Extracts six credential types (CLI, HTTPS Read/Write, SNMPv2c Read/Write,
SNMPv3) with description-based filtering from global credential store
- Retrieves site credential assignments mapping credentials to site hierarchies
for multi-site deployment documentation
- Masks sensitive credential fields (passwords, community strings, auth passwords)
with Jinja variable placeholders to prevent raw credential exposure in YAML
- Generates YAML files with comprehensive header comments including metadata,
generation timestamp, configuration summary statistics, and usage instructions
- Transforms camelCase API response keys to snake_case YAML format for improved
playbook readability and maintainability
Inheritance:
DnacBase: Provides Cisco Catalyst Center API connectivity, authentication,
request execution, logging infrastructure, and common utility methods
BrownFieldHelper: Provides parameter transformation utilities, reverse mapping
functions, and configuration processing helpers for brownfield
operations including modify_parameters() and YAML generation
Class-Level Attributes:
supported_states (list): List of supported Ansible states, currently
['gathered'] for configuration extraction workflow
module_schema (dict): Network elements schema configuration mapping API
families, functions, filters, and reverse mapping
specifications for credential components
site_id_name_dict (dict): Cached mapping of site UUIDs to hierarchical site
names from Catalyst Center for site name resolution
global_credential_details (dict): Cached global credentials grouped by type
(cliCredential, httpsRead, etc.) from
discovery.get_all_global_credentials API
module_name (str): Target workflow manager module name for generated playbooks
('device_credential_workflow_manager')
values_to_nullify (list): List of string values to treat as None during
processing (e.g., ['NOT CONFIGURED'])
Workflow Execution:
1. validate_input() - Validates playbook configuration parameters and filters
2. get_want() - Constructs desired state parameters from validated configuration
3. get_diff_gathered() - Orchestrates YAML generation workflow execution
4. yaml_config_generator() - Generates YAML file with header and configurations
5. get_global_credential_details_configuration() - Retrieves global credentials
6. get_assign_credentials_to_site_configuration() - Retrieves site assignments
7. filter_credentials() - Applies description-based credential filtering
8. write_dict_to_yaml() - Writes formatted YAML with header comments to file
Error Handling:
- Comprehensive parameter validation with detailed error messages
- API exception handling with error tracking and logging
- File I/O error handling with fallback messaging and status reporting
- Component-specific filter validation preventing invalid configurations
- Credential ID matching validation with warnings for missing credentials
Version Requirements:
- Cisco Catalyst Center: 2.3.7.9 or higher
- dnacentersdk: 2.10.10 or higher
- Python: 3.9 or higher
- PyYAML: 5.1 or higher (for YAML serialization with OrderedDumper)
Notes:
- The class is idempotent; multiple runs with same parameters generate
identical YAML content (except generation timestamp in header comments)
- Check mode is supported but does not perform actual file generation;
validates parameters and returns expected operation results
- Large-scale deployments with many credentials and sites may require
increased dnac_api_task_timeout values for complete data extraction
- Generated YAML files use OrderedDumper for consistent key ordering across
multiple generations enabling reliable version control
- Credential description fields are case-sensitive and must match exact
descriptions configured in Catalyst Center
- Site names must be full hierarchical paths (e.g., 'Global/India/Assam')
and are case-sensitive matching exact site hierarchy
See Also:
device_credential_workflow_manager: Target module for applying generated
credential configurations to Catalyst
Center instances
"""
values_to_nullify = ["NOT CONFIGURED"]
def __init__(self, module):
"""
Initialize an instance of the class.
Args:
module: The module associated with the class instance.
Returns:
The method does not return a value.
"""
self.supported_states = ["gathered"]
super().__init__(module)
self.module_schema = self.get_workflow_filters_schema()
self.site_id_name_dict = self.get_site_id_name_mapping()
self.log(
"Site ID to Name mapping: {0}".format(self.site_id_name_dict),
"DEBUG",
)
self.global_credential_details = self.dnac._exec(
family="discovery", function="get_all_global_credentials", op_modifies=False
).get("response", [])
self.module_name = "device_credential_workflow_manager"
def validate_input(self):
"""
This function performs comprehensive validation of input configuration parameters
by checking parameter presence, validating against expected schema specification,
verifying minimum requirements for brownfield credential extraction, and setting
validated configuration for downstream processing workflows.
Returns:
object: 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.
"""
self.log(
"Starting validation of playbook configuration parameters. Checking "
"configuration availability, schema compliance, and minimum requirements "
"for device credential extraction workflow.",
"DEBUG"
)
# Check if configuration is available
if not self.config:
self.status = "success"
self.validated_config = {"generate_all_configurations": True}
self.msg = "Configuration is not provided or empty - treating as generate_all_configurations mode"
self.log(self.msg, "INFO")
self.set_operation_result("success", False, self.msg, "INFO")
return self
self.log(
"Configuration found with {0} entries. Proceeding with schema validation "
"against expected parameter specification.".format(len(self.config)),
"DEBUG"
)
# Expected schema for configuration parameters
temp_spec = {
"component_specific_filters": {
"type": "dict",
"required": False
}
}
# Validate params
self.log("Validating configuration against schema.", "DEBUG")
valid_temp = self.validate_config_dict(self.config, temp_spec)
self.log(
"Schema validation passed successfully. All parameters conform to expected "
"types and structure. Total valid entries: {0}.".format(len(valid_temp)),
"DEBUG"
)
self.log("Validating invalid parameters against provided config", "DEBUG")
self.validate_invalid_params(self.config, temp_spec.keys())
# Auto-populate components_list from component filters and validate
component_specific_filters = valid_temp.get("component_specific_filters")
if component_specific_filters:
self.auto_populate_and_validate_components_list(component_specific_filters)
# Set the validated configuration and update the result with success status
self.validated_config = valid_temp
self.msg = (
"Successfully validated playbook configuration parameters using "
"'validated_input': {0}".format(str(valid_temp))
)
self.set_operation_result("success", False, self.msg, "INFO")
self.log(
"Validation completed successfully. Returning self instance with status "
"'success' and validated_config populated for method chaining.",
"DEBUG"
)
return self
def get_workflow_filters_schema(self):
"""
Constructs workflow filter schema for device credential network elements.
This function defines the complete schema specification for device credential
workflow manager operations including filter specifications for global
credentials and site assignments, reverse mapping functions for data
transformation, API configuration for Catalyst Center integration, and
operation handler functions for configuration retrieval enabling consistent
parameter validation, API execution, and YAML generation throughout the
module lifecycle.
Returns:
dict: Dictionary containing network_elements schema configuration with:
- global_credential_details: Complete configuration including:
- filters: Parameter specifications for credential types (CLI,
HTTPS, SNMPv2c, SNMPv3) with description filtering
- reverse_mapping_function: Function reference for API to YAML
format transformation with sensitive field masking
- get_function_name: Method reference for retrieving global
credential configurations
- assign_credentials_to_site: Complete configuration including:
- filters: List containing site_name parameter for filtering
- reverse_mapping_function: Function reference for site
assignment transformation
- api_function: API method name for credential settings retrieval
- api_family: SDK family name (network_settings) for API execution
- get_function_name: Method reference for site assignment retrieval
"""
self.log(
"Constructing workflow filter schema for device credential network "
"elements. Schema defines filter specifications, reverse mapping functions, "
"API configuration, and handler functions for global credentials and site "
"assignments enabling consistent parameter validation and YAML generation.",
"DEBUG"
)
return {
"network_elements": {
"global_credential_details": {
"filters": {
"type": {
"type": "str",
"required": True,
"choices": [
"cli_credential",
"https_read",
"https_write",
"snmp_v2c_read",
"snmp_v2c_write",
"snmp_v3",
],
},
"description": {
"type": "list",
"elements": "str",
"required": False,
},
},
"reverse_mapping_function": self.global_credential_details_temp_spec,
"get_function_name": self.get_global_credential_details_configuration,
},
"assign_credentials_to_site": {
"filters": [],
"reverse_mapping_function": self.assign_credentials_to_site_temp_spec,
"api_function": "get_device_credential_settings_for_a_site",
"api_family": "network_settings",
"get_function_name": self.get_assign_credentials_to_site_configuration,
}
},
}
def global_credential_details_temp_spec(self):
"""
Constructs reverse mapping specification for global credential details.
This function generates the complete ordered dictionary structure defining
transformation rules for converting API response format to user-friendly YAML
format compatible with device_credential_workflow_manager module. Handles six
credential types (CLI, HTTPS Read/Write, SNMPv2c Read/Write, SNMPv3) with
sensitive field masking using custom variable placeholders to prevent raw
credential exposure in generated YAML files.
Args:
None: Uses class methods for credential masking and transformation logic.
Returns:
OrderedDict: Reverse mapping specification with credential type mappings:
- cli_credential: List transformation with description, username,
masked password and enable_password fields
- https_read: List transformation with description, username,
masked password, and port fields
- https_write: List transformation with description, username,
masked password, and port fields
- snmp_v2c_read: List transformation with description and
masked read_community fields
- snmp_v2c_write: List transformation with description and
masked write_community fields
- snmp_v3: List transformation with auth_type, snmp_mode,
masked privacy_password, privacy_type, username,
description, and masked auth_password fields
"""
self.log(
"Constructing reverse mapping specification for global credential details. "
"Specification defines transformation rules for 6 credential types (CLI, "
"HTTPS Read/Write, SNMPv2c Read/Write, SNMPv3) with sensitive field masking "
"to prevent raw credential exposure in generated YAML playbooks.",
"DEBUG"
)
# Mask helper builds a placeholder using description to ensure
# stable variable names (e.g., { { cli_credential_desc_password } }).
def mask(component_key, item, field):
"""
Generates masked variable placeholder for sensitive credential fields.
Creates Jinja-like variable references (e.g., {{ cli_credential_desc_password }})
to replace sensitive values preventing credential exposure in YAML output.
Args:
component_key (str): Credential type identifier (e.g., 'cli_credential')
item (dict): Credential item containing description for variable naming
field (str): Sensitive field name to mask (e.g., 'password')
Returns:
str: Masked variable placeholder or None if generation fails
"""
try:
self.log(
"Generating masked variable placeholder for component '{0}', "
"field '{1}' using description '{2}' for unique variable naming.".format(
component_key, field, item.get("description", "unknown")
),
"DEBUG"
)
masked_value = self.generate_custom_variable_name(
item,
component_key,
"description",
field,
)
self.log(
"Successfully generated masked placeholder: {0} for field '{1}' "
"in component '{2}'.".format(masked_value, field, component_key),
"DEBUG"
)
return masked_value
except Exception as e:
self.log(
"Failed to generate masked variable for component '{0}', "
"field '{1}': {2}. Returning None.".format(
component_key, field, str(e)
),
"ERROR"
)
return None
global_credential_details = OrderedDict({
"cli_credential": {
"type": "list",
"elements": "dict",
"source_key": "cliCredential",
"special_handling": True,
"transform": lambda detail: [
{
"description": key.get("description"),
"username": key.get("username"),
# Sensitive fields masked
"password": mask("cli_credential", key, "password"),
"enable_password": mask("cli_credential", key, "enable_password"),
}
for key in (detail.get("cliCredential") or [])
],
},
"https_read": {
"type": "list",
"elements": "dict",
"source_key": "httpsRead",
"special_handling": True,
"transform": lambda detail: [
{
"description": key.get("description"),
"username": key.get("username"),
# Sensitive field masked
"password": mask("https_read", key, "password"),
# Non-sensitive fields passed through
"port": key.get("port"),
}
for key in (detail.get("httpsRead") or [])
],
},
"https_write": {
"type": "list",
"elements": "dict",
"source_key": "httpsWrite",
"special_handling": True,
"transform": lambda detail: [
{
"description": key.get("description"),
"username": key.get("username"),
# Sensitive field masked
"password": mask("https_write", key, "password"),
# Non-sensitive fields passed through
"port": key.get("port"),
}
for key in (detail.get("httpsWrite") or [])
],
},
"snmp_v2c_read": {
"type": "list",
"elements": "dict",
"source_key": "snmpV2cRead",
"special_handling": True,
"transform": lambda detail: [
{
# Non-sensitive fields passed through
"description": key.get("description"),
# Sensitive field masked
"read_community": mask("snmp_v2c_read", key, "read_community"),
}
for key in (detail.get("snmpV2cRead") or [])
],
},
"snmp_v2c_write": {
"type": "list",
"elements": "dict",
"source_key": "snmpV2cWrite",
"special_handling": True,
"transform": lambda detail: [
{
"description": key.get("description"),
# Sensitive field masked
"write_community": mask("snmp_v2c_write", key, "write_community"),
}
for key in (detail.get("snmpV2cWrite") or [])
],
},
"snmp_v3": {
"type": "list",
"elements": "dict",
"source_key": "snmpV3",
"special_handling": True,
"transform": lambda detail: [
{
# Non-sensitive fields passed through
"auth_type": key.get("authType"),
"snmp_mode": key.get("snmpMode"),
"privacy_password": mask("snmp_v3", key, "privacy_password"),
"privacy_type": key.get("privacyType"),
"username": key.get("username"),
"description": key.get("description"),
# Sensitive field masked
"auth_password": mask("snmp_v3", key, "auth_password"),
}
for key in (detail.get("snmpV3") or [])
],
},
})
self.log(
"Reverse mapping specification constructed successfully with 6 credential "
"type transformations. Specification includes field mappings for username, "
"passwords (masked), ports, communities (masked for v2c read), auth settings "
"(masked for v3), and description fields for all credential types.",
"DEBUG"
)
self.log(
"Returning global credential details reverse mapping specification for use "
"in modify_parameters() transformation during YAML generation workflow.",
"DEBUG"
)
return global_credential_details
def assign_credentials_to_site_temp_spec(self):
"""
Constructs reverse mapping specification for site credential assignments.
This function generates the complete ordered dictionary structure defining
transformation rules for converting site credential assignment API responses
to user-friendly YAML format compatible with device_credential_workflow_manager
module. Extracts non-sensitive credential metadata (description, username, id)
for six credential types assigned to sites, preventing sensitive credential
data exposure while maintaining credential reference integrity through ID
mapping.
Args: