Jinja2 templates, loops, trim_blocks & data in YAML
Generate configuration with templates
Lesson 10 of 20 · 15 min · Module 3: Change the network
Building configuration lines with Python strings gets messy fast. A template keeps the configuration readable, and the values that change live in a data file.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Fill a template with values
- Repeat a block for each item in a list
- Remove the empty lines that block tags leave
The idea
A Jinja2 template is configuration text with placeholders. {{ port.name }} inserts a value, and {% for port in ports %} ... {% endfor %} repeats a block. Template(text, trim_blocks=True, lstrip_blocks=True) removes the empty lines that the block tags would leave behind. render(ports=...) returns the finished text, and splitlines() turns it into the list that send_config_set expects. The data comes from YAML, so changing a port means editing the data, not the code.
from jinja2 import Template
template = Template("interface {{ name }}\n description {{ text }}")
print(template.render(name="GigabitEthernet0/6", text="Phone 2.06"))
01Placeholders
Everything outside {{ }} is copied as it is; each placeholder is replaced by the value you pass to render().
from jinja2 import Template
print(Template("hostname {{ name }}").render(name="sw2"))hostname sw202Loops leave empty lines
A block tag on its own line still ends with a newline, so the output gets empty lines. splitlines() shows them as empty strings.
LOOP = """{% for vid in vlans %}
vlan {{ vid }}
{% endfor %}"""
print(Template(LOOP).render(vlans=[10, 20]).splitlines())['', 'vlan 10', '', 'vlan 20']03trim_blocks and lstrip_blocks
trim_blocks drops the newline after a block tag, and lstrip_blocks drops the spaces before it. The output is then exactly the lines you meant.
template = Template(LOOP, trim_blocks=True, lstrip_blocks=True)
print(template.render(vlans=[10, 20]).splitlines())['vlan 10', 'vlan 20']Your turn
ports.yaml and write a Jinja2 template that renders, for every port, the lines interface ..., description ..., switchport mode access and switchport access vlan .... Store the rendered text in config and print it. Then push it to the switch named in the file (sw2 at 10.0.0.12) with error_pattern, and save.What the checks look for
- config has a block for every port
- config has no empty lines
- Gi0/6 is in VLAN 20 as Phone 2.06
- Gi0/7 is in VLAN 10 as Desk 2.07
- sw2 is saved
- Rendered with Jinja2
Take this with you
Data in YAML, layout in a template; Python only joins them and sends the result.
Go a little further
Add shutdown: true to one port in a copy of the YAML, and render shutdown for that port only with {% if port.shutdown %}.