如何使用for在ansible中嵌套变量

How to nest variable in ansible with for

我正在使用 Ansible,我需要显示主机网络接口的列表。在 Jinja2 格式模板中,我需要以下值:每个接口的名称、IP、掩码和网络。为了获得这些信息,我使用 ansible_facts 但我在制作 for.

时遇到了问题

我从这里获取网络接口:

"ansible_interfaces": [
    "eth1",
    "eth0",
    "lo"
],

到目前为止一切顺利,我做了一个 for,它向我展示了所有三个。我的问题是我需要的每个接口的信息在 jason:

中是分开的
"ansible_eth0": {
    "active": true,
    "device": "eth0",
    "hw_timestamp_filters": [],
    "ipv4": {
        "address": "x.x.x.x",
        "broadcast": "x.x.x.x",
        "netmask": "255.255.192.0",
        "network": "x.x.x.x"
    },
    "ipv4_secondaries": [
        {
            "address": "x.x.x.x",
            "broadcast": "x.x.x.x",
            "netmask": "255.255.0.0",
            "network": "x.x.x.x"
        }
    ],
    "ipv6": [
        {
            "address": "",
            "prefix": "64",
            "scope": "link"
        }
    ],
    "macaddress": "",
    "module": "virtio_net",
    "mtu": 1500,
    "pciid": "virtio0",
    "promisc": false,
    "speed": -1,
    "timestamping": [
        "tx_software",
        "rx_software",
        "software"
    ],
    "type": "ether"
},
"ansible_eth1": {
    "active": true,
    "device": "eth1",
    "hw_timestamp_filters": [],
    "ipv4": {
        "address": "x.x.x.x",
        "broadcast": "x.x.x.x",
        "netmask": "255.255.240.0",
        "network": "x.x.x.x"
    },
    "ipv6": [
        {
            "address": "",
            "prefix": "64",
            "scope": "link"
        }
    ],
    "macaddress": "",
    "module": "virtio_net",
    "mtu": 1500,
    "pciid": "virtio1",
    "promisc": false,
    "speed": -1,
    "timestamping": [
        "tx_software",
        "rx_software",
        "software"
    ],
    "type": "ether"
},

为了获取此信息,我尝试了以下方式:

{{% for interfaz in ansible_interfaces %}}
{{% for item in ansible_['interfaz'] %}}

Name: {{ item.device }}
IP: {{ item.ipv4.address }}
Netmask: {{ item.ipv4.metmask }}
Red: {{ item.ipv4.network }}

{{% endfor %}}
{{% endfor %}}

我试过各种方法,但不知道该怎么做。在我看来,for returns me 是一个字符串。我尝试使用 iteritems 选项,但我也不能。如果有人能帮助我解决这个问题,我将不胜感激。

使用 lookup 插件 vars。请参阅 运行 在 shell ansible-doc -t lookup vars 中的详细信息。例如

    - debug:
        msg: |
          {% for i in ansible_interfaces %}
          {% set dev = lookup('vars', 'ansible_' ~ i) %}
          Name: {{ dev.device }}
          IP: {{ dev.ipv4.address|default(None) }}
          Netmask: {{ dev.ipv4.netmask|default(None) }}
          Red: {{ dev.ipv4.network|default(None) }}

          {% endfor %}

给我的笔记本电脑

  msg: |-
    Name: lo
    IP: 127.0.0.1
    Netmask: 255.0.0.0
    Red: 127.0.0.0
  
    Name: wlan0
    IP:
    Netmask:
    Red:
  
    Name: eth0
    IP: 10.1.0.27
    Netmask: 255.255.255.0
    Red: 10.1.0.0

可能缺少 ipv4 属性。根据您的需要调整默认值。