Use facts compiled by ANSIBLE programmatically

I would like to write a Python program that uses facts that Ansible gives me with ansible HOST -m setup.

When I call it, I get a response that only makes it almost pure JSON:

$ ansible localhost -m setup
localhost | success >> {
    // actual data
}

Is there a way to get this JSON response directly without parsing the shell output (which may not be very stable)? Can I use Ansible directly in a Python 3 program?

+5
source share
2 answers

stable-2.2, stable-2.3, 2.4 +

2.2, 2.3 2.4 ANSIBLE_STDOUT_CALLBACK. , ansible.cfg, :

[defaults]
bin_ansible_callbacks = True
callback_plugins = ~/.ansible/callback_plugins

, . callback_plugins, . , json- . json, callback_plugins, , .

json.py, ansible --version

$ ansible --version
ansible 2.4.0.0
    config file = /Users/artburkart/Code/ansible.cfg
    configured module search path = [u'/Users/artburkart/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
    ansible python module location = /usr/local/lib/python2.7/site-packages/ansible
    executable location = /usr/local/bin/ansible
    python version = 2.7.13 (default, Jul 18 2017, 09:17:00) [GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)]

, " python", json.py.

cp /usr/local/lib/python2.7/site-packages/ansible/plugins/callback/json.py ~/.ansible/callback_plugins/

, v2_runner_on_ok json.py, ( armab GitHub):

def v2_runner_on_ok(self, result, **kwargs):
    host = result._host
    self.results[-1]['tasks'][-1]['hosts'][host.name] = result._result
    print(json.dumps({host.name: result._result}, indent=4))

, , :

ANSIBLE_STDOUT_CALLBACK=json ansible all -i localhost, -c local -m setup | jq

JSON, ansible.cfg, .

stdout_callback = json

, .

<= 2,2

:

ansible all --inventory 127.0.0.1, --connection local --module-name setup | sed '1 s/^.*|.*=>.*$/{/g'

jq, leucos, JSON. :

ansible all -i hosts -m setup | sed '1 s/^.*|.*=>.*$/{/g' | jq -r '.ansible_facts.ansible_distribution'
CentOS
Ubuntu
+3

All Articles