解析 JSON 输出以获取 Mac 地址对应的 IP 地址

Parse JSON output to get corresponding IP address for Mac address

我正在尝试从写入此值的变量中获取对应于 MAC 地址 00 0C 29 DC 5B C2 的 IP 地址:

"arp.stdout_lines": [
    "iso.3.6.1.2.1.4.22.1.2.1.192.168.0.2 \"00 50 56 EC 7B 82 \"",
    "iso.3.6.1.2.1.4.22.1.2.1.192.168.0.128 \"00 0C 29 DC 5B C2 \"",
    "iso.3.6.1.2.1.4.22.1.2.1.192.168.0.254 \"00 50 56 EA F9 67 \""
     ]

我试过按以下方式进行:

tasks:
 - set_fact:
     matched:
        "{{ arp | regex_search( 'hi', '\1' ) }}"
   vars:
      hi: "{{ iso.3.6.1.2.1.4.22.1.2.1.(.*)\"00 50 56 EC 7B 81 \" }}"
   register: matched 

但是没有效果

Select 行,将第一项拆分为点,并连接最后四个元素,例如

    - set_fact:
        matched: "{{ matched|d([]) + [item[-4:]|join('.')] }}"
      loop: "{{ arp.stdout_lines|select('search', _mac)|
                                 map('split')|map('first')|
                                 map('split', '.')|list }}"
      vars:
        _mac: 00 0C 29 DC 5B C2

给予

  matched:
  - 192.168.0.128

系统方法是使用 ansible.netcommon.cli_parse and create a library of templates

考虑到您需要与网络相关的过滤,一种略有不同的方法是使用 ansible_facts,获取与给定 Mac 地址对应的 IP 地址。

- set_fact:
    matched: "{{ ansible_facts[item]['ipv4']['address'] }}"
  loop: "{{ ansible_interfaces }}"
  when:
    - ansible_facts[item]['macaddress'] is defined
    - ansible_facts[item]['macaddress'] == "00:0c:29:dc:5b:c2"

请注意,这需要 gather_facts: truesetup 模块为 运行。