Ansible фильтр json_query - PullRequest
       14

Ansible фильтр json_query

1 голос
/ 05 февраля 2020

Итак, у меня получился вывод из ansible (пинг некоторых хостов с использованием модуля оболочки:

TASK [debug] ***************************************************************************************************************************************************************************************
skipping: [10.240.18.58]
ok: [10.240.18.57] => {
    "msg": {
        "changed": true,
        "msg": "All items completed",
        "results": [
            {
                "_ansible_ignore_errors": true,
                "_ansible_item_result": true,
                "_ansible_no_log": false,
                "_ansible_parsed": true,
                "changed": true,
                "cmd": "ping -c1 -W1 \"10.240.18.20\"",
                "delta": "0:00:00.005339",
                "end": "2020-02-05 10:41:06.527708",
                "failed": false,
                "invocation": {
                    "module_args": {
                        "_raw_params": "ping -c1 -W1 \"10.240.18.20\"",
                        "_uses_shell": true,
                        "chdir": null,
                        "creates": null,
                        "executable": null,
                        "removes": null,
                        "stdin": null,
                        "warn": true
                    }
                },
                "item": "10.240.18.20",
                "rc": 0,
                "start": "2020-02-05 10:41:06.522369",
                "stderr": "",
                "stderr_lines": [],
                "stdout": "PING 10.240.18.20 (10.240.18.20) 56(84) bytes of data.\n64 bytes from 10.240.18.20: icmp_req=1 ttl=64 time=0.268 ms\n\n--- 10.240.18.20 ping statistics ---\n1 packets transmitted, 1 received, 0% packet loss, time 0ms\nrtt min/avg/max/mdev = 0.268/0.268/0.268/0.000 ms",
                "stdout_lines": [
                    "PING 10.240.18.20 (10.240.18.20) 56(84) bytes of data.",
                    "64 bytes from 10.240.18.20: icmp_req=1 ttl=64 time=0.268 ms",
                    "",
                    "--- 10.240.18.20 ping statistics ---",
                    "1 packets transmitted, 1 received, 0% packet loss, time 0ms",
                    "rtt min/avg/max/mdev = 0.268/0.268/0.268/0.000 ms"
                ]
            },
            {
                "_ansible_ignore_errors": true,
                "_ansible_item_result": true,
                "_ansible_no_log": false,
                "_ansible_parsed": true,
                "changed": true,
                "cmd": "ping -c1 -W1 \"10.240.23.34\"",
                "delta": "0:00:00.006229",
                "end": "2020-02-05 10:41:09.889206",
                "failed": false,
                "invocation": {
                    "module_args": {
                        "_raw_params": "ping -c1 -W1 \"10.240.23.34\"",
                        "_uses_shell": true,
                        "chdir": null,
                        "creates": null,
                        "executable": null,
                        "removes": null,
                        "stdin": null,
                        "warn": true
                    }
                },
                "item": "10.240.23.34",
                "rc": 0,
                "start": "2020-02-05 10:41:09.882977",
                "stderr": "",
                "stderr_lines": [],
                "stdout": "PING 10.240.23.34 (10.240.23.34) 56(84) bytes of data.\n64 bytes from 10.240.23.34: icmp_req=1 ttl=63 time=1.33 ms\n\n--- 10.240.23.34 ping statistics ---\n1 packets transmitted, 1 received, 0% packet loss, time 0ms\nrtt min/avg/max/mdev = 1.333/1.333/1.333/0.000 ms",
                "stdout_lines": [
                    "PING 10.240.23.34 (10.240.23.34) 56(84) bytes of data.",
                    "64 bytes from 10.240.23.34: icmp_req=1 ttl=63 time=1.33 ms",
                    "",
                    "--- 10.240.23.34 ping statistics ---",
                    "1 packets transmitted, 1 received, 0% packet loss, time 0ms",
                    "rtt min/avg/max/mdev = 1.333/1.333/1.333/0.000 ms"
                ]
            },
            {
                "_ansible_ignore_errors": true,
                "_ansible_item_result": true,
                "_ansible_no_log": false,
                "_ansible_parsed": true,
                "changed": true,
                "cmd": "ping -c1 -W1 \"10.240.23.35\"",
                "delta": "0:00:00.006403",
                "end": "2020-02-05 10:41:13.237920",
                "failed": false,
                "invocation": {
                    "module_args": {
                        "_raw_params": "ping -c1 -W1 \"10.240.23.35\"",
                        "_uses_shell": true,
                        "chdir": null,
                        "creates": null,
                        "executable": null,
                        "removes": null,
                        "stdin": null,
                        "warn": true
                    }
                },
                "item": "10.240.23.35",
                "rc": 0,
                "start": "2020-02-05 10:41:13.231517",
                "stderr": "",
                "stderr_lines": [],
                "stdout": "PING 10.240.23.35 (10.240.23.35) 56(84) bytes of data.\n64 bytes from 10.240.23.35: icmp_req=1 ttl=63 time=1.36 ms\n\n--- 10.240.23.35 ping statistics ---\n1 packets transmitted, 1 received, 0% packet loss, time 0ms\nrtt min/avg/max/mdev = 1.364/1.364/1.364/0.000 ms",
                "stdout_lines": [
                    "PING 10.240.23.35 (10.240.23.35) 56(84) bytes of data.",
                    "64 bytes from 10.240.23.35: icmp_req=1 ttl=63 time=1.36 ms",
                    "",
                    "--- 10.240.23.35 ping statistics ---",
                    "1 packets transmitted, 1 received, 0% packet loss, time 0ms",
                    "rtt min/avg/max/mdev = 1.364/1.364/1.364/0.000 ms"
                ]
            }
        ]
    }
}

Я создал задачу ansible и хочу отображать с использованием debug строго следующие строки:

 "stdout_lines": [
                    "PING 10.240.18.20 (10.240.18.20) 56(84) bytes of data.",
                    "64 bytes from 10.240.18.20: icmp_req=1 ttl=64 time=0.268 ms",

для каждого из хостов.

Задача ansible будет такой:

   - debug:
       msg: "{{ smm_ping.json | json_query(pfilter) }}"
     vars:
       pfilter: "[*].{Ping response: stdout_lines}"
     when: "('primary' in default_hostname or 'Primary' in default_hostname)"
     tags: ['ic', 'smm']

По какой-то причине она не работает:

TASK [debug]
fatal: [10.240.18.57]: FAILED! => {"msg": "JMESPathError in json_query filter plugin:\nExpecting: colon, got: unquoted_identifier: Parse error at column 10, token \"response\" (UNQUOTED_IDENTIFIER), for expression:\n\"[*].{Ping response: stdout_lines}\"\n           ^"}

1 Ответ

2 голосов
/ 05 февраля 2020

Поскольку в вашем идентификаторе есть пробел, его необходимо заключить в кавычки.

pfilter: "[*].{\"Ping response\": stdout_lines}"

Чтобы упростить запись / чтение, вы можете использовать скалярный блок в виде yaml и удалить один уровень кавычек:

pfilter: >-
  [*].{"Ping response": stdout_lines}

Примечание. Символом кавычек для идентификаторов jmespath является двойная кавычка ("). Не используйте одинарные кавычки , которые используются для строковых значений. См. Спецификацию jmespath ниже.

Ссылки:

...