-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathbuild_resource_data.py
More file actions
970 lines (803 loc) · 40.4 KB
/
Copy pathbuild_resource_data.py
File metadata and controls
970 lines (803 loc) · 40.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
# Copyright (c) 2026 Cisco Systems, Inc. and its affiliates
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# SPDX-License-Identifier: MIT
"""
Build Resource Data — Consolidated Template→Render→Diff→Flag pipeline for all fabric types.
Replaces the dtc/common role's per-fabric-type sub_main_*.yml files and
~50 individual resource task files with a single data-driven action plugin.
Resource type metadata is loaded from resources/resource_types.yml.
Each resource declares its applicable fabric_types — the plugin filters
to only process entries matching the current fabric.
Implements the same Template→Render→Diff→Flag cycle as the original YAML tasks:
1. Backup previous rendered file (if exists)
2. Render Jinja2 template to output file
3. Load rendered YAML data into variable
4. Run structural diff (diff_compare) for resources that support it
5. Run MD5 diff (diff_model_changes) to detect any changes
6. Set change flag if data changed and save_previous is active
Entries with template: null are non-template steps dispatched to
internal methods by resource name:
- child_fabrics: Prepare MSD child fabric associations
- interface_all: Aggregate all interface types into combined lists
- check_msd_child: Validate overlay not managed from MSD child fabric
"""
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import copy
import hashlib
import os
import re
import shutil
import yaml
from ansible.plugins.action import ActionBase
from ansible.utils.display import Display
from ansible_collections.cisco.nac_dc_vxlan.plugins.plugin_utils.registry_loader import (
RegistryLoader,
)
from ansible_collections.cisco.nac_dc_vxlan.plugins.action.common.prepare_plugins.prep_005_resolve_env_vars import (
resolve_env_vars_recursive,
)
display = Display()
class ResourceDataBuilder:
"""
Core Template→Render→Diff→Flag pipeline logic.
Iterates through resource_types.yml filtered by fabric_type,
rendering templates, detecting changes, and collecting resource
data for downstream create/remove plugins.
"""
def __init__(self, params, action_module, task_vars, tmp=None):
self.fabric_type = params['fabric_type']
self.fabric_name = params['fabric_name']
self.data_model = params['data_model']
self.role_path = params['role_path']
self.run_map_diff_run = self._to_bool(params.get('run_map_diff_run', True))
self.force_run_all = self._to_bool(params.get('force_run_all', False))
self.check_roles = params.get('check_roles', {})
self.resource_filter = params.get('resource_filter', None)
self.action_module = action_module
self.task_vars = task_vars
self.tmp = tmp
# Load registries
collection_path = RegistryLoader.get_collection_path()
self.resource_types = RegistryLoader.load(collection_path, 'resource_types').get('resource_types', {})
self.fabric_types = RegistryLoader.load(collection_path, 'fabric_types').get('fabric_types', {})
# Get fabric type config
self.fabric_type_config = self.fabric_types.get(self.fabric_type, {})
self.file_subdir = self.fabric_type_config.get('file_subdir', '')
self.namespace = self.fabric_type_config.get('namespace', '')
# Output path: {role_path}/files/{file_subdir}/{fabric_name}/
self.output_path = os.path.join(
self.role_path, 'files', self.file_subdir, self.fabric_name
)
# Collected results
self.resource_data = {}
self.change_flags = {}
@staticmethod
def _to_bool(value):
"""Convert Ansible bool-like values into real booleans."""
if isinstance(value, bool):
return value
if isinstance(value, str):
return value.lower() in ('1', 'true', 'yes', 'on')
return bool(value)
def _should_run_structural_diff(self, diff_compare):
"""Structural diff data is only consumed during targeted diff runs."""
return bool(diff_compare) and self.run_map_diff_run and not self.force_run_all
def build(self):
"""
Execute the resource pipeline for the current fabric type.
Iterates resource_types.yml in order, processing only entries
whose fabric_types list includes the current fabric type.
Returns:
dict with:
- 'resource_data': Dict of rendered data keyed by resource_name
- 'change_flags': Dict of change flag states
- 'namespace': Fabric type namespace name
- 'failed': Boolean
- 'msg': Summary message
"""
# Cleanup output directory if not a diff run
# Skip cleanup when using resource_filter (deferred build) since the
# output directory was already set up by the common-phase build.
if not self.resource_filter:
if not self.run_map_diff_run or self.force_run_all:
self._cleanup_files()
# Ensure output directory exists
os.makedirs(self.output_path, exist_ok=True)
step_results = []
for resource_name, rt in self.resource_types.items():
# When resource_filter is set (deferred build for MSD/MCFG),
# process only the named resources and skip fabric_types check.
# Otherwise, apply the standard fabric_type filter.
if self.resource_filter:
if resource_name not in self.resource_filter:
continue
else:
applicable_fabrics = rt.get('fabric_types', [])
if self.fabric_type not in applicable_fabrics:
continue
template = rt.get('template')
# ── Non-template step: dispatch to internal method ────────
if template is None:
method_name = f'_{resource_name}'
try:
method = getattr(self, method_name)
except AttributeError:
step_results.append({
'resource_name': resource_name,
'status': 'failed',
'reason': f"Internal method '{method_name}' not found",
})
return {
'resource_data': self.resource_data,
'change_flags': self.change_flags,
'namespace': self.namespace,
'results': step_results,
'failed': True,
'msg': f"Internal method '{method_name}' not found on ResourceDataBuilder",
}
result = method(rt)
step_results.append({
'resource_name': resource_name,
'status': 'ok',
'result': result,
})
if isinstance(result, dict) and result.get('failed'):
return {
'resource_data': self.resource_data,
'change_flags': self.change_flags,
'namespace': self.namespace,
'results': step_results,
'failed': True,
'msg': result.get('msg', f"Step '{resource_name}' failed"),
}
continue
# ── Resolve template (apply fabric-specific override) ─────
template_overrides = rt.get('template_overrides', {})
if self.fabric_type in template_overrides:
template = template_overrides[self.fabric_type]
# ── Standard resource build ───────────────────────────────
result = self._build_resource(resource_name, rt, template)
step_results.append({
'resource_name': resource_name,
'status': 'ok' if not result.get('failed') else 'failed',
'result': result,
})
if result.get('failed'):
return {
'resource_data': self.resource_data,
'change_flags': self.change_flags,
'namespace': self.namespace,
'results': step_results,
'failed': True,
'msg': f"Build failed at step '{resource_name}': {result.get('msg', '')}",
}
# ── MSD/MCFG deferred overlay change detection ───────────────
# VRF/network overlay data for MSD/MCFG is not rendered during the
# common-phase build (deferred to _msite_build_overlay in the
# create/remove pipeline). However, we must detect overlay data model
# changes here so that changes_detected_any correctly gates the
# pipeline. Without this, adding VRFs/networks to MSD for the first
# time (or modifying them) would leave changes_detected_any=False
# and skip the entire create pipeline.
if not self.resource_filter and self.fabric_type in ('MSD', 'MCFG'):
self._detect_msite_overlay_changes()
# Compute aggregate change flag
self.change_flags['changes_detected_any'] = any(self.change_flags.values())
return {
'resource_data': self.resource_data,
'change_flags': self.change_flags,
'namespace': self.namespace,
'results': step_results,
'failed': False,
'msg': f"Common pipeline completed for {self.fabric_type} fabric '{self.fabric_name}'",
}
# ══════════════════════════════════════════════════════════════════════════
# Core Build Cycle
# ══════════════════════════════════════════════════════════════════════════
def _build_resource(self, resource_name, rt, template):
"""
Execute the Template→Render→Diff→Flag cycle for one resource.
Args:
resource_name: Logical name of the resource.
rt: Resource type config dict from resource_types.yml.
template: Template path (may be overridden by pipeline step).
Returns:
dict with build result.
"""
output_file = rt['output_file']
change_flag = rt['change_flag']
diff_compare = rt.get('diff_compare', False)
var_name = rt.get('var_name', resource_name)
output_file_path = os.path.join(self.output_path, output_file)
old_file_path = output_file_path + '.old'
# ── Step 1: Backup previous file ──────────────────────────────
if os.path.exists(output_file_path):
shutil.copy2(output_file_path, old_file_path)
os.remove(output_file_path)
# ── Step 2: Execute pre-hooks ─────────────────────────────────
pre_hook_data = {}
for hook in rt.get('pre_hooks', []):
hook_result = self._execute_hook(hook)
pre_hook_data[hook] = hook_result
# ── Step 3: Render template ───────────────────────────────────
try:
self._render_template(template, output_file_path)
except Exception as e:
return {
'failed': True,
'msg': f"Template rendering failed for {resource_name}: {str(e)}",
}
# ── Step 4: Load rendered data ────────────────────────────────
data = self._load_yaml(output_file_path)
# ── Step 5: Execute post-hooks ────────────────────────────────
for hook in rt.get('post_hooks', []):
hook_result = self._execute_post_hook(hook, resource_name, data)
if hook_result is not None:
pre_hook_data[hook] = hook_result
# ── Step 6: Structural diff (diff_compare) ───────────────────
diff_result = None
if self._should_run_structural_diff(diff_compare):
diff_result = self._run_diff_compare(old_file_path, output_file_path)
# ── Step 7: MD5 diff for change detection ─────────────────────
file_changed = self._run_diff_model_changes(old_file_path, output_file_path)
# ── Step 8: Set change flag ───────────────────────────────────
if change_flag and file_changed and self.check_roles.get('save_previous', False):
self.change_flags[change_flag] = True
# ── Store resource data ───────────────────────────────────────
# module_data is the authoritative data for downstream NDFC module calls.
# Default is the raw rendered template data. Post-hooks can override this
# by returning a 'module_data' key in their result dict (convention).
module_data = data
resource_entry = {'data': data, 'var_name': var_name}
if diff_result is not None:
resource_entry['diff'] = diff_result
# Store hook data alongside resource data
if pre_hook_data:
resource_entry['hook_data'] = pre_hook_data
# Convention: if any post-hook returned 'module_data', use it as the
# authoritative data for downstream modules (e.g., credential-enriched
# inventory from get_credentials).
for hook_result in pre_hook_data.values():
if isinstance(hook_result, dict) and 'module_data' in hook_result:
module_data = hook_result['module_data']
break
resolved_data = copy.deepcopy(module_data)
env_count = resolve_env_vars_recursive(resolved_data)
if env_count > 0:
module_data = resolved_data
display.vvv(
f"COMMON [{self.fabric_name}] Resolved {env_count} env_var_ "
f"token(s) in module_data for {resource_name}"
)
if module_data is not data:
resource_entry['module_data'] = module_data
self.resource_data[resource_name] = resource_entry
display.v(
f"COMMON [{self.fabric_name}] Built {resource_name}: "
f"items={len(data) if isinstance(data, list) else '?'}, "
f"changed={file_changed}"
)
return {'failed': False, 'changed': file_changed}
# ══════════════════════════════════════════════════════════════════════════
# Template Rendering
# ══════════════════════════════════════════════════════════════════════════
def _render_template(self, template_name, output_path):
"""
Render a Jinja2 template using Ansible's Templar.
Uses Ansible's Templar to render Jinja2 templates with all available
task variables. The template is loaded from the role's templates
directory.
Args:
template_name: Template path relative to role templates dir.
output_path: Absolute path for the rendered output file.
"""
from jinja2 import ChoiceLoader, FileSystemLoader
template_dir = os.path.join(self.role_path, 'templates')
template_path = os.path.join(template_dir, template_name)
if not os.path.exists(template_path):
raise FileNotFoundError(f"Template not found: {template_path}")
with open(template_path) as f:
template_content = f.read()
templar = self.action_module._templar
original_loader = templar.environment.loader
# Add role templates dir to Jinja2 loader for {% include %} and {% import %}
new_loader = ChoiceLoader([
FileSystemLoader(template_dir),
original_loader,
])
templar.environment.loader = new_loader
old_vars = templar.available_variables
try:
templar.available_variables = self.task_vars
rendered = templar.template(
template_content,
preserve_trailing_newlines=True,
convert_data=False,
)
finally:
templar.environment.loader = original_loader
templar.available_variables = old_vars
os.makedirs(os.path.dirname(output_path), exist_ok=True)
with open(output_path, 'w') as f:
f.write(rendered)
def _load_yaml(self, path):
"""Load a YAML file and return its contents, or empty list."""
if not os.path.exists(path):
return []
with open(path) as f:
data = yaml.safe_load(f)
return data if data else []
# ══════════════════════════════════════════════════════════════════════════
# Diff Operations
# ══════════════════════════════════════════════════════════════════════════
def _run_diff_model_changes(self, old_path, current_path):
"""
Compare previous and current files via MD5 hash (with omit placeholder normalization).
Replicates the logic from dtc.diff_model_changes action plugin.
If files are identical, removes the .old backup file.
Args:
old_path: Path to the previous file (.old).
current_path: Path to the current file.
Returns:
True if file data changed, False otherwise.
"""
if not os.path.exists(old_path):
return True
with open(old_path, 'r') as f:
data_previous = f.read()
with open(current_path, 'r') as f:
data_current = f.read()
md5_prev = hashlib.md5(data_previous.encode()).hexdigest()
md5_curr = hashlib.md5(data_current.encode()).hexdigest()
if md5_prev == md5_curr:
os.remove(old_path)
return False
# Normalize omit placeholders and compare again
pattern = r'__omit_place_holder__\S+'
data_previous = re.sub(pattern, 'NORMALIZED', data_previous, flags=re.MULTILINE)
data_current = re.sub(pattern, 'NORMALIZED', data_current, flags=re.MULTILINE)
md5_prev = hashlib.md5(data_previous.encode()).hexdigest()
md5_curr = hashlib.md5(data_current.encode()).hexdigest()
if md5_prev == md5_curr:
os.remove(old_path)
return False
return True
def _detect_msite_overlay_changes(self):
"""
Detect changes in MSD/MCFG multisite overlay data model.
VRF/network overlay resources for MSD/MCFG are built at pipeline
execution time by _msite_build_overlay, not during common-phase.
This method serializes the ENTIRE multisite overlay section of the
data model (including vrf_attach_groups and network_attach_groups)
to a sentinel file and compares against the previous version.
When a change is detected, sets BOTH the aggregate flag
(changes_detected_msite_overlay) AND per-resource flags
(changes_detected_vrfs, changes_detected_networks) so that
downstream pipeline steps pass their change_flag_guard checks.
Also cleans up the deferred build cache file from any prior
pipeline run in this playbook execution.
"""
# Clean up deferred build cache from prior pipeline runs so that
# each playbook run starts with a fresh cache.
cache_file = os.path.join(self.output_path, '_msite_overlay_cache.json')
if os.path.exists(cache_file):
os.remove(cache_file)
overlay = (
self.data_model
.get('vxlan', {})
.get('multisite', {})
.get('overlay', {})
)
sentinel_file = os.path.join(self.output_path, '_msite_overlay_sentinel.yml')
old_sentinel = sentinel_file + '.old'
# Handle empty/missing overlay: still need to detect removal of
# previously existing overlay data (user removed all VRFs/networks).
if not overlay:
if not os.path.exists(sentinel_file):
# No previous sentinel and no current overlay — nothing to detect
return
# Previous sentinel exists but overlay is now empty — detect removal
shutil.copy2(sentinel_file, old_sentinel)
os.remove(sentinel_file)
with open(sentinel_file, 'w') as f:
f.write(yaml.dump({}, default_flow_style=False, sort_keys=True))
if self._run_diff_model_changes(old_sentinel, sentinel_file):
if self.check_roles.get('save_previous', False):
self.change_flags['changes_detected_msite_overlay'] = True
self.change_flags['changes_detected_vrfs'] = True
self.change_flags['changes_detected_networks'] = True
display.v(
f"COMMON [{self.fabric_name}] Multisite overlay "
f"removed — all overlay data cleared"
)
return
# Backup previous sentinel file
if os.path.exists(sentinel_file):
shutil.copy2(sentinel_file, old_sentinel)
os.remove(sentinel_file)
# Capture the ENTIRE overlay dict (vrfs, networks, vrf_attach_groups,
# network_attach_groups, etc.) for change detection. Previously only
# vrfs and networks were captured, missing attach group modifications.
overlay_content = yaml.dump(
overlay,
default_flow_style=False,
sort_keys=True,
)
with open(sentinel_file, 'w') as f:
f.write(overlay_content)
overlay_vrfs = overlay.get('vrfs', [])
overlay_networks = overlay.get('networks', [])
# Compare using existing MD5 diff logic
if self._run_diff_model_changes(old_sentinel, sentinel_file):
if self.check_roles.get('save_previous', False):
self.change_flags['changes_detected_msite_overlay'] = True
# Set per-resource flags so pipeline steps pass their
# change_flag_guard checks. Both CREATE and REMOVE pipelines
# gate VRF/network steps on these flags.
if overlay_vrfs or self._sentinel_had_key(old_sentinel, 'vrfs'):
self.change_flags['changes_detected_vrfs'] = True
if overlay_networks or self._sentinel_had_key(old_sentinel, 'networks'):
self.change_flags['changes_detected_networks'] = True
display.v(
f"COMMON [{self.fabric_name}] Multisite overlay data "
f"model change detected (vrfs={len(overlay_vrfs)}, "
f"networks={len(overlay_networks)})"
)
def _sentinel_had_key(self, sentinel_path, key):
"""
Check if a previous sentinel file contained a non-empty value for key.
Used by _detect_msite_overlay_changes to determine which per-resource
change flags to set when the overlay data model has changed.
"""
if not os.path.exists(sentinel_path):
return False
try:
with open(sentinel_path) as f:
prev_data = yaml.safe_load(f)
return bool(prev_data.get(key)) if isinstance(prev_data, dict) else False
except (yaml.YAMLError, IOError):
return False
def _run_diff_compare(self, old_path, new_path):
"""
Run structural diff comparison for targeted create/remove data.
Delegates to the existing diff_compare action plugin to compute
updated, removed, and equal item lists.
Args:
old_path: Path to the previous file (.old).
new_path: Path to the current file.
Returns:
Dict with 'updated', 'removed', 'equal' lists.
"""
result = self._run_action_plugin(
"cisco.nac_dc_vxlan.dtc.diff_compare",
{"old_file": old_path, "new_file": new_path},
)
return result
# ══════════════════════════════════════════════════════════════════════════
# Action Plugin Invocation
# ══════════════════════════════════════════════════════════════════════════
def _run_action_plugin(self, action_name, args):
"""
Instantiate and run another action plugin by fully-qualified name.
Used for hooks like get_poap_data and get_credentials which are
action plugins (not modules) and cannot be called via _execute_module.
"""
task = self.action_module._task.copy()
task.action = action_name
task.args = args
action = self.action_module._shared_loader_obj.action_loader.get(
action_name,
task=task,
connection=self.action_module._connection,
play_context=self.action_module._play_context,
loader=self.action_module._loader,
templar=self.action_module._templar,
shared_loader_obj=self.action_module._shared_loader_obj,
)
if action is None:
return {
'failed': True,
'msg': f"Action plugin '{action_name}' not found via action_loader",
}
return action.run(task_vars=self.task_vars, tmp=self.tmp)
def _execute_rest(self, method, path):
"""
Execute a dcnm_rest API call.
Args:
method: HTTP method (GET, POST, etc.).
path: NDFC API path.
Returns:
Module result dict.
"""
return self.action_module._execute_module(
module_name="cisco.dcnm.dcnm_rest",
module_args={"method": method, "path": path},
task_vars=self.task_vars,
tmp=self.tmp,
)
# ══════════════════════════════════════════════════════════════════════════
# Hooks
# ══════════════════════════════════════════════════════════════════════════
def _execute_hook(self, hook_name):
"""
Execute a pre-hook before template rendering.
Currently supports:
- get_poap_data: Retrieve POAP data from POAP-enabled devices.
Args:
hook_name: Name of the hook to execute.
Returns:
Hook result dict.
"""
if hook_name == 'get_poap_data':
result = self._run_action_plugin(
"cisco.nac_dc_vxlan.dtc.get_poap_data",
{"data_model": self.data_model},
)
# Store poap_data in task_vars for template rendering
self.task_vars['poap_data'] = result
return result
display.warning(f"Unknown pre-hook: {hook_name}")
return {}
def _execute_post_hook(self, hook_name, resource_name, data):
"""
Execute a post-hook after template rendering and data loading.
Currently supports:
- get_credentials: Retrieve NDFC device credentials and update
inventory config.
Args:
hook_name: Name of the hook to execute.
resource_name: Name of the resource being built.
data: Rendered data from the template.
Returns:
Updated data dict, or None if hook doesn't modify data.
"""
if hook_name == 'get_credentials':
result = self._run_action_plugin(
"cisco.nac_dc_vxlan.common.get_credentials",
{"inv_list": data, "data_model": self.data_model},
)
if result.get('retrieve_failed'):
raise RuntimeError(f"Credential retrieval failed: {result}")
return result
display.warning(f"Unknown post-hook: {hook_name}")
return None
# ══════════════════════════════════════════════════════════════════════════
# File Operations
# ══════════════════════════════════════════════════════════════════════════
def _cleanup_files(self):
"""
Remove all files from the output directory for a clean full run.
Matches the original cleanup_files.yml behavior: delete directory
contents and recreate the empty directory.
"""
if os.path.exists(self.output_path):
shutil.rmtree(self.output_path)
os.makedirs(self.output_path, exist_ok=True)
# ══════════════════════════════════════════════════════════════════════════
# Internal Methods (called from pipeline via '_' prefix in resource_name)
# ══════════════════════════════════════════════════════════════════════════
def _interface_all(self, rt):
"""
Aggregate all individual interface type data into combined lists.
Produces two aggregated lists:
- interface_all_create: All interfaces EXCEPT breakout_preprov
(used by create pipeline with state: merged)
- interface_all_remove_overridden: ALL interfaces including breakout_preprov
(used by remove pipeline with state: overridden)
Also runs diff_compare on the aggregated list for targeted operations.
"""
interface_types_create = [
'interface_breakout',
'interface_trunk',
'interface_routed',
'sub_interface_routed',
'interface_access',
'interface_trunk_po',
'interface_access_po',
'interface_po_routed',
'interface_loopback',
'interface_dot1q',
'interface_vpc',
]
interface_types_remove = [
'interface_breakout',
'interface_breakout_preprov',
'interface_trunk',
'interface_routed',
'sub_interface_routed',
'interface_access',
'interface_trunk_po',
'interface_access_po',
'interface_po_routed',
'interface_loopback',
'interface_dot1q',
'interface_vpc',
]
# Aggregate create list (no breakout_preprov)
create_list = []
for itype in interface_types_create:
entry = self.resource_data.get(itype, {})
data = entry.get('data', []) if isinstance(entry, dict) else []
create_list.extend(data)
# Aggregate remove/overridden list (includes breakout_preprov)
remove_list = []
for itype in interface_types_remove:
entry = self.resource_data.get(itype, {})
data = entry.get('data', []) if isinstance(entry, dict) else []
remove_list.extend(data)
# Write aggregated file for diff comparison
output_file = os.path.join(self.output_path, 'ndfc_interface_all.yml')
old_file = output_file + '.old'
# Backup previous
if os.path.exists(output_file):
shutil.copy2(output_file, old_file)
os.remove(output_file)
# Write current
with open(output_file, 'w') as f:
yaml.dump(create_list, f, default_flow_style=False)
# Run structural diff only when downstream targeted processing needs it.
diff_result = None
if self._should_run_structural_diff(rt.get('diff_compare', False)):
diff_result = self._run_diff_compare(old_file, output_file)
# Run MD5 diff
file_changed = self._run_diff_model_changes(old_file, output_file)
# Set change flag
if file_changed and self.check_roles.get('save_previous', False):
self.change_flags['changes_detected_interfaces'] = True
# Store aggregated data
self.resource_data['interface_all'] = {
'data': create_list,
'data_remove_overridden': remove_list,
'var_name': 'interface_all_create',
}
if diff_result is not None:
self.resource_data['interface_all']['diff'] = diff_result
display.v(
f"COMMON [{self.fabric_name}] Aggregated interface_all: "
f"create={len(create_list)}, remove={len(remove_list)}, "
f"changed={file_changed}"
)
return {'failed': False}
def _child_fabrics(self, rt):
"""
Prepare MSD child fabric association data.
Delegates to the existing prepare_msite_child_fabrics_data plugin.
This is not template-based — it queries the controller for fabric
association information.
Sets the changes_detected_child_fabrics flag when there are child
fabrics to add or remove, so that changes_detected_any gates the
pipeline correctly. Without this, commenting out all child_fabrics
in the data model would leave changes_detected_any=False and skip
the entire remove pipeline, preventing child fabric removal.
"""
child_fabrics = self.data_model.get('vxlan', {}).get('multisite', {}).get('child_fabrics')
if not child_fabrics:
child_fabrics = []
result = self._run_action_plugin(
"cisco.nac_dc_vxlan.dtc.prepare_msite_child_fabrics_data",
{
"parent_fabric": self.fabric_name,
"parent_fabric_type": self.fabric_type,
"child_fabrics": child_fabrics,
},
)
self.resource_data['child_fabrics'] = {
'data': result,
'var_name': 'child_fabrics',
}
# Signal that child fabric changes are pending so that
# changes_detected_any is set and the pipeline is not skipped.
to_be_added = result.get('to_be_added', [])
to_be_removed = result.get('to_be_removed', [])
if (to_be_added or to_be_removed) and self.check_roles.get('save_previous', False):
self.change_flags['changes_detected_child_fabrics'] = True
display.v(
f"COMMON [{self.fabric_name}] Child fabric changes detected: "
f"to_add={len(to_be_added)}, to_remove={len(to_be_removed)}"
)
return result
def _check_msd_child(self, rt):
"""
Check if the current fabric is an active child in an MSD deployment.
If the fabric is a child of an MSD parent, VRFs and Networks cannot
be managed from the child fabric level — they must be managed from
the MSD parent. This method fails the pipeline if the user attempts
to manage overlay resources from a child fabric.
"""
# Check if already determined
is_child = self.task_vars.get('is_active_child_fabric')
if is_child is None:
# Query controller for MSD fabric associations
result = self._execute_rest(
"GET",
"/appcenter/cisco/ndfc/api/v1/lan-fabric/rest/control"
"/fabrics/msd/fabric-associations",
)
is_child = False
try:
associations = result.get('response', {}).get('DATA', [])
if isinstance(associations, list):
for assoc in associations:
if (assoc.get('fabricName') == self.fabric_name and
assoc.get('fabricParent', 'None') != 'None'):
is_child = True
break
except (KeyError, TypeError, IndexError):
pass
# Store for downstream use
self.task_vars['is_active_child_fabric'] = is_child
# Check for overlay data on child fabric
vrf_entry = self.resource_data.get('vrfs', {})
vrf_data = vrf_entry.get('data', []) if isinstance(vrf_entry, dict) else []
net_entry = self.resource_data.get('networks', {})
net_data = net_entry.get('data', []) if isinstance(net_entry, dict) else []
if is_child and vrf_data:
return {
'failed': True,
'msg': (
f"VRFs cannot be managed from fabric '{self.fabric_name}' "
f"as it is a child fabric part of a Multisite fabric."
),
}
if is_child and net_data:
return {
'failed': True,
'msg': (
f"Networks cannot be managed from fabric '{self.fabric_name}' "
f"as it is a child fabric part of a Multisite fabric."
),
}
return {'failed': False, 'is_active_child_fabric': is_child}
class ActionModule(ActionBase):
"""
Ansible ActionBase wrapper for build_resource_data.
Handles parameter validation, error handling, and delegation
to the ResourceDataBuilder domain class.
"""
REQUIRED_PARAMS = [
'fabric_type', 'fabric_name', 'data_model', 'role_path',
]
def run(self, tmp=None, task_vars=None):
results = super(ActionModule, self).run(tmp, task_vars)
task_vars = task_vars or {}
# Validate required parameters
params = self._task.args
missing = [p for p in self.REQUIRED_PARAMS if p not in params]
if missing:
results['failed'] = True
results['msg'] = f"Missing required parameters: {missing}"
return results
try:
builder = ResourceDataBuilder(params, self, task_vars, tmp)
result = builder.build()
results.update(result)
if result.get('failed'):
results['failed'] = True
else:
results['changed'] = any(
r.get('result', {}).get('changed', False)
for r in result.get('results', [])
if isinstance(r.get('result'), dict)
)
except Exception as e:
results['failed'] = True
results['msg'] = f"Build resource data failed: {str(e)}"
return results