在Ansible中,可以使用when
条件语句来跳过循环,当列表未定义时执行跳过操作。
下面是一个示例代码:
- name: Loop through a list (if defined)
hosts: localhost
gather_facts: false
vars:
my_list: # 定义一个空列表
# my_list: [item1, item2, item3] # 定义一个非空列表
tasks:
- name: Check if list is defined
debug:
msg: "List is defined"
when: my_list is defined
- name: Loop through list
debug:
msg: "Item: {{ item }}"
loop: "{{ my_list | default([]) }}"
when: my_list is defined
在上面的示例中,my_list
变量被定义为一个空列表。如果你将注释取消掉并定义一个非空列表,代码也会正常工作。
运行以上代码,将输出以下结果:
PLAY [Loop through a list (if defined)] *****************************************************************************************
TASK [Check if list is defined] ************************************************************************************************
ok: [localhost] => {
"msg": "List is defined"
}
TASK [Loop through list] *******************************************************************************************************
skipping: [localhost]
PLAY RECAP *********************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=1 rescued=0 ignored=0
从输出结果可以看到,当列表未定义时,循环被跳过。