ansible 通过提供 IP 地址获取接口名称

ste*_*wak 4 linux ansible

我在机器(linux)中有两个接口。第一个接口已被寻址,第二个接口已关闭,没有任何 IP。现在我想获取与我在 ansible 中提供的 IP 值相匹配的接口名称。

我正在尝试这样的事情:

    - 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
Run Code Online (Sandbox Code Playgroud)

当所有接口都有 IP 地址时它工作得很好,但问题是当一个接口没有 IP 时,我会出现错误: “dict object”没有属性“ipv4”

是否可以在不出现错误的情况下获取接口名称?

ili*_*-sp 5

试试这个剧本,只需设置你要搜索的IP:

- 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
Run Code Online (Sandbox Code Playgroud)


小智 5

你可以使用 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 }}"
Run Code Online (Sandbox Code Playgroud)

{{ ansible_interfaces | map('regex_replace', '^', 'ansible_') | map('extract', vars)获取接口列表,其中每个接口都是一个包含有关该接口的信息的字典。然后,您可以过滤并映射该列表以获得您需要的内容。