Home > database >  Ansible parse yaml
Ansible parse yaml

Time:11-30

I'm trying to get the IP address that corresponds to the MAC address 00 0C 29 DC 5B C2 from the variable in which this value is written:

"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 \""
     ]

I tried to do it the following way:

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 

But nothing works

CodePudding user response:

Select the lines, split the first item on dots, and join the last four elements, e.g.

    - 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

gives

  matched:
  - 192.168.0.128

A systemic approach would be using ansible.netcommon.cli_parse and create a library of templates.

CodePudding user response:

Considering that you want network related filtering, a slightly different approach would be using ansible_facts, to get the IP address corresponding to a given Mac address.

- 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"

Note that this requires gather_facts: true or setup module to be run.

  • Related