Need help merging two dict together

Viewed 33

I have these vars:

vars:
  server:
    results:
       name: instance_titi
        type: lin
       name: instance_toto
        type: win
  password:
     stdout: Titi
      rc: 0
     stdout: Toto
      rc: 0

And I want a variable to contain:

[
  {
    "name": "instance_titi",
    "type": "lin",
    "stdout": "Titi",
    "rc": 0
  }
],
[ 
  {
    "name": "instance_toto",
    "type": "win",
    "stdout": "Toto",
    "rc": 0
  }
]

I'm sure my indexes will be correctly aligned with one another, I just need to stuff one inside the other.

I get kind of close using zip:

- name: Add password for instances in server list
  set_fact:
     looped: "{{ server.results | zip(password) }}"

Debug gives me:

"msg": [
    [
        {
            "name": "instance_titi",
            "type": "lin"
        },
        {
            "rc": 0,
            "stdout": "Titi"
        }
    ],
    [
        {
            "name": "instance_toto",
            "type": "win"
        },
        {
            "rc": 0,
            "stdout": "Toto"
        }
    ]
]

Here I'm stuck.

1 Answers

if you want to avoid loop and need it in a single line, you can have a look at what I have written:

- hosts: localhost
  vars:
    server:
      results:
       - name: instance_titi
         type: lin
       - name: instance_toto
         type: win
    password:
     - stdout: Titi
       rc: 0
     - stdout: Toto
       rc: 0
  tasks:
  - debug:
      msg: |
   {{ server.results
       | zip(password)
       | map('map','dict2items')
       | map('flatten')
       | map('list')
       | map('items2dict') | list
   }}

This gives exactly what you want:

ok: [localhost] =>
  msg:
  - name: instance_titi
    rc: 0
    stdout: Titi
    type: lin
  - name: instance_toto
    rc: 0
    stdout: Toto
    type: win

Lemme know if you need an explanation of what I did. cheers!

Related