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

标签 ansible

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

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

请阅读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/

相关文章:

ansible - 在 ansible 中成为非 root 用户失败

ansible - 在 Ansible 中,如何检查是否安装了特定版本的 MySQL?

windows - Ansible Windows ACL

python - jinja2 模板中的列表

windows - 如何正确循环遍历 Ansible 中 block 内任务的文件?

ansible - 无法将 list 脚本解析为 list

ssh - 通过ansible yum在CentOS 7上安装Xfce

ssh - 使用 ansible 执行 ssh-add 会引发错误

Ansible:将注册变量保存到文件

mysql - 如何使用 Ansible 创建大型数据库