将PyATS Ansible playbook 输出保存到一个json文件:
- name: Export variable to file
copy:
content: "{{ output }}"
dest: "report.json"
Json内容如下:
{
"results": [
{
"structured": {
"interfaces": {
"Port-channel11": {
"ipv4": {
"neighbors": {
"1.1.0.1": {
"ip": "1.1.0.1",
"link_layer_address": "0000.0000.00ca"
}
}
}
},
"GigabitEthernet1": {
"ipv4": {
"neighbors": {
"1.1.1.2": {
"ip": "1.1.1.2",
"link_layer_address": "0000.0000.00cb"
},
"1.1.1.3": {
"ip": "1.1.1.3",
"link_layer_address": "0000.0000.00cc"
}
}
}
}
}
},
"item": {
"key": "vrf1",
"value": {
"route_distinguisher": "1:1",
"interfaces": [
"GigabitEthernet1",
"Port-channel11"
]
}
},
"ansible_loop_var": "item"
},
{
"structured": {
"interfaces": {
"Port-channel2": {
"ipv4": {
"neighbors": {
"2.2.2.200": {
"ip": "2.2.2.200",
"link_layer_address": "0000.0000.00dd"
}
}
}
}
}
},
"item": {
"key": "vrf2",
"value": {
"route_distinguisher": "2:2",
"interfaces": [
"Port-channel2"
]
}
},
"ansible_loop_var": "item"
}
],
"skipped": false,
"msg": "All items completed",
"changed": false
}
我想从这个json文件创建一个包含以下数据的csv文件:
{{ ansible_host/inventory_host }},vrf1,Port-channel11,1.1.0.1,0000.0000.00ca
{{ ansible_host/inventory_host }},vrf1,GigabitEthernet1,1.1.1.2,0000.0000.00cb
{{ ansible_host/inventory_host }},vrf1,GigabitEthernet1,1.1.1.3,0000.0000.00cc
{{ ansible_host/inventory_host }},vrf2,Port-channel2,2.2.2.200,0000.0000.00dd
我能联系到的最近的是:
- name: Set vrflength variable
set_fact:
vrflength: "{{ output.results | length }}"
- name: Set vrfmaxindex variable
set_fact:
vrfmaxindex: "{{ (vrflength | int) - 1 }}"
- name: Create file
lineinfile:
insertafter: EOF
dest: "report1.csv"
line: "{{ inventory_hostname }},{{ output.results[ item | int ].item.key }},{{ output.results[ item | int ].structured.interfaces }}"
with_sequence: start=0 end="{{ vrfmaxindex }}"
`device1,vrf1,{"Port-channel11":{"ipv4":{"neighbors":{"1.1.0.1":{"ip":"1.1.0.1","link_layer_address":"0000.0000.00ca"}}}},"GigabitEthernet1":{"ipv4":{"neighbors":{"1.1.1.2":{"ip":"1.1.1.2","link_layer_address":"0000.0000.00cb"},"1.1.1.3":{"ip":"1.1.1.3","link_layer_address":"0000.0000.00cc"}}}}}
device1,vrf2,{"Port-channel2":{"ipv4":{"neighbors":{"2.2.2.200":{"ip":"2.2.2.200","link_layer_address":"0000.0000.00dd"}}}}}`
我不知道如何构建所需的嵌套循环(对于每个VRF,对于每个接口,对于每个邻居,在独立的CSV行上打印设备名称、VRF名称、邻居IP和MAC).
会非常感谢任何人的帮助.