How to check the JSON response from a uri request with Ansible?

You need to use a jinja2 filter (http://docs.ansible.com/ansible/playbooks_filters.html). In this case, the name of the filter is from_json. In the following example I'll take an action when the key is found and other action when the could not be found:

 ---                                                                                                            

 - hosts: somehost                                                                                               
   sudo: yes                                                                                                    

   tasks:                                                                                                       

   - name: Get JSON from the Interwebs                                                                          
     uri: url="https://raw.githubusercontent.com/ljharb/node-json-file/master/package.json" return_content=yes  
     register: json_response                                                                                    

   - debug: msg="Error - undefined tag"                                                                         
     when: json_response["non_existent_tag"] is not defined                                                     

   - debug: msg="Success - tag defined =>{{  (json_response.content|from_json)['scripts']['test'] }}<="  
     when:  (json_response.content|from_json)['scripts']['test']  is defined    

Now replace the debug for the appropriate to take the desired action.

Hope it helps,


I stumbled here after looking for a way on how to extract a field from json from the github api. I ended up with the following solution.

uri: url="https://api.github.com/repos/.../.../releases/latest" return_contents=yes

register: github_json

and use it somewhere else like this:

"{{ github_json.json.$key }}"

As per documentation at https://docs.ansible.com/ansible/latest/modules/uri_module.html

Whether or not to return the body of the response as a "content" key in the dictionary result. Independently of this option, if the reported Content-type is "application/json", then the JSON is always loaded into a key called json in the dictionary results.

---
- name: Example of JSON body parsing with uri module
  connection: local
  gather_facts: true
  hosts: localhost
  tasks:

    - name: Example of JSON body parsing with uri module
      uri: 
        url: https://jsonplaceholder.typicode.com/users
        method: GET
        return_content: yes
        status_code: 200
        body_format: json
      register: data
      # failed_when: <optional condition based on JSON returned content>

    - name: Print returned json dictionary
      debug:
        var: data.json

    - name: Print certain element
      debug:
        var: data.json[0].address.city