Combining list of dicts in Ansible

Viewed 206

I have 3 separate list of dicts that I'm hoping to combine together. I've tried a combination of dict and zip filters but don't seem to be able to it right.

remoteports:
  - remoteport: Gi1/0/11
  - remoteport: Gi1/0/12
  - remoteport: Gi1/0/13

shorthosts:
  - host: HOST01
  - host: HOST02
  - host: HOST03

neighbour_keys:
  - GigabitEthernet1/0/1
  - GigabitEthernet1/0/2
  - GigabitEthernet1/0/3

Expected Output

Combined:
  GigabitEthernet1/0/1:
  - host: HOST01
    remoteport: Gi1/0/11
  GigabitEthernet1/0/2:
  - host: HOST02
    remoteport: Gi1/0/12
  GigabitEthernet1/0/3:
  - host: HOST03
    remoteport: Gi1/0/13
1 Answers

For example

    - set_fact:
        combined: "{{ combined|d({})|combine({item.0: [item.1]}) }}"
      loop: "{{ neighbour_keys|zip(_hosts) }}"
      vars:
        _hosts: "{{ shorthosts|zip(remoteports)|map('combine') }}"

gives what you want

  combined:
    GigabitEthernet1/0/1:
    - host: HOST01
      remoteport: Gi1/0/11
    GigabitEthernet1/0/2:
    - host: HOST02
      remoteport: Gi1/0/12
    GigabitEthernet1/0/3:
    - host: HOST03
      remoteport: Gi1/0/13

This might be simplified if you don't insist on keeping the lists, e.g.

    - set_fact:
        combined: "{{ dict(neighbour_keys|zip(_hosts)) }}"
      vars:
        _hosts: "{{ shorthosts|zip(remoteports)|map('combine') }}"

gives

  combined:
    GigabitEthernet1/0/1:
      host: HOST01
      remoteport: Gi1/0/11
    GigabitEthernet1/0/2:
      host: HOST02
      remoteport: Gi1/0/12
    GigabitEthernet1/0/3:
      host: HOST03
      remoteport: Gi1/0/13
Related