Extract Field from Json Response with Ansible

I have a task which performs a GET request to a page. The response's body is a JSON like the following.

 {
  "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"
    }
  ]
}

I want to extract the fields id and address, and tried (for id field):

tasks:
  - name: get request                                           
    uri:
      url: ""
      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"

but I get this error:

the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'list object' has no attribute 'id'..

Where is the problem?

2 Answers

The error was: 'list object' has no attribute 'id'

json_response.json.ips is a list.

You either need to choose one element (first?): json_response.json.ips[0].id.

Or process this list for example with map or json_query filters if you need all ids.

Ansible command to copy to file:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest