How to convert a dict of key=dict pairs to a list of dicts extending each item with key in Ansible?

Viewed 43

I have a dict of user definitions (users_def) and a list of user names to actually set up (users):

users_def:
  john:
    attr1: val1
    attr2: val2
  alice:
    attr1: val1
    attr2: val2

users:
  - alice

I would like to get a list of users with all their attributes from users_def, including the username:

[
  {
     "name": "alice",
     "attr1": "val1",
     "attr2": "val2"
  }
]

How can I achieve this in Ansible?

I saw this answer to a similar question but when I try:

- set_fact:
    _users: "{{ item.value | map('combine', {'name': item.key}) | list }}"
  loop: "{{ users_def | dict2items }}"

I get this error:

failed to combine variables, expected dicts but got a 'str' and a 'dict': \n\"attr1\"\n{\"name\": \"john\"}`
1 Answers

The task below does the job

    - set_fact:
        _users: "{{ _users|default([]) +
                    [{'name': item.0}|combine(item.1)] }}"
      with_together:
        - "{{ users }}"
        - "{{ users|map('extract', users_def)|list }}"
Related