python - 使用 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', ... }} 的服务器上,这显然不起作用。
但是,如果我不小心在脚本文件名中打错了字,比如称之为gather--hosts.py,它会抱怨找不到文件,所以它实际上是被解释的,但只是不用于填充父级它的内容。
有人知道我做错了什么吗?
如果它不会像这样工作,还有其他方法吗?
注意:我使用的是 ansible 2.10.2,python 3.8.6。
注意:如果我去掉变量只输出主机,它也不起作用。
解决方案
推荐阅读
- javascript - 在 AntD 的覆盖属性中使用自定义组件
- excel - 运行时错误 1004 object_global 的方法范围在 Excel 中使用命名范围搜索失败
- php - php 7.2 的 symfony2.8 中的 session_cache_limiter 错误
- c# - 插入新的 SQL 行后如何更新列表视图?
- python-3.x - 以月份为索引绘制数据
- javascript - 我的 javascript 代码会发生什么,它与流程无关
- iis - .Net 程序集 dll 不能在 IIS 10 上的经典 ASP 中调用,但在 windows cscript 上
- jquery - 将数据属性值设置为其他属性的相同元素
- python - 使用 anaconda 对黑色星期五数据集进行线性回归
- django - Django listview 从 url 捕获值然后传递给模板