How to iterate a list of dictionaries where the dictionary names are contained in a list in Ansible ?

Hi team,

Below is the scenario and snippet of the files.

~/ansible/group_vars/all/main.yml

Check out loop_control
http://docs.ansible.com/ansible/latest/playbooks_loops.html#loop-control

Hi Kai Stian Olstad,

Thanks for the reply.

Yes I did try the loop_control. The problem with loop_control is when it iterates over the list_of_dict and takes each item of it, it considers the item as “String” and not the dict to iterate over, so I get the error saying with_dict expects a dict on the task of iterating over the dict.

Here are the playbooks and ansible output.

test.yml

Yes I did try the loop_control. The problem with loop_control is when it
iterates over the list_of_dict and takes each item of it, it considers the
item as "String" and not the dict to iterate over, so I get the error
saying with_dict expects a dict on the task of iterating over the dict.

Since you variable look like this

list_of_dict:
  - dict1_test
  - dict2_test
dict1_test:
      var1: test1
      var2: test2
dict2_test:
      var3: test3
      var4: test4

Your list_of_dict is a list of string literally called dict1_test and dict2_test.
If you like to have the content you need to specify them as variables.

list_of_dict:
  - '{{ dict1_test }}'
  - '{{ dict2_test }}'

With this list_of_dict will contain the content of dict1_test and dict2_test and not just the names.

You can use both, the only difference is how your something.yml look like.

Here are the playbooks and ansible output.

*test.yml*

---
- hosts: localhost
  tasks:
     - name: print
       include: "something.yml listDict={{listDict}}"

Remove the listDict={{listDict}}, it shouldn't be there
   include: something.yml

       with_items: "{{ list_of_dict }}"
       loop_control:
         loop_var: listDict

*something.yml*
---
- debug: var=listDict

- name: print the task
  debug: msg="{{ item.key }} is key,{{ item.value }} is value"
  with_dict: listDict

Here you feed the with_dict the literally string listDict and not it content, to do that you need to say its a varaiable
   with_dict: '{{ listDict }}'

So it you would like to use
list_of_dict:
  - dict1_test
  - dict2_test

This something.yml will work
   - debug: var=listDict

   - name: print the task
     debug: msg="{{ item.key }} is key,{{ item.value }} is value"
     with_dict: '{{ vars[listDict] }}'

If you would like to use
list_of_dict:
  - '{{ dict1_test }}'
  - '{{ dict2_test }}'

This something.yml will work
   - debug: var=listDict

   - name: print the task
     debug: msg="{{ item.key }} is key,{{ item.value }} is value"
     with_dict: '{{ listDict }}'