0

I'am trying to get the list of the device ID and the list of the port Id with ansible with regex but i get all the lines, below the output that i'am trying to parse it :

Device ID        Local Intrfce     Holdtme    Capability  Platform  Port ID
hello.fr.com #(this is in line separatly)
                 Fa 3/1/1         400             R S I    XXXX       Gi 3/3 #(and this in the next line)
cdp.fr.com
                 Fa 0/0/1         600            R S I     XXXX         Gi 3/3

Total cdp entries displayed : 2

and here my code:



tasks:
   - name: get neighbors
     ios_command:
       commands: 
         - show cdp neighbors
     register: output

   - set_fact: 
       reg_address: '(\S+)\s+'
       reg_ports: '\s+\S+\s+\d+\s+\w\s\w\s\w\s+\S+\s+(\S+\s\S+)'

   - set_fact: 
       List_interfaces: []
       List_ports: []

   - set_fact: 
       List_interfaces: "{{List_interfaces + item | string | regex_search(reg_address, '\\1') }}"
     loop: "{{output.stdout_lines[0]}}"
     when: "{{ List_interfaces | length }} > 0"
   - set_fact: 
       List_ports: "{{List_ports + item | string | regex_search(reg_ports, '\\1') }}"
     loop: "{{ output.stdout_lines[0] }}"
     when: "{{ List_ports | length }} > 0"

Brun
  • 9
  • 2
  • You will want to read up on the [MCVE](https://stackoverflow.com/help/mcve) section since it's not clear what _is_ happening versus what you _want_ to happen – mdaniel Jun 02 '21 at 15:51
  • I would like to get only a list of the device id and the port id but what i get an empty list this means that the regex didn’t match the list of lines – Brun Jun 02 '21 at 16:16
  • Have you considered [`show cdp neighbors detail`](https://www.cisco.com/E-Learning/bulk/public/tac/cim/cib/using_cisco_ios_software/cmdrefs/show_cdp_neighbors.htm) which looks more line delimited and thus might be easier to parse? – mdaniel Jun 03 '21 at 01:20

1 Answers1

1

When you fix your code as below, you will be able to get the result you want;

- set_fact:
        No_Of_Neighbors: "{{ output.stdout_lines[-1]['Total cdp entries displayed'] }}"
    - set_fact:
        cdp_neighbors: "{{ cdp_neighbors|default({})|
                           combine({Device_ID: {'Port_ID': Port_ID}}) }}"
      loop: "{{ range(0, No_Of_Neighbors|int)|list }}"
      vars:
        Device_ID: "{{ output.stdout_lines[item * 2 + 1] }}"
        params: "{{ output.stdout_lines[item * 2 + 2].split() }}"
        Port_ID: "{{ params[-2] }} {{ params[-1] }}"

And you will get the output as below;

  cdp_neighbors:
    cdp.fr.com:
      Port_ID: Gi 3/3
    hello.fr.com:
      Port_ID: Gi 3/3
Baris Sonmez
  • 477
  • 2
  • 8