【发布时间】:2019-07-07 19:40:27
【问题描述】:
前段时间,有人建议使用动态清单根据模板中的位置和其他变量生成不同的主机文件,但我遇到了一个相当大的问题:
从模板创建清单后,我需要刷新它(我使用 meta:refresh_inventory 执行此操作)以便 Ansible 在新添加的主机上执行任务,但是,如果主机最初不在 hosts 文件中,ansible 会不对其执行任务。另一方面,如果在更改主机文件后新形成的文件中没有主机,那么 Ansible 会像它应该的那样省略主机,因此 refresh_inventory 完成了一半的工作。有没有办法解决这个问题?
例如我有 1 个任务从模板生成主机文件,然后刷新库存,然后在所有主机上执行一个简单的任务,例如显示消息:
tasks:
- name: Creating inventory template
local_action:
module: template
src: hosts.j2
dest: "/opt/ansible/inventories/{{location}}/hosts"
mode: 0777
force: yes
backup: yes
ignore_errors: yes
run_once: true
- name: "Refreshing hosts file for {{location}} location"
meta: refresh_inventory
- name: Force refresh of host errors
meta: clear_host_errors
- name: Show message
debug: msg="This works for this host"
如果初始 hosts 文件有主机 A、B、C、D,而新创建的清单有 B、C、D,则一切正常:
ok: [B] => {
"msg": "This works for this host"
}
ok: [C] => {
"msg": "This works for this host"
}
ok: [D] => {
"msg": "This works for this host"
}
但是,如果新形成的主机文件有主机 B、C、D、E(E 不存在于初始主机文件中),那么结果又是:
ok: [B] => {
"msg": "This works for this host"
}
ok: [C] => {
"msg": "This works for this host"
}
ok: [D] => {
"msg": "This works for this host"
}
缺少 E 的任务。现在,如果我重播剧本,只添加另一个主机,比如 F,那么结果如下所示:
ok: [B] => {
"msg": "This works for this host"
}
ok: [C] => {
"msg": "This works for this host"
}
ok: [D] => {
"msg": "This works for this host"
}
ok: [E] => {
"msg": "This works for this host"
}
但没有 F,它在刷新之前已经添加到库存文件中。
那么,有什么想法吗?
【问题讨论】:
-
贴出如何测试“
if the host was not initially in the hosts file, Ansible does not execute tasks on it”的代码。让它minimal. -
我用代码和示例更新了我的初始帖子
标签: networking automation ansible refresh inventory