4
"{{ 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?

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
Ali
  • 55
  • 5

2 Answers2

2

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'
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
1

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 }}"
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83