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

时间:2014-09-30 16:22:32

标签: python ansible ansible-facts

我想写一个Python程序,它使用Ansible给我ansible HOST -m setup的事实。

当我这样称呼时,我得到一个响应,这使得它几乎只有纯粹的JSON:

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

有没有办法直接获得这个JSON响应而不解析shell输出(可能不太稳定)?我甚至可以直接在Python 3程序中使用Ansible吗?

2 个答案:

答案 0 :(得分:3)

版本stable-2.2stable-2.3和2.4 +

2.2,2.3和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目录,然后在其中编辑了一行以使其工作。

首先执行json.py

,我找到了ansible --version文件
$ 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 module location”找到json.py

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

最后,我编辑了v2_runner_on_ok文件中的json.py函数,看起来像这样(courtesy of armab on GitHub):

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文件的末尾。

stdout_callback = json

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

版本< =最新2.2稳定

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

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

如果将输出管道输入jq,如leucos所示,它会愉快地解析半有效的JSON。例如:

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

答案 1 :(得分:1)

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

另外,以shell为中心的方式是使用jq。这里有一个快速介绍:http://xmodulo.com/how-to-parse-json-string-via-command-line-on-linux.html