【问题标题】:How to Iterate through YAML list/dictionary items while rending Jinja2 template in Python如何在 Python 中渲染 Jinja2 模板时遍历 YAML 列表/字典项
【发布时间】:2016-01-19 11:35:15
【问题描述】:

我似乎被代码或概念卡住了,需要一些帮助来迭代基于 YAML 的 dict/list,同时在 Python 中渲染 Jinja2 模板。 我在编程方面有点新手(3 周),所以对于任何错误,请提前道歉。

例如,我在 YAML 中定义了以下字典。

---
- hostname: R1
  interfaces:
    - name: f0/0
      description: This is FastEth 0/0 connected to R2 FastEth 0/0
    - name: f0/1
      description: This is FastEth 0/1 connected to Local Host Loopback
- hostname: R2
  interfaces:
    - name: f0/0
      description: This is FastEth 0/0 connected to R2 FastEth 0/0
    - name: f0/1
      description: This is FastEth 0/1 connected to Local Host Loopback

以下是我正在渲染的 Jinja 模板:

{% for iface in config.interfaces %}
int {{ config.name }}
description {{ config.description }}
{% endfor %}

.... 我有两个路由器 R1 和 R2,我只想根据它们的字典发送渲染的配置。我想生成两个配置集,每个路由器一个。 因此,我想这样做是 Python,但没有运气。

env = Environment(loader=FileSystemLoader('./templates'),trim_blocks=True)
with open('./YAML/configuration.yml') as _:
    config_commands_var = yaml.load(_)

for device in range(len(devices)):
    print "\nStart time: " + str(datetime.now())
    username = devices[device]['username']
    password = devices[device]['password']
    ip = devices[device]['ip']
    device_type = devices[device]['device_type']
    secret = devices[device]['secret']
    hostname = devices[device]['hostname']

    config_commands = template.render(config=config_commands_var)
    push_config_commands(username, password, ip, device_type, secret, config_commands)

这里的“设备”是设备字典列表。和“push_config_commands”函数一次将命令列表发送到任何设备。

我希望在这里能真正解决我的问题,因此将不胜感激任何形式的帮助。 提前致谢。

【问题讨论】:

    标签: python dictionary networking automation jinja2


    【解决方案1】:

    我想我成功了。但是仍然欢迎任何建议。

    将 YAML 文件更改为:

    ---
    interfaces:
      R1:
        f0/0:
          description: This is FastEth 0/0 connected to R2 FastEth 0/0
        f0/1:
          description: This is FastEth 0/1 connected to Local Host Loopback
      R2:
        f0/0:
          description: This is FastEth 0/0 connected to R2 FastEth 0/0
        f0/1:
          description: This is FastEth 0/1 connected to Local Host Loopback
    

    我把模板改成:

    {% for iface in config %}
    interface {{ iface }}
    description {{ config[iface]['description'] }}
    {% endfor %}
    

    在渲染时我通过键查看:

    config_commands = template.render(config=config_commands_var['interfaces'][hostname])
    

    欢迎任何改进。

    谢谢。

    【讨论】:

      猜你喜欢
      • 2019-09-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2014-10-11
      • 1970-01-01
      • 2020-01-05
      • 2013-10-09
      相关资源
      最近更新 更多