diaryfolio
diaryfolio

Reputation: 625

Ansible: Nested loop with dictionary & dynamic list : 'item' is undefined" Error

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?

Upvotes: 0

Views: 231

Answers (1)

Frenchy
Frenchy

Reputation: 17007

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"

Upvotes: 1

Related Questions