首页 > 解决方案 > 使用带有 Ansible 的 jinja 模板陷入循环情况

问题描述

我在使用 jinja 模板和 Ansible 时遇到了循环情况。

我的神社模板:

{% for int in interfaces | difference(existing_conf) %}
interface {{ int }}
{% for ip in dhcp_servers | difference(existing_conf) %}
  ip dhcp relay address {{ ip }}
{% endfor %}
{% endfor %}
TASK [view the existing config] *******************************************************************************************************************************************************************************************************************************************************************************
ok: [nxos-1] => {
    "existing_conf": [
        "Vlan1",
        "10.1.1.2",
        "10.1.1.3",
        "10.1.1.4",
        "Ethernet1/49",
        "10.1.1.2",
        "Ethernet1/50",
        "10.1.1.2"
    ]
}
TASK [Needed config] *****************************************************************************************************************************************************************************************************************************************************************
ok: [nxos-1]
TASK [View the needed config] ************************************************************************************************************************************************************************************************************************************************************************************
ok: [nxos-1] => {
    "needed_conf": [
        "Vlan1",
        "10.1.1.2",
        "10.1.1.3",
        "10.1.1.4",
        "Ethernet1/49",
        "10.1.1.2",
        "10.1.1.3",
        "10.1.1.4",
        "Ethernet1/50",
        "10.1.1.2",
        "10.1.1.3",
        "10.1.1.4"
    ]
}

我的变量:

interfaces=["Vlan1", "Ethernet1/49", "Ethernet1/50"]
dhcp_servers=["10.1.1.2", "10.1.1.3", "10.1.1.4"]

使用我的模板,我得到一个空配置。

我想要的配置:

interface Ethernet1/49
  ip dhcp relay address 10.1.1.3
  ip dhcp relay address 10.1.1.4
interface Ethernet1/50
  ip dhcp relay address 10.1.1.3
  ip dhcp relay address 10.1.1.4

注意:我只想添加不在交换机运行配置中的配置。

标签: ansiblejinja2

解决方案


问:......我得到一个空配置。

A:没有要迭代的项目。区别_

    - debug:
        msg: "{{ interfaces|difference(existing_conf) }}"

给出一个空列表

  msg: []

推荐阅读