Extract field from JSON response with Ansible

14,904

Solution 1

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.

Solution 2

Ansible command to copy to file:

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

Related videos on Youtube

SegFault
Author by

SegFault

Updated on June 04, 2022

Comments

  • SegFault
    SegFault almost 2 years

    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: "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"
    

    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?