繁体   English   中英

以编程方式使用ansible收集的事实

[英]Use facts gathered by ansible programmatically

我想编写一个Python程序,该程序使用Ansible为我提供ansible HOST -m setup的事实。

当我打电话给我时,我得到一个响应,使其几乎只使用纯JSON:

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

有没有某种方法可以直接获取此JSON响应而无需解析shell输出(可能不太稳定)? 我什至可以直接在Python 3程序中使用Ansible吗?

稳定版本2.2稳定版本2.3和2.4+

适用于ANSIBLE_STDOUT_CALLBACK和2.4的最新ansible发行版均支持ANSIBLE_STDOUT_CALLBACK变量。 要使用它,您需要添加一个ansible.cfg文件:

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

您可以将其放置在任何使用ansible的地方。 然后,您需要创建callback_plugins目录(如果尚未创建)。 最后,您需要在目录中添加一个自定义json解析器。 我将与ansible捆绑在一起的json解析器复制到callback_plugins目录,然后在其中编辑一行以使其正常工作。

我通过首先执行ansible --version找到了json.py文件

$ 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)]

然后使用“ ansible python模块位置”找到json.py

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

最后,我在json.py文件中编辑了v2_runner_on_ok函数,如下所示( 由GitHub上的armab提供 ):

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添加到上述的ansible.cfg文件的末尾。

stdout_callback = json

这样,您就不再需要包含环境变量。

版本<=最新的2.2稳定版

当查询实例时,我使用以下命令:

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

如果按照leucos的建议将输出通过管道传递jq ,它将很高兴地解析半有效的JSON。 例如:

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

如果Python2适合您,则可以直接使用Ansible API。 您可以在这里找到详细的说明: http ://docs.ansible.com/developing_api.html确实很容易。

而以壳为中心的替代方法是使用jq。 这里有一个快速介绍: http : //xmodulo.com/how-to-parse-json-string-via-command-line-on-linux.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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