在ansible中解析表格数据

在ansible中解析表格数据,ansible,ansible-template,Ansible,Ansible Template,试图解析ansible中的路由信息,如下所示。 正确的方法是什么 [ { "destination": '10.110.2.192', "gateway": '10.110.0.129' "interface": 'eth2' }, { "destination": '10.110.2.64', "gateway": '10.110.0.129' "interface": 'eth2'

试图解析ansible中的路由信息,如下所示。 正确的方法是什么

[
   { 
      "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'
     }
]

您可以以此为例:

第一部分是带有正则表达式搜索的本地Ansible,第二部分使用远程主机上的
jq
作为助手

---
- 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 }}"
---
-主机:服务器
收集事实:不
任务:
#远程主机上没有jq
-命令:netstat-nrw
登记:路线
-调试:
msg:“{{route}}”
带_项:“{routes.stdout_行[2::}”
变量:
路由:“{item | regex_search(regex,“\g”,“\g”,“\g”,“\g”,“\g”,“\g”)}”
正则表达式:“^(?P\S+)\S+(?P\S+)\S+(?P\S+)\S+(?P\S+).*\S(?P\S+)”
#在远程主机上使用jq
-shell:netstat-nrw | tail-n+3 | jq-R-c'捕获(“^(?\\S+)\\S+(?\\S+)\\S+)\\S+(?\\S+)\\S+(?\\S+).*\\S(?\\S+)”
登记:路线
-调试:
msg:“{{item}}”
与_项一起:“{routes.stdout_lines | map('from_json')| list}”

请提供原始数据。但很可能在ansible中直接解析数据是没有意义的。