[英]How can I get the ansible facts of my local machine in a json?
我正在尝试使用ansible_runner
从我的本地机器收集事实:
import ansible_runner, json
res = ansible_runnner.run(
module='setup',
host_pattern='localhost',
)
json.loads(res.stdout.read())
但是json
由于数据格式错误而中断。 我尝试使用命令行 ansible 执行此操作: ansible -m setup localhost > bla
然后更改文件,然后尝试json.load
它但仍然卡住了。
有内置的 ansible 吗?
来自 Ansible 的 output 并不是真正意义上的机器可解析的。 例如,在您的示例中由res.stdout.read()
生成的内容包括 ANSI 颜色代码,这些代码很适合显示,但即使数据在其他方面有效,也会使数据无效 JSON。
您可以通过res
变量的events
属性以结构化形式访问setup
模块的结果(即,已经解析为 Python 数据结构)。
例如:
>>> 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.