Ansible JSON Output

18,817

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.

Share:
18,817

Related videos on Youtube

Akshay
Author by

Akshay

Updated on September 18, 2022

Comments

  • Akshay
    Akshay over 1 year

    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
    Akshay about 7 years
    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.
  • Konstantin Suvorov
    Konstantin Suvorov about 7 years
    This is the same operation, as if you set stdout_callback = json_cb in ansible.cfg.
  • JGurtz
    JGurtz almost 5 years
    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
  • harshavmb
    harshavmb over 4 years
    @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?