在Ansible中,条件循环遍历with_items可以使用when关键字来实现。下面是一个示例代码:
- name: Conditional loop with_items
hosts: localhost
gather_facts: false
vars:
fruit_list:
- apple
- banana
- orange
tasks:
- name: Print fruits that start with 'a'
debug:
msg: "{{ item }}"
with_items: "{{ fruit_list }}"
when: item.startswith('a')
在上面的示例中,我们定义了一个名为fruit_list的变量,其中包含了一些水果。然后,在debug任务中使用with_items循环遍历fruit_list变量的每一个元素。
使用when关键字,我们设置了一个条件,只有当item的值以字母'a'开头时,debug任务才会执行并打印出该水果的名称。
运行上述Playbook后,只有以字母'a'开头的水果(如apple)会被打印出来。