Kassav'
Kassav'

Reputation: 1150

Ansible double loop

I have a data list in an yml file. I would like to extract data, using a double loop, like we use to do. This is an example of my list

[a,b,c] vm1: -a -b vm2: -a -c vm3: -b

This is for a generic deployment purpose. I need to loop the list, and for each element, get the list of the vm that need to be installed in. For example

a > vm1 vm2 

b > vm1 vm3

 c > vm2

I tried with_nested but it doesn't help. Any idea to deal with that?

Upvotes: 0

Views: 506

Answers (1)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68269

This question is very similar to this one.

Here's modified JMESPath:

---
- hosts: localhost
  gather_facts: no
  vars:
    mylist: [a,b,c]
    myvms:
      vm1:
        - a
        - b
      vm2:
        - a
        - c
      vm3:
        - b
  tasks:
    - debug:
        msg: "{{ item }} > {{ list_with_keys | json_query(qry) | join(',') }}"
      vars:
        list_with_keys: "{{ myvms | dictsort | to_json | from_json }}"
        qry: "[?contains([1],`{{ item }}`)][0]"
      with_items: "{{ mylist }}"

result:

ok: [localhost] => (item=a) => {
    "changed": false,
    "item": "a",
    "msg": "a > vm1,vm2"
}
ok: [localhost] => (item=b) => {
    "changed": false,
    "item": "b",
    "msg": "b > vm1,vm3"
}
ok: [localhost] => (item=c) => {
    "changed": false,
    "item": "c",
    "msg": "c > vm2"
}

Upvotes: 2

Related Questions