Reputation: 25
I am working with Ansible and I need to display a list of the hosts' network interfaces. In a Jinja2 format template I need the following values: Name, IP, Mask and Network for each of the interfaces. To have this information I use the ansible_facts but I have a problem when making the for.
I get the network interfaces from here:
"ansible_interfaces": [
"eth1",
"eth0",
"lo"
],
So far so good, I make a for and it shows me all three. My problem is that the information I need from each interface is separated in 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"
},
To get this information I try it in the following way:
{{% 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 %}}
I've tried it in different ways and can't figure out how to do it. In my opinion, what the for returns me is a string. And I tried with the iteritems option but I can't either. If someone can help me with the problem I would appreciate it.
Upvotes: 1
Views: 289
Reputation: 68034
Use lookup plugin vars. See the details by running in shell ansible-doc -t lookup vars
. For example
- 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 %}
gives in my laptop
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
The attribute ipv4 might be missing. Fit the default values to your needs.
Upvotes: 1