netmiko使用案列17 jinjia2的使用

jinja2_vlans.py

#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import jinja2

template_vars = {
    'vlan_id': 400,
    'vlan_name': 'red400',
}

vlan_template = '''
vlan {{ vlan_id }}
   name {{ vlan_name }}

'''

template = jinja2.Template(vlan_template)
print(template.render(template_vars))
image.png

jinja2_for_loop.py

#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import jinja2

my_vlans = {
    '501': 'blue501',
    '502': 'blue502',
    '503': 'blue503',
    '504': 'blue504',
    '505': 'blue505',
    '506': 'blue506',
    '507': 'blue507',
    '508': 'blue508',
}
template_vars = {
    'vlans': my_vlans
}

vlan_template = '''

{%- for vlan_id, vlan_name in vlans.items() %}
vlan {{ vlan_id }}
   name {{ vlan_name }}
{%- endfor %}

'''

template = jinja2.Template(vlan_template)
print(template.render(template_vars))
image.png

jinja2_ospf_file.py

读取文件名的方式

#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import jinja2

template_file = 'ospf_config.j2'
with open(template_file) as f:
    jinja_template = f.read()

ospf_active_interfaces = ['Vlan1', 'Vlan2']
area0_networks = [
    '10.10.10.0/24',
    '10.10.20.0/24',
    '10.10.30.0/24',
]
template_vars = {
    'ospf_process_id': 10,
    'ospf_priority': 100,
    'ospf_active_interfaces': ospf_active_interfaces,
    'ospf_area0_networks': area0_networks,
}

template = jinja2.Template(jinja_template)
print(template.render(template_vars))

ospf_config.j2


{%- if ospf_priority is defined %}
interface Vlan1
   ip ospf priority {{ ospf_priority }}
{%- endif %}

router ospf {{ ospf_process_id }}
   passive-interface default
   {%- for intf in ospf_active_interfaces %}
   no passive-interface {{ intf }}
   {%- endfor %}
   {%- for network in ospf_area0_networks %}
   network {{ network }} area 0.0.0.0
   {%- endfor %}
   max-lsa 12000

image.png

jinja2_crypto.py

#!/usr/bin/env python
from __future__ import print_function, unicode_literals
import jinja2

template_vars = {
    'isakmp_enable': True,
    'encryption': 'aes',
    'dh_group': 5,
}

cfg_template = '''

{%- if isakmp_enable %}
crypto isakmp policy 10
 encr {{ encryption }}
 authentication pre-share
 group {{ dh_group }}
crypto isakmp key my_key address 1.1.1.1 no-xauth
crypto isakmp keepalive 10 periodic
{%- endif %}

'''

template = jinja2.Template(cfg_template)
print(template.render(template_vars))
image.png

你可能感兴趣的:(netmiko使用案列17 jinjia2的使用)