-1

Trying to parse route information in ansible to something like below. What's the right way to do

[
   { 
      "destination":  '10.110.2.192',
      "gateway":  '10.110.0.129'
      "interface": 'eth2'
    },
    {
      "destination": '10.110.2.64',
       "gateway":   '10.110.0.129'
       "interface": 'eth2'
     },
    {
      "destination": '10.110.1.0',
      "gateway": '0.0.0.0'
       "interface": 'eth0'
     },
    {
      "destination": '10.110.1.128',
      "gateway": '0.0.0.0'
       "interface": 'eth2'
     },
    {
      "destination": '0.0.0.0',
      "gateway": '10.110.1.1'
      "interface": 'eth0'
     }
]
Dave2e
  • 22,192
  • 18
  • 42
  • 50
  • Please supply the original data. But most likely it won't make sense to parse your data directly in ansible. – iptizer Apr 01 '17 at 11:27

1 Answers1

0

You can take this as example:

First part is native Ansible with regex search, and second part uses jq on remote host as helper.

---
- hosts: server
  gather_facts: no
  tasks:
    # without jq on remote host
    - command: netstat -nrw
      register: routes
    - debug:
        msg: "{{ route }}"
      with_items: "{{ routes.stdout_lines[2:] }}"
      vars:
        route: '{{ item | regex_search(regex,"\g<dest>","\g<gw>","\g<mask>","\g<flags>","\g<iface>") }}'
        regex: '^(?P<dest>\S+)\s+(?P<gw>\S+)\s+(?P<mask>\S+)\s+(?P<flags>\S+).*\s(?P<iface>\S+)$'
    # with jq on remote host
    - shell: netstat -nrw | tail -n+3 | jq -R -c 'capture("^(?<dest>\\S+)\\s+(?<gw>\\S+)\\s+(?<mask>\\S+)\\s+(?<flags>\\S+).*\\s(?<iface>\\S+)$")'
      register: routes
    - debug:
        msg: "{{ item }}"
      with_items: "{{ routes.stdout_lines | map('from_json') | list }}"
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193