如何解决使用python脚本在ansible清单中具有变量的动态主机
我希望能够使ansible库存调查数据库,以使正确的主机可以工作。
为完成这项工作,我编写了一个Python脚本,该脚本从数据库中查询主机名并将其打印为yaml。
我进行了测试,以查看管道查找插件是否能够获取输出:
$ ansible webservers -m debug -a "msg={{ lookup('pipe','./gather-hosts.py') }}"
{{ lookup('pipe','./gather-hosts.py') }} | SUCCESS => {
"msg": "web001:\n descr: External websites\n phpversion: 7.3\nweb002:\n descr: External websites\n phpversion: 7.3\nweb003:\n descr: Internal websites\n phpversion: 7.4\nweb004:\n descr: Internal websites\n phpversion: 7.4"
}
这似乎可行,我转到下一步,主机清单文件:
---
webservers:
hosts: "{{ lookup('pipe','./gather-hosts.py') }}"
当我尝试运行此代码时:
$ ansible-playbook playbook.yml
PLAY [webservers] *****************************************************************************************************
TASK [Gathering Facts] ************************************************************************************************
fatal: [{{ lookup('pipe','./gather-hosts.py') }}]: UNREACHABLE! => {"changed": false,"msg": "Failed to connect to the host via ssh: ssh: Could not resolve hostname {{ lookup('pipe','./gather-hosts.py') }}: Name or service not known","unreachable": true}
PLAY RECAP ************************************************************************************************************
{{ lookup('pipe','./gather-hosts.py') }} : ok=0 changed=0 unreachable=1 failed=0 skipped=0 rescued=0 ignored=0
因此,它不是使用管道输出作为Webservers:组的数据,而是尝试通过ssh将服务器连接到名为{{lookup('pipe',...}})的服务器上,这显然行不通。
但是,如果我不小心在脚本文件名中输入了错字,请说它叫“ ghost--hosts.py”,它会抱怨找不到文件,因此它实际上是被解释的,只是不用于填充父项及其内容。
有人知道我做错了什么吗?
如果它不能像这样工作,还有另一种方法吗?
注意:我使用的是ansible 2.10.2,python 3.8.6。
注意:如果我去掉变量而只输出主机,那么它也不起作用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。