Iterating over all network interfaces in Ansible 2016-04-21
Table of Contents
Description: Getting information about every network interface on a system with ansible is not that obvious. Here's the solution I found.
Reading Time: 1
The problem
Ansible keeps a list of all network interfaces in the ansible_interfaces
fact. Sometimes you need to iterate over all of these, but access the ansible_eth0
or other interface data, but doing so is non-obvious. Here’s what I found that works:
- name: debug print all interface ipv4 data
when: "{{ hostvars[ansible_fqdn]['ansible_'~item]['ipv4'] is defined }}"
debug:
msg="{{ hostvars[ansible_fqdn]['ansible_'~item]['ipv4'] | pprint }}"
with_items:
- "{{ ansible_interfaces | map('replace', '-','_') | list }}"
Notes
You can’t access the variables directly in facts, thus the use of
hostvars
to access the global facts, andansible_fqdn
to specify the current host.Per interface information is stored in
ansible_eth0
or similar, thus the'ansible_'~item
which builds this interface name.Ansible facts don’t contain the
-
character but the interface name might, thus themap()
filter that replaces them with_
’s inwith_items
. Themap
filter returns a python generator, thus the call tolist
which converts the generator to a list.You may need to filter out any interfaces that might not be set up, which is done with the
when:
statement