[英]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
:我正在尝试使用
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.但是
json
由于数据格式错误而中断。 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.我尝试使用命令行 ansible 执行此操作:
ansible -m setup localhost > bla
然后更改文件,然后尝试json.load
它但仍然卡住了。
Is there an ansible built-in for this?有内置的 ansible 吗?
The output from Ansible isn't really meant to be machine-parseable.来自 Ansible 的 output 并不是真正意义上的机器可解析的。 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.例如,在您的示例中由
res.stdout.read()
生成的内容包括 ANSI 颜色代码,这些代码很适合显示,但即使数据在其他方面有效,也会使数据无效 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.您可以通过
res
变量的events
属性以结构化形式访问setup
模块的结果(即,已经解析为 Python 数据结构)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.