问题描述
我在剧本中使用 set_fact 来使用 regex_findall() 收集数据.我用正则表达式拉出两组,最终结果成为列表列表.
I am using a set_fact in a playbook to gather data using a regex_findall(). I'm pulling out two groups with the regex and the ending result becomes a list of lists.
set_fact: nestedList="{{ myOutput.stdout[0] | regex_findall('(.*?)\n markerText(.*)')}}"
列表的示例转储如下所示:
A example dump of the list looks like:
[[a,b],[c,d],[e,f],[g,h]]
我需要遍历父列表,取每个子列表的两个部分并一起使用.我尝试了 with_items 和 with_nested 但没有得到我正在寻找的结果.
I need to iterate through the parent list, and take the two parts of each sub-list and use them together. I tried with_items, and with_nested but do not get the results I'm looking for.
使用上面的示例,在一次循环中,我需要使用a"和b".例如 item.0 = 'a' 和 item.1 = 'b'.在下一个循环中,item.0 = 'c' 和 item.1 = 'd'.
Using the example above, in one loop pass I need to work with 'a' and 'b'. An example could be item.0 = 'a' and item.1 = 'b'. On the next loop pass, item.0 = 'c' and item.1 = 'd'.
当它是这样的列表时,我似乎无法正确理解.如果我采用上面的列表并输出它,项目"将遍历所有子列表中的每个项目.
I can't seem to get it correct when it is a list of lists like that.If I take the list above and just output it, the 'item' iterates through every item in all of the sub-lists.
- debug:
msg: "{{ item }}"
with_items: "{{ nestedList }}"
结果如下:
a
b
c
d
e
f
g
h
如何遍历父列表,并使用子列表中的项目?
How can I iterate through the parent list, and use the items in the sub-lists?
推荐答案
您想使用 with_list
而不是 with_items
.
You want to use with_list
instead of with_items
.
with_items
强制扁平化嵌套列表,而 with_list
按原样提供参数.
with_items
forcefully flattens nested lists, while with_list
feeds argument as is.
---
- hosts: localhost
gather_facts: no
vars:
nested_list: [[a,b],[c,d],[e,f],[g,h]]
tasks:
- debug: msg="{{ item[0] }} {{ item[1] }}"
with_list: "{{ nested_list }}"
这篇关于Ansible 列表列表 - 扁平化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!