Merging a list of dicts with another list of dicts

Hi

I have a role for managing user accounts, which accepts a list of dicts to configure those, for example:

default_users:

  • name: bob
    comment: Bob Morton
    state: present
  • name: dick
    comment: Dick Jones
    state: present
  • name: alex
    comment: Alex Murphy
    state: present

Some systems need additional accounts, for instance:

customer_users:

  • name: anne
    comment: Anne Lewis
    state: present

This is easily done with the union filter:

“{{ default_users | union(custom_users) }}”

BUT, I would like users in the second list to override the ones in the first list, so that you change existing users. So for instance I would like to merge this in:

custom_users:

  • name: alex
    comment: Alex Murphy (locked for reason X)
    password_lock: yes

So that the resulting list would look like this:

  • name: bob
    comment: Bob Morton
    state: present
  • name: dick
    comment: Dick Jones
    state: present
  • name: alex
    comment: Alex Murphy (locked for reason X)
    password_lock: yes
    state: present

So the lists of dicts need to be merged, and overwritten if the ‘name’ attribute is the same (if I express myself correctly).

union does not work here, and combine only works for individual dicts, not lists of dicts.

Before I set off to create my own filter - is there a way this could still be achieved using native ansible/jinja filters?

Thx

You might get what you need with the combine filter - not tested
see https://www.jeffgeerling.com/blog/2017/changing-deeply-nested-dict-variable-ansible-playbook as an example

HTH

Phil