【问题标题】:Ansible list of lists - flatteningAnsible 列表列表 - 展平
【发布时间】:2017-10-09 16:06:45
【问题描述】:

我在剧本中使用 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'。

当它是这样的列表时,我似乎无法正确理解。 如果我使用上面的列表并仅输出它,则“项目”会遍历所有子列表中的每个项目。

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

结果如下:

a
b
c
d
e
f
g
h

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

【问题讨论】:

    标签: ansible


    【解决方案1】:

    您想使用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 }}"
    

    【讨论】:

    • 我在Github 上阅读了关于with_items 对列表列表进行展平的问题列表,但是我从未看到任何提及with_list。有文档吗?我只看到with_dict 和我已经提到的其他人。我今天会试试你的代码。
    • 我没有看到任何文档。您可以检查plugins/lookup 目录下的所有可用查找。每个插件都可以作为with_<lookup_plugin_name>构造。
    • 是的,没有文档。我想会考虑它是一个 Ansible 核心模块。 with_list 完美运行。
    • 至少现在Ansible 2.5 Porting Guide中有这方面的文档
    猜你喜欢
    • 2015-10-30
    • 2012-03-19
    • 2016-06-10
    • 2016-01-26
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-06-24
    相关资源
    最近更新 更多