João Amaro
João Amaro

Reputation: 496

How to create a loop inside a loop in ansible and export variables?

So basically, I have these two dictionaries:

dict_1:
  - name: one
  - name: two

dict_2:
  - identifier: one
    type: typeA
  - identifier: two
    type: typeB

I need to iterate over both and "export" the vars to process.yml. This is what I am doing right now but not working properly:

#main.yml

- name:
  include_tasks: process.yml
  loop: "{{ dict_1 | flatten }}"
  loop_control:
    loop_var: entity
      loop: "{{ dict_2 | selectattr('identifier', 'equalto', entity) | map(attribute='type') | flatten }}"
        loop_control:
          loop_var: type


#process.yml

- name: Print variables
  debug:
    msg: "{{ entity }}_{{ type }}"

What I wanted to see after this was:

one_typeA
two_typeB

How can I get this result from the loop?

Upvotes: 0

Views: 161

Answers (1)

ebrewer
ebrewer

Reputation: 484

I think your original solution is close, just a little more complicated than it needs to be. Please note that this solution assumes that there will not be more than one item from dict2 that you will be finding using the value from dict1, it's just the order that you can't predict.

- debug: msg="{{ item.name }}_{{ dict_2 | selectattr('identifier', 'equalto', item.name) | map(attribute='type') | list | join() }}"
  with_items: "{{ dict_1 }}"

If you CAN control order of the lists, this gets even easier.

- debug: msg="{{ item.0.name }}_{{ item.1.type }}"
  with_together:
    - "{{ dict_1 }}"
    - "{{ dict_2 }}"

And if you can control the order and the content, and you want to have every possible combination of the two lists, you can do this:

- debug: msg="{{ item.0.name }}_{{ item.1.type }}"
  with_cartesian:
    - "{{ dict_1 }}"
    - "{{ dict_2 }}"

Upvotes: 1

Related Questions