1

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\"}`
rocku
  • 141
  • 1
  • 5

1 Answers1

2

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 }}"
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
  • Thanks, works perfectly. For completeness, I've settled on a version using `loop: "{{ users|zip(users|map('extract', users_def)|list)|list }}"` instead of `with_together`. – rocku Jan 27 '21 at 20:21