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

rgr*_*erg 88 ansible

只有当前剧本的主持人不属于某个组时,我才能运行一个ansible任务.在半伪代码中:

- name: my command
  command: echo stuff
  when: "if {{ ansible_hostname }} not in {{ ansible_current_groups }}"
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

小智 160

这是另一种方法:

- name: my command
  command: echo stuff
  when: "'groupname' not in group_names"
Run Code Online (Sandbox Code Playgroud)

group_names是一个神奇的变量,如下所示:http://docs.ansible.com/playbooks_variables.html#magic-variables-and-how-to-access-information-about-other-hosts:

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

  • 这种方式比groups ['groupname']中的`inventory_hostname'更强大,因为在灌浆本身不存在的情况下,Ansible会抛出一个错误,例如"确保你的变量名称不包含像' - '这样的无效字符:类型'StrictUndefined'不可迭代" (3认同)
  • +1,如果您不包括周围的引号,则会出现错误:`这个看起来很容易修复。似乎有一个以引号开头的值,并且YAML解析器期望行以相同的引号结束。 (2认同)
  • 我发现这种方法更具可读性,编写起来也很方便,但是两者都可以很好地工作。何时:库存主机名不在groups.certain_groups中 (2认同)
  • 现在的链接应该是 https://docs.ansible.com/ansible/latest/user_guide/playbooks_vars_facts.html#information-about-ansible-magic-variables。该文档已被移动。 (2认同)

nva*_*mei 15

您可以在位于group_vars/hosts文件中或直接在hosts文件中的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
Run Code Online (Sandbox Code Playgroud)

并运行这样的任务:

- name: "test"
  command: "echo {{test_var}}"
  when: test_var is defined and test_var
Run Code Online (Sandbox Code Playgroud)

  • 接受的答案对于该问题更准确,但这会引导您走上更好的道路 (2认同)

Yos*_*SaL 6

我想出了这个:

- name: my command
  command: echo stuff
  when: inventory_hostname not in groups.get('your-group', [])

Run Code Online (Sandbox Code Playgroud)