仅当主机名包含字符串时运行 Ansible 任务 [英] Run an Ansible task only when the hostname contains a string
问题描述
我在一个角色中有多个任务,如下所示.我不想创建另一个 yml
文件来处理这个任务.我已经有一个用于 web 服务器的包含,但是我们的几个 Perl 服务器需要安装一些 web 包.
I have multiple tasks in a role as follows. I do not want to create another yml
file to handle this task. I already have an include for the web servers, but a couple of our Perl servers require some web packages to be installed.
- 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">
主机清单文件
[webs]
web01
web02
web03
[perl]
perl01
perl02
perl03
perl-batch01
perl-batch02
推荐答案
下面应该可以解决问题:
Below should do the trick:
- name: Install PHP Modules
command: <command>
with_dict: php_modules
when: "'batch' in inventory_hostname"
请注意,在 playbook 运行期间,您会跳过几个主机.
Note you'll have a couple of skipped hosts during playbook run.
inventory_hostname
是 Ansible 的神奇"变量之一:
inventory_hostname
is one of Ansible's "magic" variables:
此外,inventory_hostname 是主机名的名称,如在 Ansible 的清单主机文件中配置.这可以用于当您不想依赖发现的主机名时ansible_hostname 或其他神秘原因.如果你有很长的FQDN,inventory_hostname_short 也包含直到第一个的部分期间,没有域的其余部分.
Additionally, inventory_hostname is the name of the hostname as configured in Ansible’s inventory host file. This can be useful for when you don’t want to rely on the discovered hostname ansible_hostname or for other mysterious reasons. If you have a long FQDN, inventory_hostname_short also contains the part up to the first period, without the rest of the domain.
来源:Ansible 文档 - 魔术变量以及如何访问其他主机的信息
这篇关于仅当主机名包含字符串时运行 Ansible 任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!