首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带计数的python-Jinja2循环

带计数的python-Jinja2循环
EN

Stack Overflow用户
提问于 2016-04-20 14:01:02
回答 1查看 338关注 0票数 0

我试图通过创建基于预定义变量的开关的接口配置来循环,我知道我可以在Jinja中这样做,但我不确定如何开始实现它。

我的模板如下。通过python脚本,我将传递2个值,开关的数量和端口的数量。

因此,如果有三个开关--24个端口开关--我需要它为端口g1/0/1到g1/0/24、g2/0/1到g2/0/24和g3/0/1至24创建一个配置。

这有道理吗?我需要计算这两个数字,直到它们达到设定的数值为止。

谢谢亚历克斯

代码语言:javascript
复制
{% for %}
interface GigabitEthernet{{ SW }}/0/{{ Port }}
 switchport access vlan {{ DATAVLAN }}
 switchport mode access
 switchport voice vlan {{ VOICEVLAN }}
 switchport port-security maximum 2
 switchport port-security violation restrict
 switchport port-security aging time 1
 switchport port-security aging type inactivity
 switchport port-security
 spanning-tree portfast
 spanning-tree bpduguard enable
{% endfor %}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-04-20 15:33:34

我已经成功地实现了我的结果,我动态地创建了一个数组,它将列出所有的端口,然后在这个数组上迭代,它完美地工作。不确定是否有更好的方法,但这暂时是好的

谢谢

创建数组

代码语言:javascript
复制
    #create interface list
    intSwitchCount = int(row['SWITCHES'].strip())
    intPortCount = int(row['PORTS'].strip())
    intSW = 0
    intPort = 0
    lstPorts = []
    while intSW != intSwitchCount:
        intSW += 1
        while intPort != (intPortCount) :
            intPort += 1
            strPort = '%s/0/%s' % (str(intSW),str(intPort))
            lstPorts.extend([strPort])
        intPort = 0

模板

代码语言:javascript
复制
{% for item in SWITCHPORTS %}
interface GigabitEthernet{{ item }}
 switchport access vlan {{ DATAVLAN }}
 switchport mode access
 switchport voice vlan {{ VOICEVLAN }}
 switchport port-security maximum 2
 switchport port-security violation restrict
 switchport port-security aging time 1
 switchport port-security aging type inactivity
 switchport port-security
 spanning-tree portfast
 spanning-tree bpduguard enable
{% endfor %}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36746221

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档