I'm looking for an expression to fetch the interface name given an ip address assigned to that iface, across Linux and FreeBSD.
This question is based on this answer: https://serverfault.com/a/948288/416946
This jinja2 expression will, on Debian, return the interface object (from ansible facts) for the given_ip
iface_for_ip: >-
{{ ansible_facts
| dict2items
| selectattr('value.ipv4', 'defined')
| selectattr('value.ipv4.address', 'equalto', given_ip)
| first }}
However this does not work on FreeBSD because the ipv4
structure is an array, not an object.
If you run just this snippet:
iface_for_ip: >-
{{ ansible_facts
| dict2items
| selectattr('value.ipv4', 'defined') }}
You will get an output like this:
on Debian - key: eth0
value:
active: true
device: eth0
ipv4:
address: 10.8.20.206
broadcast: 10.8.20.255
netmask: 255.255.255.0
network: 10.8.20.0
ipv6:
- address: fe80::84ee:35ff:fed4:a23c
prefix: '64'
scope: link
macaddress: 00:ee:35:00:00:00
mtu: 1500
promisc: false
speed: 10000
type: ether
on FreeBSD
- key: epair0b
value:
device: epair0b
flags:
- UP
- BROADCAST
- RUNNING
- SIMPLEX
- MULTICAST
ipv4:
- address: 10.8.20.207
broadcast: 10.8.20.255
netmask: 255.255.255.0
network: 10.8.20.0
ipv6: []
macaddress: 00:ee:23:00:00:00
media: Ethernet
media_options:
- full-duplex
media_select: 10Gbase-T
media_type: 10Gbase-T
metric: '0'
mtu: '1500'
options:
- PERFORMNUD
status: active
type: ether
How can I use a jinja2 ansible expression to fetch the interface given just the ip address cross platform? json_query
could be useful here, but the method eludes me.