问题原文
原帖链接 · Neik · CC BY-SA 3.0
I'd like to get an ordered list of the network interfaces on a machine using Ansible. Modern Linux systems don't use eth0, eth1, etc. So the names are unpredictable. On our network we connect the lowest numbered interface to the LAN and the highest to the WAN, so I can use the position of the interface in an ordered list to determine its function.
I am looking for the canonical way to do this in Ansible. So that I can use something like {{ansible_eth0.ipv4.address}}. (Where eth0 is some other name).
Even if I manually set a variable with the name of the interface there seems no way to get the IP of that interface (using the contents of the variable).
I'd like to process the Ansible facts to get what I want rather than running a shell script on the remote system.
社区高分解答
原帖链接 · simohe · CC BY-SA 4.0
Some hints to get an interface when we know some information:
var:
allNetworkInterfaces: "{{ ansible_facts | dict2items | selectattr('value.ipv4', 'defined') | map(attribute='value') | list }}"
allNetworkInterfaces_variant2: "{{ ansible_facts.interfaces | map('extract', ansible_facts ) | list }}"
interfaceWithKnownIp: "{{ ansible_facts | dict2items | selectattr('value.ipv4', 'defined') | selectattr('value.ipv4.address', 'equalto', myKnowIpV4) | first }}"
interfaceWithKnownIp_fromVar: "{{ allNetworkInterfaces | selectattr('ipv4.address', 'equalto', myKnowIpV4) | first }}"
interfacesWithPartialKnowMac: "{{ allNetworkInterfaces | selectattr('macaddress', 'match', knownMacPrefix~'.*') | list }}"
interfacesWitKnowType: "{{ allNetworkInterfaces | selectattr('type', 'equalto', knownType) | sort(attribute='device') | list }}"
# extended on 2020-10-28
queryForKnownIpv6: "[*].{device: device, ipv4: ipv4, ipv6: ipv6[? address == 'fe80::a00:27ff:fe38:ad36']}[?ipv6])" # string must be in ' # sorry, only partial interface info, did not find out how to return all info directly
interfacesWithKnownIpv6: '{{ allNetworkInterfaces | json_query(queryForKnownIpv6) | first }}'
queryForKnownIpv4_linux: "[?ipv4.address == '{{ myKnownIpV4 }}']}[?ipv4])" # string must be in '
interfacesWithKnownIp_variantJsonQuery: '{{ allNetworkInterfaces | json_query(queryForKnownIpv4_linux) | first }}'
some short explications:
- dict2item because selectattr expects an array
- map(attribute='...') to unpack this array
- map('extract', ...) to extract interfaces from
ansible_facts ansible_facts.interfacesis the same asansible_interfaces- json_query() for flexible selecting and unpacking, an alternative variant with `map()? is welcome
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
