我有一个任务对页面执行GET请求。响应的正文是JSON,如下所示。
{
"ips": [
{
"organization": "1233124121",
"reverse": null,
"id": "1321411312",
"server": {
"id": "1321411",
"name": "name1"
},
"address": "x.x.x.x"
},
{
"organization": "2398479823",
"reverse": null,
"id": "2418209841",
"server": {
"id": "234979823",
"name": "name2"
},
"address": "x.x.x.x"
}
]
}
我想提取字段ID和地址,并尝试(对于id字段):
tasks:
- name: get request
uri:
url: "https://myurl.com/ips"
method: GET
return_content: yes
status_code: 200
headers:
Content-Type: "application/json"
X-Auth-Token: "0010101010"
body_format: json
register: json_response
- name: copy ip_json content into a file
copy: content={{json_response.json.ips.id}} dest="/dest_path/json_response.txt"
但我得到这个错误:
字段'args'具有无效值,该值似乎包含未定义的变量。错误是:'list object'没有属性'id'..
问题出在哪儿?
错误是:'list object'没有属性'id'
json_response.json.ips
是一个清单。
你要么选择一个元素(第一个?):json_response.json.ips[0].id
。
或者,如果您需要所有ID,请使用map
或json_query
过滤器处理此列表。
Ansible命令复制到文件:
copy:
content: "{{ output.stdout[0] }}"
dest: "~/ansible/local/facts/{{ inventory_hostname }}.txt"