Linux – Ansible JSON Output

ansibleansible-playbookautomationlinux

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 ?

Best Answer

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.