使用Ansible从JSON响应中提取字段

时间:2017-03-24 15:39:47

标签: json parsing ansible

我有一个对页面执行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'具有无效值,似乎包含变量  这是未定义的。错误是:'列出对象'没有属性' id' ..

问题出在哪里?

2 个答案:

答案 0 :(得分:6)

  

错误是:'list object'没有属性'id'

json_response.json.ips是一个列表。

您需要选择一个元素(第一个?):json_response.json.ips[0].id

如果您需要所有ID,请使用mapjson_query过滤器处理此列表。

答案 1 :(得分:0)

可复制到文件的命令:

  copy:
    content: "{{ output.stdout[0] }}"
    dest: "~/ansible/local/facts/{{ inventory_hostname }}.txt"