在Ansible中,可以使用when
条件语句来检查inventory_hostname
是否在列表中。下面是一个示例代码:
- name: Check if inventory_hostname is in the list
hosts: all
gather_facts: false
tasks:
- name: Define the list
set_fact:
my_list: ["host1", "host2", "host3"]
- name: Check if inventory_hostname is in the list
debug:
msg: "inventory_hostname is in the list"
when: inventory_hostname in my_list
- name: Do something if inventory_hostname is not in the list
debug:
msg: "inventory_hostname is not in the list"
when: inventory_hostname not in my_list
在上面的示例中,我们首先使用set_fact
模块定义了一个名为my_list
的变量,其中包含了一个字符串列表。然后,我们使用when
条件语句来检查inventory_hostname
是否在my_list
中。如果是,就输出inventory_hostname is in the list
,如果不是,就输出inventory_hostname is not in the list
。
请注意,inventory_hostname
是Ansible的内置变量,它代表当前主机的名称。