ansible/yaml : get value as string from dict

Viewed 195

I've got some variables I need to loop on :

mariadb_grants:
  "*.*":
    - user1: "ALL, SELECT"
    - user2: "ALL"
  "toto":
    - user1: "ALL"
    - user23: "GRANT"

Of course, userX is not defined in advance, I can have user1233 etc. I can loop through the dict fairly easily with this code :

  tasks:
    - debug:
        msg: "Key is {{ item }} and value is {{ mariadb_grants[item] }}"
      loop: "{{ mariadb_grants.keys() }}"

I got this :

ok: [localhost] => (item=*.*) => {}

MSG:

Key is *.* and value is [{'user1': 'ALL, SELECT'}, {'user2': 'ALL'}]
ok: [localhost] => (item=toto) => {}

MSG:

Key is toto and value is [{'user1': 'ALL'}, {'user23': 'GRANT'}]

The thing I'm trying to do, is just get the key and values of userx, basically I want this :

My key is *.* I'm user1 and my value is "ALL, SELECT"
My key is *.* I'm user2 and my value is ALL
My key is "toto" I'm user1 and my value is ALL
[...]

It seems I can't loop through my subelements :(

1 Answers

It's possible to use dict2items inside the with_subelements loop, e.g.

  - debug:
      msg: 'My key is {{ item.0.key }} I am {{ key }} and my value is "{{ val }}"'
    with_subelements:
      - "{{ mariadb_grants|dict2items }}"
      - value
    vars:
      key: "{{ item.1.keys()|first }}"
      val: "{{ item.1.values()|first }}"

gives

  msg: My key is *.* I am user1 and my value is "ALL, SELECT"
  msg: My key is *.* I am user2 and my value is "ALL"
  msg: My key is toto I am user1 and my value is "ALL"
  msg: My key is toto I am user23 and my value is "GRANT"
Related