How to loop over list while pulling data from different list?

Hello,

I’m encountering a loop issue that I’m unsure how to solve cleanly. Suppose I have a list of dictionaries:

list_of_dict:

  • { key: d01, value: ‘v1’ }
  • { key: d02, value: ‘v2’ }
  • { key: d99, value: ‘v99’ }

Somewhere else I have another list whose elements are a subset of the keys in list_of_dict:

list01:

  • d01

  • d07

  • d33

There are many other lists like list01 with a similar structure. How do I loop through list01 while echoing the corresponding ‘value’ from list_of_dict?

Jack,

Interesting dilemma, I believe a little bit of Jinja2 would help you out. Try running this:

  • name: Test playbook
    hosts: localhost
    vars:

list01:

  • d01
  • d03
  • d04
  • d06
    list02:
  • d02
  • d05
  • d06
    list_of_dict:
  • { key: d01, value: ‘v1’ }
  • { key: d02, value: ‘v2’ }
  • { key: d03, value: ‘v3’ }
  • { key: d04, value: ‘v4’ }
  • { key: d05, value: ‘v5’ }
  • { key: d06, value: ‘v6’ }
    tasks:
  • debug: msg=“{% for each in list_of_dict %}{{ each.value if each.key == item else ‘’ }}{% endfor %}”

with_items:

  • “{{list01}}”
  • “{{list02}}”

This seems easily scalable and works like a charm!

\Chip

have you tried:

  tasks:
    - debug: msg="{{ llist_of_dict[item] }}"
      with_items:"{{list01|union(list02)}}"

That is exactly what I was looking for! Thanks.

the above code got this error message, how to fix it ?

TASK: [debug msg=“{{ list_of_dict[item] }}”] **********************************
fatal: [localhost] => One or more undefined variables: ‘list object’ has no attribute ‘d01’

FATAL: all hosts have already failed – aborting

Hi Clay,

My understanding is that list_of_dict, being a list, should be indexed by integer and not by a string such as ‘d01’. Try the code in Chip’s response; it runs successfully.