Chapter 8 Data Models and Dynamic Templates

For diagrams, tables, or exact code formatting, .

JOHN W. CAPOBIANCOPRINTED PAGE 139

The template is composed of a mix of static explicit data replacement, “if” / “else” / “end if” logic, and “for” loop logic.

Every device requires a hostname. This is a good place to start looking closer at the format of the template.

hostname {{ host_defaults.hostname }} The Cisco IOS command to configure a hostname is hostname <desired hostname>. This is present on every IOS device so should be set in a global or hostname template early in the configuration because it is near the top of the running-configuration. This variable is in the host_vars data dictionary. The dictionary is called host_defaults and the key-pair value is accessible as .hostname. A key-pair value is a set of two linked data items: a key, which is a unique identifier for some item of data, and the value, which is either the data that is identified or a pointer to the location of that data.

Here is an explicitly evaluated “if” statement: {% if platform_defaults.type == 6000 %} boot system bootdisk:{{ platform_defaults.boot }} {% endif %} If the value in the key-pair value type in the data dictionary platform_defaults is equal to 6000 add the following configuration line to the template. Look up the value of the boot key-pair value in the data dictionary platform_defaults and replace this variable with the information.

A more complex example: {% if platform_defaults.type == 6000 %} port-channel load-balance src-dst-mixed-ip-port {% else %} {% if platform_defaults.type == 4000 or platform_defaults.type == 3850 %} port-channel load-balance src-dst-port {% endif %} {% endif %} First, we are evaluating the value in the key-pair value type in the data dictionary platform_defaults. If the value equals 6000 run the command port-channel load-balance src-dst-mixed-ip-port otherwise if the same value equals 4000 or 3850 run the command port-channel load-balance src-dst-port.

Here is an example of a “for” loop: 
 
{%  for access_list in global_campus_access_lists %} 
{%      if global_campus_access_lists[access_list].permit is defined %} 
{%          for permit in global_campus_access_lists[access_list].permit %} 
access-list {{ access_list }} permit {{ permit }} 
{%          endfor %} 
{%  endif %} 
 
“For” loops can be nested: 
 
{%  if host_spanning_tree_values is defined %} 
{%      for host_spanning_tree_value in host_spanning_tree_values %} 
{%          for vlan_list in host_spanning_tree_values[host_spanning_tree_value] %}