Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide and multiply Ansible facts queried by json_query?

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

like image 917
Ali Avatar asked Oct 22 '25 09:10

Ali


1 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'
like image 119
Vladimir Botka Avatar answered Oct 26 '25 02:10

Vladimir Botka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!