如果是组成员,如何跳过 Ansible 主机

How to Skip Ansible Host if member of a group

我正在编写一本剧本(用于 AWX)来为我们的一个 Web 应用程序处理一些后端处理。 通过对 AWX 的 REST 调用传递给剧本的额外变量之一用于传递主机
到剧本

hosts: {{target}}

目标可以是单个服务器或服务器列表。
问题:如果主机不是清单组的成员,我如何使用模式跳过主机
例如,如果我想让 playbook 跳过一个服务器,如果它在 inventory
的暂存组中 我尝试了以下方法:

hosts: "{{target}}:!staging"

这仅在仅将一台服务器作为目标变量发送时有效,但如果使用列表调用则失败。

如果您确实使用 : 作为主机的分隔符而不是 ,,这应该有效。


语法 host1:host2:host3:!staging 有效,但另一方面,host1,host2,host3:!staging 确实会生成警告

[WARNING]: Could not match supplied host pattern, ignoring: host3:!staging

这很可能也是您面临的问题。
The two syntaxes are documented here

给定库存:

all:
  hosts:
    host1:
    host2:
    host3:

  children:
    staging:
      hosts:
        host2:

剧本:

- hosts: host1:host2:host3:!staging
  gather_facts: no
      
  tasks:
    - debug:
        msg: "{{ inventory_hostname  }}"

这产生了回顾:

PLAY [host1:host2:host3:!staging] *********************************************************************************

TASK [debug] ******************************************************************************************************
ok: [host1] => {
    "msg": "host1"
}
ok: [host3] => {
    "msg": "host3"
}

PLAY RECAP ********************************************************************************************************
host1                      : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
host3                      : ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

它在使用剧本时给出了完全相同的回顾:

- hosts: "{{ target }}:!staging"
  gather_facts: no
      
  tasks:
    - debug:
        msg: "{{ inventory_hostname  }}"

运行 来自:

ansible-playbook play.yml -i inventory.yml -e "target=host1:host2:host3"