开发者

jinja2 keep indentaion when render multi line string

开发者 https://www.devze.com 2022-12-07 18:52 出处:网络
I\'m using jinja2 with python to config network device automatically.Now I\'m in trouble with line indentaion. Here is my demo: reading config info from csv file and render into config string.

I'm using jinja2 with python to config network device automatically.Now I'm in trouble with line indentaion. Here is my demo: reading config info from csv file and render into config string.

.j2 file

interface {{ interface }}
    description {{ ip }}-{{ server }}-{{ contact }}
    port link-type {{ port_type }}
    {% if port_type == "access" -%}
    port default vlan {{ vlan }}
    {% endif %}

.py

def generate_config():
    """
    Parameter:None
    Return:device config string
    """
        
    template_fd = open(template_file,'r')
    server_info_fd = open(server_info_file,'r')
    
    jinja_template = Template(template_fd.read(),keep_trailing_newline=True)
    server_info = csv.DictReader(server_info_fd)
    
  开发者_如何学编程  config_set=''
    for info in server_info:
        interface_config = jinja_template.render(
            interface=info['Interface'],
            ip=info['Ip'],
            server=info['Server'],
            contact=info['Contact'],
            vlan=info['Vlan'],
            port_type=info['Port-type']
        )
        config_set += interface_config
        
    template_fd.close()
    server_info_fd.close()
    return config_set

What I got is:

interface GigabitEthernet0/0/17
    description x.x.x.x-test-101
    port link-type access
    port default vlan 2101
    interface GigabitEthernet0/0/18
    description x.x.x.x-test-102
    port link-type access
    port default vlan 2101

The second interface 0/0/18 still keeps indentation which I don't want. Thx for you great help

0

精彩评论

暂无评论...
验证码 换一张
取 消