3

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]]

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.

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

The result from this looks like:

a
b
c
d
e
f
g
h

How can I iterate through the parent list, and use the items in the sub-lists?

hiddenicon
  • 551
  • 2
  • 11
  • 23

1 Answers1

6

You want to use with_list instead of with_items.

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 }}"
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • I had read the issues list on [Github](http://github.com) about `with_items` doing flattening on a list of lists, however I never saw any mention of `with_list`. Is there documentation for it? I only see a `with_dict` and the others I've mentioned already. I will try your code today. – hiddenicon May 11 '17 at 12:22
  • I don't see any documentation for this. You can check all available lookups under [plugins/lookup](https://github.com/ansible/ansible/tree/stable-2.2/lib/ansible/plugins/lookup) directory. Every plugin can be used as `with_` construction. – Konstantin Suvorov May 11 '17 at 12:34
  • Yes, no documentation. I figured there would be considering it's an Ansible core module. `with_list` works perfect. – hiddenicon May 11 '17 at 13:45
  • At least nowadays there is documentation for this in the [Ansible 2.5 Porting Guide](https://docs.ansible.com/ansible/latest/porting_guides/porting_guide_2.5.html) – Dirk Jablonski Nov 07 '18 at 20:17