繁体   English   中英

如何在 json 中获取本地机器的 ansible 事实?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM