---

- name: show_ip_bgp_summary
  parser_metadata:
    version: 1.0
    command: show ip bgp summary
    network_os: ios

- name: match not active
  register: not_active
  pattern_match:
    regex: "BGP not active"
    match_all: true

- name: set_vars bgp state active
  set_vars:
    process_state: "active"

- name: set_vars bgp state not active
  set_vars:
    process_state: "not active"
  when: "not_active.0.matches == 'BGP not active'"

- name: match sections
  register: context
  pattern_match:
    regex: "Neighbor.+"
    match_all: true
    match_greedy: true
  when: process_state == 'active'

- name: match lines
  register: lines
  pattern_match:
    regex: "^[0-9a-f.]+"
    content: "{{ context.0 }}"
    match_all: true
    match_greedy: true
  when: process_state == 'active'

- name: match neighbors
  register: matched_neighbors
  loop: "{{ lines }}"
  pattern_match:
    regex: "(?P<ip>[0-9a-f.]+)\\s+(?P<version>\\d+)\\s+(?P<asn>\\d+)\\s+(?P<msgrcvd>\\d+)\\s+(?P<msgsent>\\d+)\\s+(?P<tblver>\\d+)\\s+(?P<inq>\\d+)\\s+(?P<outq>\\d+)\\s+(?P<timer>\\S+)\\s+(?P<state>\\S+)"
    content: "{{ item }}"
  when: process_state == 'active'

- name: template bgp values
  extend: cisco_ios.vrf.DEFAULT.protocols
  register: bgp
  export: true
  export_as: dict
  json_template:
    template:
      - key: "process_state"
        value: "{{ process_state }}"

- name: template bgp neighbor entries
  extend: cisco_ios.vrf.DEFAULT.protocols.bgp
  register: neighbors
  export: true
  export_as: dict
  loop: "{{ matched_neighbors }}"
  when: process_state == 'active'
  json_template:
    template:
      - key: "{{ item.ip }}"
        object:
          - key: state_pfxrcd
            value: "{{ item.state }}"
          - key: asn
            value: "{{ item.asn }}"
          - key: timer
            value: "{{ item.timer }}"
          - key: ip_version
            value: "{{ item.version }}"
