2
Most read
6
Most read
8
Most read
PythonTemplates for
Network Automation
Rick Sherman
VulgarPython.com
What are templates and why use
them?
A template is a text document where some or all of the
content is automatically generated.
Templates are text files in the format you already work
with.
Data is stored separated and automatically loaded.
Easily re-used and shared.
Quick Example – Configuration file
system {
host-name tp8;
name-server 192.168.5.68;
domain-name shermdog.com;
backup-router 192.168.71.254;
root-authentication {
encrypted-password
"$1$hKWBk3fAgDHF/"; ## Secret data
}
}
Below is an example of a Junos configuration. The configuration
data is highlighted in blue.
Quick configuration template
system {
host-name {{ host_name }};
name-server {{ dns_server }};
domain-name {{ domain_name }};
backup-router {{ backup_router }};
root-authentication {
encrypted-password "{{ root_password }}";
## Secret data
}
}
Here is a Jinja2 template.The configuration bits have been
replaced with variables. This allows us to separate the “how”
from the “what”.
Template data source
---
host_name: tp8
dns_server: 192.168.5.68
domain_name: shermdog.com
backup_router: 192.168.71.254
root_password: $1$hKWBk3fb$/
The data used to fill in the variables can come from a variety
of sources such as Python dict, CSV, JSON,YAML, even
databases. Here is an example of usingYAML.
Templates are reusable text files
Templates are enhanced text files in the format you already
work with.
They are easily reused, shared and modified because the
configuration syntax (“how”) is separated from the
configuration data (“what”).
So why Jinja2?
• Prevalent in the DevOps / NetOps community
• Supported by Ansible and SaltStack
• Vast amounts of information published
• Easy to debug
• Line numbers of exceptions directly point to the
correct line in the template.
• Template inheritance
• Allows you to build a base “skeleton” template that
contains all the common elements of your site and
defines blocks that child templates can override.
• Execution is very fast
Jinja2Template Basics
Variables are delimited by {{ … }} and expressions
(conditionals, loops, macros, blocks) by {% … %}
system {
host-name {{ host_name }};
name-server {
{% for dns_server in dns %}
{{ dns_server }};
{% endfor %}
}
}
If Statements
Template:
user {{ user.name }} {
authentication {
{% if user.passwd %}
encrypted-password "{{ user.passwd }}";
{% elif user.key %}
ssh-rsa "{{ user.key }}";
{% endif %}
}
}
If Statements
Rendered:
user rick {
authentication {
encrypted-password "$1$wDeov1";
}
}
For Loops
Template:
{% for interface_name in core_interfaces %}
{{ interface_name }} {
output-traffic-control-profile CORE-MAP;
}
{% endfor %}
For Loops
Rendered:
xe-4/1/0 {
output-traffic-control-profile CORE-MAP;
}
xe-4/2/0 {
output-traffic-control-profile CORE-MAP;
}
xe-4/3/0 {
output-traffic-control-profile CORE-MAP;
}
Filters
Template:
{% for interface_name in core_interfaces %}
{{ interface_name }} {
description “{{ desc|upper }}”;
}
{% endfor %}
Jinja2 can programmatically manipulate data directly in the
template. The library includes a large amount of built in
filters such as default value, upper/lower, replace, etc.
http://jinja.pocoo.org/docs/dev/templates/#builtin-filters
Filters
Rendered:
xe-4/1/0 {
description “UPSTREAM CON”;
}
xe-4/2/0 {
description “DOWNSTREAM CON”;
}
xe-4/3/0 {
description “MIRROR PORT”;
}
Include
Template:
system {
{% include “login.j2” %}
{% include “services.j2” %}
}
Jinja2 templates are able to directly include the content of
files (such as ssh keys) and other templates.
This allows you to split a configuration into multiple pieces.
Include
Rendered:
system {
login {
user rick {
class super-user;
}
services {
ssh;
}
}
Block (Template Inheritance)
Jinja2 provides a very powerful mechanism of
template inheritance.
Template inheritance allows you to build a base
template that contains all the common elements
/ defaults of your configuration and defines
blocks that child templates can override.
This provides great flexibility in generating base
templates and selectively changing sections
based on things like role or location.
Block – ParentTemplate
services {
ssh;
{% block dhcp %}
dhcp {
pool 0.0.0.0/0;
}
{% endblock dhcp %}
}
Here is a parent template that has wrapped the dhcp
configuration in a block named ‘dhcp’.
The configuration listed inside of this block is the default
value used if not overridden by a child template.
Block – ChildTemplate
{% extends "parent.j2" %}
{% block dhcp %}
dhcp {
pool 10.0.0.0/24 {
domain-name shermdog.com;
}
}
{% endblock dhcp %}
Here is a child template that contains the ‘dhcp’ block.
Because it extends the parent template, the dhcp
configuration inside of the block will override the parents
value.
Block – Rendered template
Rendered:
services {
ssh;
dhcp {
pool 10.0.0.0/24 {
domain-name shermdog.com;
}
}
}
Use templates for configurations!
You will have reusable templates that are easily shared, version
controlled, and updated!

More Related Content

PDF
Advanced Use of jinja2 for Templates
PDF
Intro to Jinja2 Templates - San Francisco Flask Meetup
PDF
Introduction to kubernetes
PDF
Prometheus 101
PDF
Elasticsearch in Netflix
PDF
OpenStack-ansibleで作るOpenStack HA環境 Mitaka版
PDF
Scalable Monitoring Using Prometheus with Apache Spark Clusters with Diane F...
PDF
Open vSwitch 패킷 처리 구조
Advanced Use of jinja2 for Templates
Intro to Jinja2 Templates - San Francisco Flask Meetup
Introduction to kubernetes
Prometheus 101
Elasticsearch in Netflix
OpenStack-ansibleで作るOpenStack HA環境 Mitaka版
Scalable Monitoring Using Prometheus with Apache Spark Clusters with Diane F...
Open vSwitch 패킷 처리 구조

What's hot (20)

PDF
FIWARE Global Summit - NGSI-LD – an Evolution from NGSIv2
PDF
[2018] MySQL 이중화 진화기
PDF
Go Programming Patterns
PDF
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요
PDF
CKA Certified Kubernetes Administrator Notes
PDF
Cassandra sharding and consistency (lightning talk)
PDF
ETL With Cassandra Streaming Bulk Loading
PPTX
Apache kafka 관리와 모니터링
PPTX
Centralized Logging System Using ELK Stack
PDF
Apache Spark on K8S Best Practice and Performance in the Cloud
PDF
How OpenShift SDN helps to automate
PDF
CloudStack - Top 5 Technical Issues and Troubleshooting
PPTX
An Intro to Elasticsearch and Kibana
PDF
Deep dive into highly available open stack architecture openstack summit va...
PDF
Ceph Day Beijing - Ceph All-Flash Array Design Based on NUMA Architecture
PDF
Kubernetes - A Comprehensive Overview
PPTX
NGINX Installation and Tuning
PDF
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
PPTX
Attack monitoring using ElasticSearch Logstash and Kibana
FIWARE Global Summit - NGSI-LD – an Evolution from NGSIv2
[2018] MySQL 이중화 진화기
Go Programming Patterns
왜 쿠버네티스는 systemd로 cgroup을 관리하려고 할까요
CKA Certified Kubernetes Administrator Notes
Cassandra sharding and consistency (lightning talk)
ETL With Cassandra Streaming Bulk Loading
Apache kafka 관리와 모니터링
Centralized Logging System Using ELK Stack
Apache Spark on K8S Best Practice and Performance in the Cloud
How OpenShift SDN helps to automate
CloudStack - Top 5 Technical Issues and Troubleshooting
An Intro to Elasticsearch and Kibana
Deep dive into highly available open stack architecture openstack summit va...
Ceph Day Beijing - Ceph All-Flash Array Design Based on NUMA Architecture
Kubernetes - A Comprehensive Overview
NGINX Installation and Tuning
[오픈소스컨설팅]Day #1 MySQL 엔진소개, 튜닝, 백업 및 복구, 업그레이드방법
Attack monitoring using ElasticSearch Logstash and Kibana
Ad

Similar to Python (Jinja2) Templates for Network Automation (20)

PPTX
Network automation with Ansible and Python
PPT
Ansible meetup-kamen
PDF
slides-frnog34.pdf
PDF
Automation@Brainly - Polish Linux Autumn 2014
PDF
Managing Large-scale Networks with Trigger
PDF
Travel with your mock server
PDF
Ansible at work
PDF
Automated Deployment and Configuration Engines. Ansible
PPTX
Infrastructure Automation
PPTX
How to deploy spark instance using ansible 2.0 in fiware lab v2
PPTX
How to Deploy Spark Instance Using Ansible 2.0 in FIWARE Lab
PDF
PLNOG14: Automation at Brainly - Paweł Rozlach
PDF
PLNOG Automation@Brainly
PDF
Python Templating Engine - Intro to Jinja
PDF
Ansible
PPTX
Network Automation using Python and Ansible.pptx
PPTX
Mastering_Ansible_PAnsible_Presentation our score increases as you pick a
PPTX
PPTX
Ansible Meetup NYC 060215
PDF
Ansible - A 'crowd' introduction
Network automation with Ansible and Python
Ansible meetup-kamen
slides-frnog34.pdf
Automation@Brainly - Polish Linux Autumn 2014
Managing Large-scale Networks with Trigger
Travel with your mock server
Ansible at work
Automated Deployment and Configuration Engines. Ansible
Infrastructure Automation
How to deploy spark instance using ansible 2.0 in fiware lab v2
How to Deploy Spark Instance Using Ansible 2.0 in FIWARE Lab
PLNOG14: Automation at Brainly - Paweł Rozlach
PLNOG Automation@Brainly
Python Templating Engine - Intro to Jinja
Ansible
Network Automation using Python and Ansible.pptx
Mastering_Ansible_PAnsible_Presentation our score increases as you pick a
Ansible Meetup NYC 060215
Ansible - A 'crowd' introduction
Ad

Recently uploaded (20)

PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PDF
Architecture types and enterprise applications.pdf
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PPTX
O2C Customer Invoices to Receipt V15A.pptx
PDF
Enhancing emotion recognition model for a student engagement use case through...
PPT
Geologic Time for studying geology for geologist
PDF
A review of recent deep learning applications in wood surface defect identifi...
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
Five Habits of High-Impact Board Members
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PDF
Hindi spoken digit analysis for native and non-native speakers
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
PDF
Getting started with AI Agents and Multi-Agent Systems
PDF
sustainability-14-14877-v2.pddhzftheheeeee
WOOl fibre morphology and structure.pdf for textiles
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
1 - Historical Antecedents, Social Consideration.pdf
Taming the Chaos: How to Turn Unstructured Data into Decisions
A contest of sentiment analysis: k-nearest neighbor versus neural network
Architecture types and enterprise applications.pdf
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
O2C Customer Invoices to Receipt V15A.pptx
Enhancing emotion recognition model for a student engagement use case through...
Geologic Time for studying geology for geologist
A review of recent deep learning applications in wood surface defect identifi...
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
Five Habits of High-Impact Board Members
NewMind AI Weekly Chronicles – August ’25 Week III
Hindi spoken digit analysis for native and non-native speakers
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
Group 1 Presentation -Planning and Decision Making .pptx
Getting started with AI Agents and Multi-Agent Systems
sustainability-14-14877-v2.pddhzftheheeeee

Python (Jinja2) Templates for Network Automation

  • 2. What are templates and why use them? A template is a text document where some or all of the content is automatically generated. Templates are text files in the format you already work with. Data is stored separated and automatically loaded. Easily re-used and shared.
  • 3. Quick Example – Configuration file system { host-name tp8; name-server 192.168.5.68; domain-name shermdog.com; backup-router 192.168.71.254; root-authentication { encrypted-password "$1$hKWBk3fAgDHF/"; ## Secret data } } Below is an example of a Junos configuration. The configuration data is highlighted in blue.
  • 4. Quick configuration template system { host-name {{ host_name }}; name-server {{ dns_server }}; domain-name {{ domain_name }}; backup-router {{ backup_router }}; root-authentication { encrypted-password "{{ root_password }}"; ## Secret data } } Here is a Jinja2 template.The configuration bits have been replaced with variables. This allows us to separate the “how” from the “what”.
  • 5. Template data source --- host_name: tp8 dns_server: 192.168.5.68 domain_name: shermdog.com backup_router: 192.168.71.254 root_password: $1$hKWBk3fb$/ The data used to fill in the variables can come from a variety of sources such as Python dict, CSV, JSON,YAML, even databases. Here is an example of usingYAML.
  • 6. Templates are reusable text files Templates are enhanced text files in the format you already work with. They are easily reused, shared and modified because the configuration syntax (“how”) is separated from the configuration data (“what”).
  • 7. So why Jinja2? • Prevalent in the DevOps / NetOps community • Supported by Ansible and SaltStack • Vast amounts of information published • Easy to debug • Line numbers of exceptions directly point to the correct line in the template. • Template inheritance • Allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. • Execution is very fast
  • 8. Jinja2Template Basics Variables are delimited by {{ … }} and expressions (conditionals, loops, macros, blocks) by {% … %} system { host-name {{ host_name }}; name-server { {% for dns_server in dns %} {{ dns_server }}; {% endfor %} } }
  • 9. If Statements Template: user {{ user.name }} { authentication { {% if user.passwd %} encrypted-password "{{ user.passwd }}"; {% elif user.key %} ssh-rsa "{{ user.key }}"; {% endif %} } }
  • 10. If Statements Rendered: user rick { authentication { encrypted-password "$1$wDeov1"; } }
  • 11. For Loops Template: {% for interface_name in core_interfaces %} {{ interface_name }} { output-traffic-control-profile CORE-MAP; } {% endfor %}
  • 12. For Loops Rendered: xe-4/1/0 { output-traffic-control-profile CORE-MAP; } xe-4/2/0 { output-traffic-control-profile CORE-MAP; } xe-4/3/0 { output-traffic-control-profile CORE-MAP; }
  • 13. Filters Template: {% for interface_name in core_interfaces %} {{ interface_name }} { description “{{ desc|upper }}”; } {% endfor %} Jinja2 can programmatically manipulate data directly in the template. The library includes a large amount of built in filters such as default value, upper/lower, replace, etc. http://jinja.pocoo.org/docs/dev/templates/#builtin-filters
  • 14. Filters Rendered: xe-4/1/0 { description “UPSTREAM CON”; } xe-4/2/0 { description “DOWNSTREAM CON”; } xe-4/3/0 { description “MIRROR PORT”; }
  • 15. Include Template: system { {% include “login.j2” %} {% include “services.j2” %} } Jinja2 templates are able to directly include the content of files (such as ssh keys) and other templates. This allows you to split a configuration into multiple pieces.
  • 16. Include Rendered: system { login { user rick { class super-user; } services { ssh; } }
  • 17. Block (Template Inheritance) Jinja2 provides a very powerful mechanism of template inheritance. Template inheritance allows you to build a base template that contains all the common elements / defaults of your configuration and defines blocks that child templates can override. This provides great flexibility in generating base templates and selectively changing sections based on things like role or location.
  • 18. Block – ParentTemplate services { ssh; {% block dhcp %} dhcp { pool 0.0.0.0/0; } {% endblock dhcp %} } Here is a parent template that has wrapped the dhcp configuration in a block named ‘dhcp’. The configuration listed inside of this block is the default value used if not overridden by a child template.
  • 19. Block – ChildTemplate {% extends "parent.j2" %} {% block dhcp %} dhcp { pool 10.0.0.0/24 { domain-name shermdog.com; } } {% endblock dhcp %} Here is a child template that contains the ‘dhcp’ block. Because it extends the parent template, the dhcp configuration inside of the block will override the parents value.
  • 20. Block – Rendered template Rendered: services { ssh; dhcp { pool 10.0.0.0/24 { domain-name shermdog.com; } } }
  • 21. Use templates for configurations! You will have reusable templates that are easily shared, version controlled, and updated!