[英]ansible get the interface name by providing an IP address
我在機器(linux)中有兩個接口。 一個接口已被尋址,第二個接口關閉,沒有任何 IP。 現在我想獲取與 IP 匹配的接口名稱,我在 ansible 中作為值提供。
我正在嘗試這樣的事情:
- 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
當所有接口都有 IP 地址時它工作得很好但問題是當一個接口沒有 IP 時我有錯誤: 'dict object' has no attribute 'ipv4'
是否可以在不出錯的情況下獲取接口名稱?
試試這個劇本,只需設置你要搜索的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
您可以使用 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)
{{ ansible_interfaces | map('regex_replace', '^', 'ansible_') | map('extract', vars)
為您獲取接口列表,其中每個接口都是包含有關接口信息的字典。 然后,您可以過濾和映射列表以獲得您需要的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.