Ansible 仅当主机不属于组时运行任务

Ansible 仅当主机不属于组时运行任务,ansible,Ansible,我希望仅当当前剧本的主机不属于某个组时才能运行ansible任务。在半伪代码中: - name: my command command: echo stuff when: "if {{ ansible_hostname }} not in {{ ansible_current_groups }}" 我应该怎么做?您可以在组\u vars/中的vars文件中设置控制变量,或者直接在hosts文件中设置,如下所示: [vagrant:vars] test_var=true [locati

我希望仅当当前剧本的主机不属于某个组时才能运行ansible任务。在半伪代码中:

- name: my command
  command: echo stuff
  when: "if {{ ansible_hostname }} not in {{ ansible_current_groups }}"

我应该怎么做?

您可以在
组\u vars/
中的vars文件中设置控制变量,或者直接在hosts文件中设置,如下所示:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2
- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var
并运行如下任务:

[vagrant:vars]
test_var=true

[location-1]
192.168.33.10 hostname=apollo

[location-2]
192.168.33.20 hostname=zeus

[vagrant:children]
location-1
location-2
- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var

下面是另一种方法:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"
group\u names
是一个神奇的变量,如本文所述:

group_names是当前主机所在的所有组的列表(数组)


+1如果不包括周围的引号,则会出现错误:
这一个看起来很容易修复。似乎有一个以引号开头的值,YAML解析器希望看到该行以相同类型的引号结尾。
我发现这种方法可读性更高,编写起来也更方便,但两种方法都同样有效<代码>时间:库存主机名不在组中。某些库存主机名不在组中。这种方法比
库存主机名在组['groupname']
中更可靠,因为在灌浆本身不存在的情况下,Ansible将抛出如下错误“确保变量名不包含诸如“-”之类的无效字符:类型为“StrictUndefined”的参数不可编辑”链接现在应该是。文档已被移动。对于该问题,接受的答案更准确,但这将引导您走上一条更好的道路