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


106

我只想在当前剧本的主机不属于某个组的情况下才能执行ansible任务。在半伪代码中:

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

我应该怎么做?

Answers:


198

这是另一种方法:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"

group_names是此处记录的魔术变量:https : //docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables

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


3
+1,如果您不包括周围的引号,则会出现错误:This one looks easy to fix. It seems that there is a value started with a quote, and the YAML parser is expecting to see the line ended with the same kind of quote.
Peter Ajtai

3
我发现此方法更具可读性和编写方便性,但是两者都可以很好地工作。when: inventory_hostname not in groups.certain_groups
利亚姆

4
这种方法比inventory_hostname in groups['groupname']因为在浆液本身不存在的情况下更健壮,所以Ansible会抛出类似“确保变量名不包含无效字符(如'-')的错误:'StrictUndefined'类型的参数不可迭代”的错误
hamx0r

20

您可以在位于group_vars/主机文件中或直接位于主机文件中的vars文件中设置控制变量,如下所示:

[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

2
接受的答案对于该问题而言更准确,但这会引导您走上更好的道路
nik.shornikov
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.