I am getting the v_data from 2 different hosts: HOST-1, HOST-2.
TASK [Print v_data] **************************************************************************************************
ok: [HOST-1] => {
"v_data": [
{
"vrf": "vrf-11",
"ip": "10.10.10.1",
"policy": "RP-11",
"max-pref": "15",
"thresh": "15%"
},
{
"vrf": "vrf-12",
"ip": "10.10.10.2",
"policy": "RP-12",
"max-pref": "15",
"thresh": "15%"
}
]
}
ok: [HOST-2] => {
"v_data": [
{
"vrf": "vrf-21",
"ip": "20.20.20.1",
"policy": "RP-21",
"max-pref": "15",
"thresh": "15%"
},
{
"vrf": "vrf-22",
"ip": "20.20.20.2",
"policy": "RP-22",
"max-pref": "25",
"thresh": "25%"
}
]
}
I get the data into a table format if I convert it into a table (single host).
And I am doing the below to get the data into a singe json/table:
- name: Get v_data
shell: echo "{{ v_data }}"
register: v_data
loop: "{{ ansible_play_hosts }}"
vars:
vd: "{{ hostvars[item]['v_data'] }}"
- name: Create data structure
set_fact:
host_data: "{{ host_data | default([]) + [{'host': item.item, 'v_data': item.stdout | from_json }] }}"
with_items: "{{ v_data.results }}"
- name: Print data structure
debug:
var: host_data
But I want to get the data as below and hence I can convert the same to a CSV or a table as below:
{
"data": [
{
"host": "HOST-1",
"v_data": [
{
"vrf": "vrf-11",
"ip": "10.10.10.1",
"policy": "RP-11",
"max-pref": "15",
"thresh": "15%"
},
{
"vrf": "vrf-12",
"ip": "10.10.10.2",
"policy": "RP-12",
"max-pref": "15",
"thresh": "15%"
}
]
},
{
"host": "HOST-1",
"v_data": [
{
"vrf": "vrf-21",
"ip": "20.20.20.1",
"policy": "RP-21",
"max-pref": "15",
"thresh": "15%"
},
{
"vrf": "vrf-22",
"ip": "20.20.20.2",
"policy": "RP-22",
"max-pref": "25",
"thresh": "25%"
}
]
}
]
}
Even if I have hosts, HOST-1, HOST-2, .....HOST-n
,
how to represent/convert the data from each inventory_hostname
and combine/merge to a single JSON in order to further convert to a table.
not sure I can use the term combine/merge. final output should be as shown in data
and screenshot
2
Answers
In a nutshell. You can debug intermediate variables in the task to better understand the process but the different steps and corresponding variable names should be enough for the first idea.
Note: I created the following fake
inventories/demo/hosts.yml
inventory to run against your example data:Using the above, the
merge_json.yml
demo playbook:returns:
Given the inventory
and the host_vars with simplified variables v_data for testing
combines the data into a single dictionary
gives
gives
gives
Create csv files
Given the data
the play
will create the csv file