I am trying to merge the following 2 arrays using Ansible:
TASK [Show var1] ****************************************************************************
ok: [localhost] => {
"var1": [
{
"id": "133"
},
{
"id": "149"
},
{
"id": "188"
}
]
}
and
TASK [Show var2] ****************************************************************************
ok: [localhost] => {
"var2": [
{
"name": "two"
},
{
"name": "one"
},
{
"name": "three"
}
]
}
The result should be:
"var1": [
{
"id": "133",
"name": "two"
},
{
"id": "149",
"name": "one"
},
{
"id": "188",
"name": "three"
}
]
My efforts for merging so far...returned only the last pair. How can I get the whole arrays merged?
Here's one possible solution; we use set_fact
and the combine
filter, looping over var1|zip(var2)
:
- hosts: localhost
gather_facts: false
vars:
var1:
- id: 133
- id: 149
- id: 188
var2:
- name: two
- name: one
- name: three
tasks:
- set_fact:
var3: "{{ var3 + [item[0]|combine(item[1])] }}"
vars:
var3: []
loop: "{{ var1|zip(var2)|list }}"
- debug:
msg: "{{ var3 }}"
(See the docs for information about set_fact and combine).
This will output:
PLAY [localhost] *****************************************************************************************************************************************************************************
TASK [set_fact] ******************************************************************************************************************************************************************************
ok: [localhost] => (item=[{'id': 133}, {'name': 'two'}])
ok: [localhost] => (item=[{'id': 149}, {'name': 'one'}])
ok: [localhost] => (item=[{'id': 188}, {'name': 'three'}])
TASK [debug] *********************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": [
{
"id": 133,
"name": "two"
},
{
"id": 149,
"name": "one"
},
{
"id": 188,
"name": "three"
}
]
}
PLAY RECAP ***********************************************************************************************************************************************************************************
localhost : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With