Ansible列表清单 - 展平

时间:2017-05-10 20:25:09

标签: ansible

我在playbook中使用set_fact来使用regex_findall()收集数据。我正在用正则表达式取出两组,结果结果变成一个列表列表。

set_fact: nestedList="{{ myOutput.stdout[0] | regex_findall('(.*?)\n markerText(.*)')}}"

列表的示例转储如下:

[[a,b],[c,d],[e,f],[g,h]]

我需要遍历父列表,并获取每个子列表的两个部分并一起使用它们。我尝试了with_items和with_nested,但没有得到我正在寻找的结果。

使用上面的例子,在一个循环传递中,我需要使用'a'和'b'。一个例子可能是item.0 ='a'和item.1 ='b'。在下一个循环传递中,item.0 ='c'和item.1 ='d'。

当它是像这样的列表列表时,我似乎无法理解它。 如果我拿上面的列表并输出它,'item'会遍历所有子列表中的每个项目。

- debug:
    msg: "{{ item }}"
    with_items: "{{ nestedList }}"

这样做的结果如下:

a
b
c
d
e
f
g
h

如何遍历父列表,并使用子列表中的项目?

1 个答案:

答案 0 :(得分:5)

您想使用with_list代替with_items

with_items强制展平嵌套列表,而with_list按原样反馈参数。

---
- 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 }}"