仅当主机名包含字符串时才运行Ansible任务

luc*_*axi 23 ansible

我在角色中有多个任务,如下所示.我不想创建另一个yml文件来处理此任务.我已经为Web服务器提供了一个包含,但是我们的一些Perl服务器需要安装一些Web包.

- name: Install Perl Modules
  command: <command>
  with_dict: perl_modules

- name: Install PHP Modules
  command: <command>
  with_dict: php_modules
  when: <Install php modules only if hostname contains the word "batch">
Run Code Online (Sandbox Code Playgroud)

主机库存文件

[webs]
web01
web02
web03

[perl]
perl01
perl02
perl03
perl-batch01
perl-batch02
Run Code Online (Sandbox Code Playgroud)

Mic*_*sek 46

下面应该做的诀窍:

- name: Install PHP Modules
  command: <command>
  with_dict: php_modules
  when: "'batch' in inventory_hostname"
Run Code Online (Sandbox Code Playgroud)

请注意,在playbook运行期间,您将有几个跳过的主机.

inventory_hostname 是Ansible的"神奇"变量之一:

此外,inventory_hostname是Ansible的库存主机文件中配置的主机名的名称.当您不想依赖于发现的主机名ansible_hostname或出于其他神秘原因时,这可能很有用.如果您有一个很长的FQDN,则inventory_hostname_short还包含直到第一个句点的部分,而不包含其余的域.

来源:Ansible Docs - 魔术变量以及如何访问其他主机的信息