Chapter 8 Data Models and Dynamic Templates
For diagrams, tables, or exact code formatting, .
spanning-tree vlan {{ vlan_list }} priority {{ host_spanning_tree_value }}
{% endfor %}
{% endfor %}
{% endif %}
This might look complicated because we have a loop nested inside another loop. Scenarios exist where
it is required to nest loops. It is not that difficult if good syntax and a consistent approach is taken.First, evaluate if a data dictionary, host_spanning_tree_values is defined. If so, loop through the list host_spanning_tree_values. Each item in the list will also be a list: vlan_list. Notice the syntax used in the second loop, using square brackets and the name of the list item makes it human-readable.
Ultimately it produces the line spanning-tree vlan {{ vlan_list }} priority {{ host_spanning_tree_value }} for each nested list item in the data dictionary. The following data model:
host_spanning_tree_values:
24576:
- 2-3,10-13,20,30,50,100,200
Results in the following configuration:
spanning-tree vlan 2-3,10-13,20,30,50,100,200 priority 24576And the template allows the configuration or intent to scale as well as different priorities for different lists of VLANs.
Recommended Practices Some general guidelines to help write templates that are human-readable and easy to change in collaboration with a full NetDevOps team:
Use meaningful names for all files, variables, and data models. Differentiate between data found in group_vars and host_vars with standard prefixes on variables in data dictionaries. Keep templates small, modular, and focused on specific tasks, features, platforms, or technologies. Do not write massive one size fits all templates designed to provide full coverage of a device. Model data and abstract it from configurations. Do not nest too deep in multi-layered “for” loops or “if” statements. Write code in VS Code with the Jinja2 extension installed and the YAML extension installed. Establish best practices and share them with the team.
After learning and developing skills, refactor code often.
