Search code examples
bashansible

Get the highest value of a json key with Ansible


I want to get the highest value of a child key with Ansible and store it in a variable. I'm able to do it with a bash command, which I could easily use with Ansible but I'm sure there is a more Ansible way to do it. Here is what I currently have:

- name: get latest version
  hosts: localhost
  gather_facts: no
  tasks:
    - name: get latest version
      ansible.builtin.command: curl --silent https://download.checkmk.com/stable_downloads.json | jq -r '.checkmk[].version' | sort -r | head -1

How could I improve this and store it in a variable? Thank you!


Solution

  • You can use the uri module to fetch the remote URL, instead of calling out to curl; you can use the json_query filter to parse the data; and you can use the sort and last filters to get the value you want. Finally, you use the set_fact module to store the value in a variable:

    - name: get latest version
      hosts: localhost
      gather_facts: false
      tasks:
        - name: get latest version
          uri:
            url: https://download.checkmk.com/stable_downloads.json
          register: version
    
        - set_fact:
            chkmk_version: "{{ version.json|json_query('checkmk.*.version')|sort|last }}"
    
        - debug:
            msg: "Latest checkmk version: {{ chkmk_version }}"