What is the way to get the output of Ansible ad-hoc command in json, csv or other format
Use the -o option to display the output of Ansible ad hoc commands in a single line format.
Automation with Ansible Playbooks Ad hoc commands are commands which can be run individually to perform quick functions. These commands need not be performed later. For example, you have to reboot all your company servers. For this, you will run the Adhoc commands from '/usr/bin/ansible'.
An Ansible ad hoc command uses the /usr/bin/ansible command-line tool to automate a single task on one or more managed nodes. ad hoc commands are quick and easy, but they are not reusable. So why learn about ad hoc commands first? ad hoc commands demonstrate the simplicity and power of Ansible.
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's environment variables here https://docs.ansible.com/ansible/latest/reference_appendices/config.html#environment-variables
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 }}"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With