On Thu, 17 Aug 2023 13:11:25 -0400
Brian Coca <bc...@redhat.com> wrote:

> see map/select/reject filters .. they are actually loops and normally
> much simpler than using jinja command syntax ( {% %} ).

Unfortunately, some filters are not *map* friendly. For example, the
filter *product*

  list1|product(list2) .............. works fine
  list1|zip(list2)|map('product') ... does not work


Details: Given the list

  l1:
    - dir: /tmp/test/d1
      sub_dir: [a, b]
    - dir: /tmp/test/d2
      sub_dir: [a, b, c]

the goal is to create the list of products

  l2:
  - /tmp/test/d1/a
  - /tmp/test/d1/b
  - /tmp/test/d2/a
  - /tmp/test/d2/b
  - /tmp/test/d2/c

The iteration (the filter *subelements* not used
to demonstrate the functionality of *product*)

    - debug:
        msg: "{{ [item.0]|product(item.1) }}"
      loop: "{{ dirs|zip(sdirs) }}"
      vars:
        dirs: "{{ l1|map(attribute='dir') }}"
        sdirs: "{{ l1|map(attribute='sub_dir') }}"

works as expected. Gives (abridged)

  msg:
  - - /tmp/test/d1
    - a
  - - /tmp/test/d1
    - b

  msg:
  - - /tmp/test/d2
    - a
  - - /tmp/test/d2
    - b
  - - /tmp/test/d2
    - c

But, the filter *product* doesn't work with *map*

  dirs: "{{ l1|map(attribute='dir') }}"
  sdirs: "{{ l1|map(attribute='sub_dir') }}"
  l3: "{{ dirs|zip(sdirs)|map('product') }}"

gives

  l3:
  - - - /tmp/test/d1
    - - - a
        - b
  - - - /tmp/test/d2
    - - - a
        - b
        - c

This leaves you with Jinja if you want to avoid the loops in tasks

  l3: |
    {% filter from_yaml %}
    {% for i in l1 %}
    {% for s in i.sub_dir %}
    - {{ i.dir }}/{{ s }}
    {% endfor %}
    {% endfor %}
    {% endfilter %}

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20230817202944.3f3512c8%40gmail.com.

Attachment: pgpzQmp4GVXoP.pgp
Description: OpenPGP digital signature

Reply via email to