首页 > 解决方案 > 使用 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。

注意:如果我去掉变量只输出主机,它也不起作用。

标签: pythonlinuxansiblepipelookup

解决方案


推荐阅读