Enabling interfaces

Create a .yml data file (data.yml) with variables and lists:


host_ports:
– 1/1
– 1/2
– 1/3
Create a .j2 file (noshut.j2) which will reference the data from the data file:

{%- for iface in host_ports %}
interface gigabitethernet {{ iface }}
no shutdown
exit
{%- endfor %}

Merge data and template together and output to a file:

python render.py > output.conf

Render.py:

from jinja2 import Template
import yaml
import sys
from glob import glob

data_fname = sys.argv[1:1] or glob(‘*.yml’)[0]
template_fname = sys.argv[2:2] or glob(‘*.j2’)[0]

data = yaml.load(open(data_fname).read())
template = Template(open(template_fname).read())
print template.render(data)

Adding data to a variable called myvars (native python structure aka dictionary):

import yaml

myvars = yaml.load(open(‘data.yml’).read())

from pprint import pprint

pprint(myvars)

{‘host_ports’: [‘1/1’, ‘1/2’, ‘1/3’]}

 

https://neckercube.com/index.php/2018/04/

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s