在Ansible中,通过使用with_items将一个列表迭代到一个任务中。然而,当这个列表中包含子列表时,在滚动访问时可能会遇到一些问题。
下面是解决该问题的示例代码:
- name: example of scrolling through a list with a sublist
hosts: localhost
gather_facts: no
vars:
list_with_sublist:
- [
{"fruit": "apple", "color": "green"},
{"fruit": "banana", "color": "yellow"}
]
- [
{"fruit": "orange", "color": "orange"},
{"fruit": "grape", "color": "purple"}
]
tasks:
- name: loop through the list with a sublist
debug:
msg: "{{ item.0.fruit }} has color {{ item.0.color }}"
with_subelements:
- "{{ list_with_sublist }}"
- "{{ item }}"
loop_control:
label: "{{ item.0.fruit }}"
在这个示例代码中,我们定义了一个名为list_with_sublist的变量,其中包含两个子列表。我们使用with_subelements循环遍历整个列表,并打印出每个水果的名称和颜色。在loop_control中,我们使用水果名称作为标签,以便在发生故障时更容易识别故障项。
通过使用with_subelements代替with_items,我们可以成功地滚动访问包含子列表的列表。