将列表作为清单传递给ansible_runner python 模块



我想用ansible_runner在主机上做一些解析。 我有一个脚本,它从数据库中收集主机列表,然后我想将该列表传递给 python 模块ansible_runner而无需将"清单"写入磁盘。

我试图根据我从文档中理解的内容来做到这一点:

>> import ansible_runner
>> hostlist = ['host1', 'host2']
>>> r = ansible_runner.run(private_data_dir='.',inventory=hostlist, playbook='check_ping.yml')

我似乎传递的列表中的每个元素都被视为位于库存目录中的库存文件。我只想使用列表中的元素作为要使用的主机,在这种情况下执行ping。

我的问题是如何将库存变量传递给ansible_runner Python 模块,无论它是磁盘上不存在的 JSON 文件、列表、字典吗? 并让 Ansible 连接到这些。

构建一个嵌套字典,如图所示。给一个可迭代的主机我想要

hosts = {r:None for r in hostsiwant}
inv = {'all': {'hosts': hosts}}
r = ansible_runner.run(inventory=inv, #remaining arguments as needed

ansible_runner.run()接受以下参数inventory值。

  1. private_data_dir中库存文件的路径
  2. 支持 YAML/json 清单结构的原生 python 字典
  3. 文本 INI 格式的字符串
  4. 清单来源列表或用于禁用传递的空列表 库存

如果未传递,则此参数的默认值为private_data_dir/inventory目录。传递此参数将覆盖清单目录/文件。文档在这里

在问题中给出的代码示例中,主机列表作为参数的值传递inventory并根据设计,列表值被视为清单源文件的列表。

例子:

  • 将库存作为字典传递:

可以使用python构建具有所有必需详细信息的字典,并作为ansible_runner.run(inventory=my_inventory)传递。

web_serverbackend_server将成为主机组名称。


import ansible_runner
my_inventory = {
"web_server": {
"hosts": {
"webserver_1.example.com": {
"ansible_user": "test",
"ansible_ssh_private_key_file": "test_user.pem",
"ansible_host": "webserver_1.example.com"
},
"webserver_2.example.com": {
"ansible_user": "test",
"ansible_ssh_private_key_file": "test_user.pem",
"ansible_host": "webserver_1.example.com"
}
}
},
"backend_server": {
"hosts": {
"backend_server_1.example.com": {
"ansible_user": "test",
"ansible_ssh_private_key_file": "test_user.pem",
"ansible_host": "backend_server_1.example.com"
}
}
}
}
runner_result = ansible_runner.run(private_data_dir='.', inventory=my_inventory, playbook='check_ping.yml')
print(runner_result.stats)

注意:这样做会将内容保存在hosts.json目录中private_data_dir/inventory

  • 写入库存文件:

另一种方法是将 YAML/json 格式的主机详细信息写入目录中private_data_dir/inventory文件中。

最新更新