How to divide and multiply Ansible facts queried by json_query?

Viewed 179
"{{ ansible_facts | json_query('mounts[*].size_available') }} / {{ ansible_facts | json_query('mounts[*].size_total') }} * 100"

I am trying to get size available and divide it by size total and Multiply it by 100 to give me the percentage disc usage. This current code gives me the output something like this:

"msg": "[238273] / [483298433] * 100"

It completely ignores the / and the *.
How can I resolve this issue?

2 Answers

json_query is not needed. Simply map the attributes, e.g.

    - debug:
        msg: "{{ (item.0 / item.1 * 100)|round }}"
      with_together:
        - "{{ ansible_mounts|map(attribute='size_available')|list }}"
        - "{{ ansible_mounts|map(attribute='size_total')|list }}"

gives

ok: [localhost] => (item=[2085240832, 41015336960]) => 
  msg: '5.0'
ok: [localhost] => (item=[30278656, 100663296]) => 
  msg: '30.0'
ok: [localhost] => (item=[21565116416, 109899771904]) => 
  msg: '20.0'

A simpler option is to iterate the list of mounts, e.g.

    - debug:
        msg: "{{ (item.size_available / item.size_total * 100)|round }}"
      loop: "{{ ansible_mounts }}"
      loop_control:
        label: "{{ item.mount }}"

gives

ok: [localhost] => (item=/) => 
  msg: '5.0'
ok: [localhost] => (item=/boot/efi) => 
  msg: '30.0'
ok: [localhost] => (item=/export) => 
  msg: '20.0'

You need your math operator to be inside the Jinja expression {{ ... }}.

Moreover, since you are getting [238273] and [483298433] your JMESPath queries in json_query are returning you two lists, so you do want to use the first filter.

Last, but not least, those two values are still going to return you some string, so you do want to use the int filter.

"{{ (ansible_facts | json_query('mounts[*].size_available') | first | int) / (ansible_facts | json_query('mounts[*].size_total') | first | int) * 100 }}"
Related