gpt4 book ai didi

ansible - 仅当组存在时如何运行 ansible 剧本?

转载 作者:行者123 更新时间:2023-12-02 20:24:45 26 4
gpt4 key购买 nike

我想知道是否有人找到了一种解决方案,可以在库存组未定义或为空时避免显示任何警告。

我只想让剧本的一部分运行如果组存在并且不为空,如果不存在,跳过而不警告

请阅读https://github.com/ansible/ansible/issues/35255#issuecomment-388455001并测试替代方案,因为我花了很多时间试图找到解决此问题的方法。

到目前为止,我无法找到任何方法来避免未定义组时出现警告。

最佳答案

我有点不确定我是否回答了正确的问题,但就这样吧。我将“如果一个组存在并且不为空”解释为“当前执行的主机属于某个组”。

如果您想问诸如“我可以从当前主机中找出是否有其他主机属于当前主机不属于的组”或“我可以运行当为某些组定义的主机无法访问时,剧本没有错误,”那么恐怕这不能回答您的问题:)

但是可以使用 Ansible's default vars 之一来根据当前主机是否属于某个组来运行任务。 , group_names

以下 playbook 包含两个任务,一项是在当前主机属于组 existent 时运行调试任务,一项是在当前主机属于组时运行调试任务主机属于不存在组。如输出所示,第一个任务运行,而第二个任务则不运行。

hosts.yml

[existent]
localhost ansible_connection=local

playbook.yml

- hosts: all
gather_facts: true

tasks:
- name: This command will run.
debug:
msg: "The group `existent_1` exists!"
when:
- "'existent_1' in groups"

- name: This command will not run.
debug:
msg: "The group `existent_1` exists and this host is in it!"
when:
- "'existent_1' in groups"
- "'existent_1' in group_names"

- name: This command will run.
debug:
msg: "The group `existent_2` exists and this host is in it!"
when:
- "'existent_2' in groups"
- "'existent_2' in group_names"

- name: This command will not run.
debug:
msg: "The group `nonexistent` exists!"
when:
- "'nonexistent' in groups"
- "'nonexistent' in group_names"

输出

➜ ansible-playbook -i hosts.yml playbook.yml

PLAY [all] *********************************************************************

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [This command will run.] **************************************************
ok: [localhost] =>
msg: The group `existent_1` exists!

TASK [This command will not run.] **********************************************
skipping: [localhost]

TASK [This command will run.] **************************************************
ok: [localhost] =>
msg: The group `existent_2` exists and this host is in it!

TASK [This command will not run.] **********************************************
skipping: [localhost]

PLAY RECAP *********************************************************************
localhost : ok=3 changed=0 unreachable=0 failed=0

关于ansible - 仅当组存在时如何运行 ansible 剧本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50298679/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com