json - Ansible - json解析 - “未定义变量”
问题描述
环境:
- Ansible:2.10.12
- 蟒蛇:3.6.8
- Jinja2:3.0.1
给定 API 响应,我试图获取地址,但得到“未定义变量”。这是一个将 API 响应作为 var 的剧本:
---
- name: test
gather_facts: no
hosts: localhost
vars:
pool_details: {
"allow": "",
"cache_control": "no-store, no-cache, must-revalidate",
"changed": false,
"connection": "close",
"content_length": "668",
"content_security_policy": "default-src 'self' 'unsafe-inline' 'unsafe-eval' data: blob:; img-src 'self' data: http://127.4.1.1 http://127.4.2.1",
"content_type": "application/json; charset=UTF-8",
"cookies": {},
"cookies_string": "",
"date": "Tue, 24 Aug 2021 16:34:47 GMT",
"elapsed": 0,
"expires": "-1",
"failed": false,
"json": {
"items": [
{
"address": "10.200.136.22",
"connectionLimit": 0,
"dynamicRatio": 1,
"ephemeral": "false",
"fqdn": {
"autopopulate": "disabled"
},
"fullPath": "/Common/sensor01:443",
"generation": 103,
"inheritProfile": "enabled",
"kind": "tm:ltm:pool:members:membersstate",
"logging": "disabled",
"monitor": "default",
"name": "sensor01:443",
"partition": "Common",
"priorityGroup": 0,
"rateLimit": "disabled",
"ratio": 1,
"selfLink": "https://localhost/mgmt/tm/ltm/pool/~Common~sensor01/members/~Common~sensor01:443?ver=16.1.0",
"session": "monitor-enabled",
"state": "up"
}
],
"kind": "tm:ltm:pool:members:memberscollectionstate",
"selfLink": "https://localhost/mgmt/tm/ltm/pool/~Common~sensor01/members?ver=16.1.0"
},
"msg": "OK (668 bytes)",
"pragma": "no-cache",
"redirected": false,
"server": "Jetty(9.2.22.v20170606)",
"status": 200,
"strict_transport_security": "max-age=16070400; includeSubDomains",
"x_content_type_options": "nosniff",
"x_frame_options": "SAMEORIGIN",
"x_xss_protection": "1; mode=block"
}
tasks:
- debug:
var: pool_details
- debug:
var: pool_details.json.items[0].address
启用详细程度的完整错误是:
pool_details.json.items[0].address: 'VARIABLE IS NOT DEFINED!: builtin_function_or_method object has no element 0'
我获取地址的第二次调试不起作用(“未定义”),我不知道为什么。如果我采用相同的 json,并将其通过管道传输到 jq,它就可以正常工作:
pbpaste | jq '.json.items[0].address'
"10.200.136.22"
解决方案
如果列表中有更多项目,您可能想要使用json_query,例如
- set_fact:
list_address: "{{ pool_details.json['items']|
json_query('[].address') }}"
给
list_address:
- 10.200.136.22
如果您不想或不能安装 JmesPath,下一个选项将是map 属性,例如下面的代码给出相同的结果
- set_fact:
list_address: "{{ pool_details.json['items']|
map(attribute='address')|
list }}"
推荐阅读
- automapper - Automapper 未正确映射可空值
- datatable - 使用数据表的 UFT 脚本仅重复运行第一行;不考虑其余的行
- javascript - Vuejs为数字输入设置变量最大值
- javascript - 在视频球内显示图像
- c# - C# Regex.Matches - 引号问题
- database - 将任意数量的数据源同步到一个中央数据库
- ruby-on-rails - ActiveRecord 仅在属性低于另一个属性时查询
- javascript - Javascript 反转方法不会反转我的数组
- docker - 您的要求无法解决为一组可安装的软件包。码头工人组成
- kubernetes - 为什么prometheus operator无法启动