ansible - 如何在ansible中从字典中提取深度嵌套的数据
问题描述
我正在尝试从 ansible 字典中打印嵌套数据。但是,我无法弄清楚如何提取嵌套值。具体来说,在下面的数据中,我试图打印在“ipv4”下返回的两个值。目前,item.value.ipv4 的输出是下面括号中的部分:
"msg": "GigabitEthernet0/0/0,[{'address': '192.168.3.1', 'subnet': '28'}]"
我想只使用这样的值:
"msg": "GigabitEthernet0/0/0, 192.168.3.1, 28"
我无法弄清楚如何将这些嵌套数据拉出来来做到这一点。简而言之,如果这样的事情可行,那就太好了:item.value.ipv4['address']。这是怎么做到的?
tasks:
- name: get config for Cisco IOS
ios_facts:
gather_subset: all
gather_network_resources: interfaces
- name: create dictionary with ansible_net_interfaces
set_fact:
foo_value: "{{ query('dict', ansible_net_interfaces) }}"
- name: display the results of foo_value
debug:
msg: "{{ foo_value }}"
- name: display certain detalys values from foo_value
debug:
msg: "{{ item.key }},{{ item.value.ipv4 }}"
with_items: "{{ foo_value }}"
这些任务产生以下结果:
TASK [display the results of foo] **********************************************************************************************************************
ok: [192.168.3.1] => {
"msg": [
{
"key": "GigabitEthernet0/0/0",
"value": {
"bandwidth": 1000000,
"description": "This is an interface description",
"duplex": "Full",
"ipv4": [
{
"address": "192.168.3.1",
"subnet": "28"
}
],
"lineprotocol": "up",
"macaddress": "50f7.123c.b0c0",
"mediatype": "RJ45",
"mtu": 1500,
"operstatus": "up",
"type": "ISR4331-3x1GE"
}
},
{
"key": "GigabitEthernet0/0/1",
"value": {
"bandwidth": 1000000,
"description": "This is another interface description",
"duplex": "Full",
"ipv4": [
{
"address": "192.168.3.33",
"subnet": "30"
}
],
"lineprotocol": "up",
"macaddress": "50f7.123c.b0c0",
"mediatype": "RJ45",
"mtu": 1500,
"operstatus": "up",
"type": "ISR4331-3x1GE"
}
},
]
}
解决方案
ipv4
是一个字典列表。假设您只需要第一本字典,
- name: display certain detalys values from foo_value
debug:
msg: "{{ item.key }},{{ item.value.ipv4[0].address }},{{ item.value.ipv4[0].subnet }}"
when: item.value.ipv4 is defined and item.value.ipv4[0].subnet is defined and item.value.ipv4[0].address is defined
with_items: "{{ foo_value }}"
推荐阅读
- node.js - 将其他命令发送到使用 exec - nodejs 运行的 powershell 脚本中
- javascript - 从 Rich 中读取文件名:FileUpload using javascript
- python - 使用 systemd 启动 python 代码的问题
- reactjs - 太多的重新渲染 ReactJs
- javascript - 我想从 JSON Stringify 中提取某些字段,例如名称、金额和详细信息
- ruby-on-rails - 嵌套在模块内的类的Rspec未初始化常量 - Ruby on Rails
- python - K 表示算法实现
- python - 在 x 轴 matplot 上突出显示周末
- javascript - 过滤为空时忽略对象属性
- flutter - 如何使用 Flutter 在 image_picker 中包含特定数量的图像