CIsForCookies
CIsForCookies

Reputation: 12837

How can I get the ansible facts of my local machine in a json?

I'm trying to gather the facts from my local machine using ansible_runner:

import ansible_runner, json


res = ansible_runnner.run(
    module='setup',
    host_pattern='localhost',
)
json.loads(res.stdout.read())

But the json breaks because the data is malformed. I tried doing it with command line ansible: ansible -m setup localhost > bla and then changing the file and then trying to json.load it but still got stuck.

Is there an ansible built-in for this?

Upvotes: 1

Views: 603

Answers (1)

larsks
larsks

Reputation: 311978

The output from Ansible isn't really meant to be machine-parseable. For example, the content produced by res.stdout.read() in your example includes ANSI color codes, which are nice for display but render the data invalid even if it were otherwise valid JSON.

You can access the result of the setup module in structured form (that is, already parsed into Python data structures) via the events attribute of your res variable.

For example:

>>> import ansible_runner
>>> res = ansible_runner.run(module='setup', host_pattern='localhost')
>>> setup_results= next(x for x in res.events if  x['event'] == 'runner_on_ok' and x['event_data']['task'] == 'setup')
>>> facts = setup_results['event_data']['res']['ansible_facts']
>>> print(facts['ansible_processor_vcpus'])
8

Upvotes: 3

Related Questions