0

I Have 2 dictionary:

- Test1:
   1: pass
   2: fail
   3: pass

- Test2:
   1.1.1.1: val1
   2.2.2.2: val2
   3.3.3.3: val3

Condition is when Test1.value contians fail

- name: test
  debug:
    msg: "{{item.1.value}} {{item.1.key}} {{item.0.key}} {{item.0.value}}"
  with_together:
    - "{{Test1}}"
    - "{{Test2}}"
  when: item.0.value == "fail"

This is not working as expected unable to get both key and value of 2 dict in one loop

Tan512
  • 15
  • 6

2 Answers2

1

In when statement you must to use item.0 or item.1 to evaluate the condition. And I recommend you use a list in with_together loop and if you are using a variable you have to use braces {{ variable }} .

Try as below:

    - name: test
      debug:
        msg: "{{item.1 }}"
      with_together:
        - "{{ Test1.values() | list }}"
        - "{{ Test2.values() | list }}"
      when: item.0 == "fail"

You'll get

TASK [test] *******************************************************************************************************************************************************************************************************
skipping: [127.0.0.1] => (item=['pass', 'val1'])
ok: [127.0.0.1] => (item=['fail', 'val2']) => {
    "msg": "val2"
}
skipping: [127.0.0.1] => (item=['pass', 'val3'])
gary lopez
  • 1,823
  • 7
  • 15
  • 2
    Be extra carefull implementing this as dict key order in yaml/ansible/python cannot be relied upon. You might very easily end up with de-synchronized items. If you are in controle of the input data, you should transform it to lists directly, or to dicts that can easilly refer one to an other (e.g. with an `id` refered in the second you can find in the first....) – Zeitounator Aug 17 '21 at 14:40
  • I need both key as well as values... if use Test1.values, key value I won't have inside loop – Tan512 Aug 17 '21 at 15:15
  • You are not showing a single example using the key anywhere in your example. – Zeitounator Aug 17 '21 at 17:37
  • Added that to question, I tried this with_nested(using item[0], item [1] and so on...) but loops run many iteration then expected Any other approach... One is Jinja 2 template any other better way to do this .. – Tan512 Aug 17 '21 at 18:30
0

I achieved this by :
converting dict to list using filter -> |list
since both dict of same size I was able to get data of both dict in single loop:

- name: test
  debug:
    msg: "{{item.0}} {{item.1}} {{item.2}} {{item.3}}"
  with_together:
    - "{{ Test1.values() | list }}"
    - "{{ Test2.values() | list }}"
    - "{{ Test1.keys() | list }}"
    - "{{ Test2.keys() | list }}"
  when: item.0 == "fail"
Tan512
  • 15
  • 6