'ansible get the interface name by providing an IP address

I have two interfaces in machine(linux). One interface has been addressed and second is down without any IP. Now I would like to get the interface name matched with IP what I provide as value in ansible.

I was trying something like this:

    - name: interface name from provides IP
  set_fact:
    interface_name="{{ item }}"
  with_items:
     - "{{ ansible_interfaces | map('replace', '-','_') | list }}"
  when: hostvars[ansible_fqdn]['ansible_'~item]['ipv4']['address'] == PROVIDED_IP

It works good when all interfaces have IP address but problem is when one interface has no IP then I have error: 'dict object' has no attribute 'ipv4'

Is possible to get interface name without getting errors?



Solution 1:[1]

try this playbook, just set the IP you want to search for:

- hosts: localhost
  gather_facts: true
  vars:
    desired_interface_name: ""
    target_interface_name: "192.168.16.200"

  tasks:
    - name: parse interfaces
      set_fact:
        desired_interface_name="{{ item }}"
      when: hostvars[inventory_hostname]['ansible_{{item}}']['ipv4']['address'] == target_interface_name
      with_items:
        - "{{ ansible_interfaces }}"

    - name: print result
      debug:
        var: desired_interface_name

Solution 2:[2]

You can do this using jinja:

- name: Get interface name from provided IP
  set_fact:
    interface_name: "{{ ansible_interfaces | map('regex_replace', '^', 'ansible_') | map('extract', vars) | selectattr('ipv4.address', 'match', '192\\.168\\.16\\.200') | map(attribute='device') | first }}"

{{ ansible_interfaces | map('regex_replace', '^', 'ansible_') | map('extract', vars) gets you a list of interfaces, where each interface is a dictionary with information about the interface. You can then filter and map the list to get what you need.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ilias-sp
Solution 2 β.εηοιτ.βε