7

What is the way to get the output of Ansible ad-hoc command in JSON, CSV or other format?

U880D
  • 8,601
  • 6
  • 24
  • 40
Rajesh Yidi
  • 91
  • 1
  • 3

3 Answers3

7

You could also do it through the environment variables if you do not want to modify the .cfg file, for example:

ANSIBLE_LOAD_CALLBACK_PLUGINS=true \
ANSIBLE_STDOUT_CALLBACK=json \
ansible all \
  -a "df -h /tmp"

More info on Ansible environment variables here: https://docs.ansible.com/ansible/latest/reference_appendices/config.html#environment-variables.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
mher
  • 369
  • 3
  • 7
4

In ansible.cfg add:

[defaults]
stdout_callback = json

See documentation

Instead of this:

ok: [localhost] => {
    "msg": "test"
}

You will have:

{
    "plays": [
        {
            "play": {
                "id": "720000f8-9450-586c-9a68-000000000005", 
                "name": "Json Test"
            }, 
            "tasks": [
                {
                    "hosts": {
                        "localhost": {
                            "_ansible_no_log": false, 
                            "_ansible_verbose_always": true, 
                            "changed": false, 
                            "msg": "test"
                        }
                    }, 
                    "task": {
                        "id": "720000f8-9450-586c-9a68-000000000007", 
                        "name": "Debug"
                    }
                }
            ]
        }
    ], 
    "stats": {
        "localhost": {
            "changed": 0, 
            "failures": 0, 
            "ok": 1, 
            "skipped": 0, 
            "unreachable": 0
        }
    }
}

For the following playbook:

---
- name: Json Test
  hosts: localhost
  gather_facts: False

  vars: 
    test: test


  tasks:
    - name: Debug
      debug:
        msg: "{{ test  }}"
imjoseangel
  • 3,543
  • 3
  • 22
  • 30
2

You need to use at least Ansible 2.5

and then set this in your ansible config:

stdout_callback = json
bin_ansible_callbacks = True

A quick note (complaint?) about ansible config... config files are not additive. If you have multiple config files (e.g. /etc/ansible/ansible.cfg and ~/.ansible.cfg) it will only take values from ~/.ansible.

Here's the config file order:

https://docs.ansible.com/ansible/latest/reference_appendices/config.html#the-configuration-file

Here's the bug:

https://github.com/ansible/ansible/issues/17914

Also here's the full callback plugin list:

https://docs.ansible.com/ansible/2.6/plugins/callback.html#plugin-list

Clintm
  • 4,505
  • 3
  • 41
  • 54
  • This worked for me. I was missing the `bin_ansible_callbacks = True` directive in `~/.ansible.cfg`. Having added that, I get JSON output from `ansible(1)` ad-hoc commands. Thank you. – NYCeyes Jan 29 '20 at 15:36