0

I'm trying to read information from ansible_net_interfaces, but the interface names will be different on each device. I'm having no trouble accessing most information, but when I get to ipv4, there's a sub-array, and no matter what I try, I can't access it consistently. Here are my tasks:

- name: Get config for Cisco Routers
  ios_facts:
    gather_subset: interfaces

- name: Display all interface data
  debug:
     msg: "{{ item.key }},{{item.value.description}},{{item.value.ipv4}}"
  with_dict:
   - "{{ ansible_net_interfaces }}"

This prints out the interface. the description, and then both the key pairs subnet and address within the subarray ipv4.

I've tinkered with this a bit, and I've found that

{{item.value.ipv4.0.address}}

will grab the info from some interfaces then fail out of the task saying "FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: list object has no element 0" as soon as it hits an interface that doesn't have an IP configured.

if it's possible to check that the interface is configured with an IP address beforehand that could work (since I won't need to use unconfigured interfaces) but if I use a when statement, I don't know where to put it since it needs to be part of the loop that reads through the dictionary.

I've researched using with_subelements, but I'm not quite sure how to define it, and I'm not sure if I need to use with_dict to read the dictionary properly

1 Answer 1

1

I finally figured it out:

- name: Display all interface data
  debug:
     msg: "{{ item.key }},{{item.value.description}},{{item.value.ipv4.0.address}},{{item.value.ipv4.0.subnet}}"
  when: item.value.ipv4.0.address is defined
  with_dict:
   - "{{ ansible_net_interfaces }}"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .