3

Could you please help me fetch Ansible-Playbook output in a JSON Format. I do get a JSON output if I set stdout_callback variable as "json" in ansible.cfg

But that output is not in realtime. The result is shown when the whole playbook is executed. How can I get the output as soon as a task is executed ?

Akshay
  • 123
  • 1
  • 2
  • 5
  • Looks like it's not possible nor will it be. https://github.com/ansible/ansible/issues/3887 – ceejayoz Mar 02 '17 at 15:13
  • I'm not sure what you actually want. When you think of what JSON actually is (from `{` to `}`), any partial output will not be a correct JSON. – techraf Mar 03 '17 at 05:54

1 Answers1

6

There are definitely some problems to overcome, but nothing is impossible.

Here is something for you to play with:

Save this as ./callback_plugins/json_cb.py:

from __future__ import absolute_import
from ansible.plugins.callback import CallbackBase
import json

class CallbackModule(CallbackBase):

    CALLBACK_VERSION = 2.0
    CALLBACK_TYPE = 'stdout'
    CALLBACK_NAME = 'json_cb'

    def __init__(self):
        self.tasks = {}

    def dump_result(self, result):
        print(json.dumps(dict(name=self.tasks[result._task._uuid],result=result._result)))

    def v2_playbook_on_task_start(self, task, is_conditional):
        self.tasks[task._uuid] = task.name

    v2_runner_on_ok = dump_result
    v2_runner_on_failed = dump_result

And execute your playbook as:

ANSIBLE_STDOUT_CALLBACK=json_cb ansible-playbook myplaybook.yml

This will print JSON-object for every completed task (ok or failed).

But you are going to feed this into some other tool to parse it, aren't you? So this other tool should understand continuous stream of JSON objects.

Konstantin Suvorov
  • 3,996
  • 1
  • 12
  • 13
  • Perfect!! Thank You. Can you please explain "ANSIBLE_STDOUT_CALLBACK=json_cb ansible-playbook myplaybook.yml". I dont understand how an assignment operation, is bringing a playbook into execution. – Akshay Mar 05 '17 at 05:03
  • This is the same operation, as if you set `stdout_callback = json_cb` in ansible.cfg. – Konstantin Suvorov Mar 05 '17 at 08:06
  • This concept is perfect for piping to tee. This way it becomes possible to monitor status *and as well* act on the complete data from the saved file with jq or other tooling – JGurtz Aug 13 '19 at 00:18
  • 1
    @KonstantinSuvorov, Thanks for this code snippet. However, with `ANSIBLE_STDOUT_CALLBACK=json`, ansible prints stats of `changed`, `failures`, `ignored`, `ok` etc., of all the tasks in the end, how can we get those too? – harshavmb Jan 08 '20 at 14:04