How to concatenate two lists of dictonaries in Ansible

Viewed 610

I have two list of dicts:

dev_users:
  - name: cs3141
    key:
      cs513e_key1.pub
      cs513e_key2.pub
  - name: ab1234
    key:
      ab1234.pub
  - name: cd5678
    key:
      ab1234.pub

and

sys_admin_users:
  - name: xy3141
    key:
      xy3141.pub
  - name: cd1234
    key:
      cd1234.pub
  - name: ef5678
    key:
      ef5678.pub

When I try to concatenate them:

- set_fact: users= "{{ dev_users + sys_admin_users }}"

I get this error:

ERROR! failed to combine variables, expected dicts but got a 'dict' and a 'AnsibleSequence': 
{}
[{"set_fact": "users= \"{{ dev_users + sys_admin_users }}\""}]

How can I concatenate these two lists?

2 Answers

The problem was that I was trying to concatenate the two list in the variables section, as opposed to the task section. Tadeboro in #ansible gave me this code that worked:

---
- hosts: localhost
  gather_facts: false

  vars:
    dev_users:
      - name: cs3141
        key:
          cs513e_key1.pub
          cs513e_key2.pub
      - name: ab1234
        key:
          ab1234.pub
      - name: cd5678
        key:
          ab1234.pub
    sys_admin_users:
      - name: xy3141
        key:
          xy3141.pub
      - name: cd1234
        key:
          cd1234.pub
      - name: ef5678
        key:
          ef5678.pub

  tasks:
    - name: Test
      set_fact:
        users: "{{ dev_users + sys_admin_users }}"

This command works fine: ansible-playbook -v x.yaml

Here is another solution, that iteratively concatenates a list of list. I like it better, because it is more general. It only works in more recent versions of ansible, because there was a bug in version 2.5 which took some time to fix.

---
# ansible-playbook -v manyx.yaml

- hosts: localhost
  gather_facts: false

  vars:
    dev_users:
      - name: cs3141
        key:
          cs513e_key1.pub
          cs513e_key2.pub
      - name: ab1234
        key:
          ab1234.pub
      - name: cd5678
        key:
          ab1234.pub
    sys_admin_users:
      - name: xy3141
        key:
          xy3141.pub
      - name: cd1234
        key:
          cd1234.pub
      - name: ef5678
        key:
          ef5678.pub

    other_users:
      - name: fe9876
        key:
          fe9876.pub

    list_of_users_list:
      - "{{ dev_users }}"
      - "{{ sys_admin_users }}"
      - "{{ other_users }}"

    all_users: []

  tasks:

    - name: Test
      set_fact:
        all_users: "{{ item + all_users }}"
      loop: "{{ list_of_users_list }}"

    - name: print all_users
      debug:
        msg: "{{ item }}"
      loop: "{{ all_users }}"
Related