0

The requirement was to get a dynamic set of files from a directory based on a dictionary. I've implemented it with concept mentioned in: Nested loop with a list and a dictionary

    - name: color print - hardcoded
      debug:
        msg:
        - "{{ item[0] }} - {{ item[1] }}"
      with_nested:
        - [ 'red', 'green' ]
        - [ 'grapes', 'apple', 'chilli' ]

The above works correctly

But if I change the 2nd list to a dynamically generated list from the 1st list, it is not working. it throws 'item' is undefined" error

Below is a rough implementation I'm trying and getting the error

    - name: color print - dynamic
      debug:
        msg:
        - "Copy from directory: {{ item[0] }} to {{ item[1] }}"
      with_nested:
        - [ 'red', 'green' ]
        - "{{colored_fuit| dictsort}}"
      vars:
        - color: "{{ item[0] }}"
        - colored_fuit:
            fruit1: "{{color}}_grapes"
            fruit2: "{{color}}_apple"
            fruit3: "{{color}}_chilli"

Why is it so? It is because the variable is not generated in case of 2nd list?

2
  • 2
    you have a self-referential set of vars:, where you are trying to define colored_fruit: but also with_nested: over them; it seems you need to move the red, green into a separate step and generate colored_fruit: in that step Commented Mar 10, 2022 at 21:10
  • The question doesn't make sense. You can simply concatenate the items "{{ item.0 }} to {{ item.0 }}_{{ item.1 }}". I deleted the answer because I didn't know what you want. You commented: filter conditions from 1st list. What is the condition? You commented: nesting needs to ensure the specific set only. What is the expected specific set? I asked you to edit the question and make it minimal reproducible example. Commented Mar 11, 2022 at 16:36

1 Answer 1

1

use this piece of code to resolve your problem:

- name: color print - dynamic
  debug:
    msg: "Copy from directory: {{ item.0 }} to {{ item.0 }}_{{ item.1.1 }}"
  loop: "{{ color | product(colored_fuit|dictsort)|list }}"
  vars:
    color: [ 'red', 'green' ]
    colored_fuit:
        fruit1: "grapes"
        fruit2: "apple"
        fruit3: "chilli"
Sign up to request clarification or add additional context in comments.

3 Comments

this is a great idea thanks for that. But my 2nd list is dependent on the 1st.
i dont understant by "dependent"... the result is a product of 2 lists, same result you want...
Unfortunately my 2nd list is dependent on the 1st list

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.