Hello Ansible users,
i have a nice playbook that make a convenient hash table for network card like that:
{
“192.168.0.1”: “eth0”,
“192.168.0.2”: “eth1”
}
Here is the playbook:
- set_fact:
ifaces: “{{ ifaces|default({}) | combine({hostvars[item][‘ansible_%s’ | format(local_iface)][‘ipv4’][‘address’]: local_iface}) }}”
with_items:
- “{{ hostvars[item][‘ansible_interfaces’] }}”
loop_control:
loop_var: local_iface
All was working fine but i encounter an error when i launch it with a host that have a network card with no ip address.
The playbook fails with the following error:
"FAILED! => {“msg”: “The task includes an option with an undefined variable. The error was: ‘dict object’ has no attribute ‘ipv4’”
Do you have any idea how i can handle this case with a special condition to ignore network card with no ipv4 address ?
Thanks!
I forgot to say that “item” refer to a list of hosts in a group.
I tried with these special condition:
- set_fact:
when: hostvars[item][‘ansible_’~local_iface][‘ipv4’] is defined
ifaces: “{{ ifaces|default({}) | combine({hostvars[item][‘ansible_%s’ | format(local_iface)][‘ipv4’][‘address’]: local_iface}) }}”
with_items:
- “{{ hostvars[item][‘ansible_interfaces’] }}”
loop_control:
loop_var: local_iface
But with no more luck.
Any ideas?
The when is indented to far in, is should be on the same level as set_fact.
Yeah sure, sorry wrong copy/paste i haven’t syntax problem on my original playbook.
Anyway i found the solution which is:
- set_fact:
ifaces: “{{ ifaces|default({}) | combine({hostvars[item][‘ansible_%s’ | format(local_iface)][‘ipv4’][‘address’]: local_iface}) }}”
when: hostvars[item][‘ansible_’~local_iface][‘ipv4’] is defined
with_items:
- “{{ hostvars[item][‘ansible_interfaces’] }}”
loop_control:
loop_var: local_iface