How to use arithmetic when setting a variable value in Ansible?
Solution 1:
You're really close! I use calculations to set some default java memory sizes, which is similar to what you are doing. Here's an example:
{{ (ansible_memtotal_mb*0.8-700)|int|abs }}
That shows a couple of things- first, it's using jinja math, so do the calculations inside the {{ jinja }}
. Second, int
and abs
do what you'd expect- ensure the result is an unsigned integer.
In your case, the correct code would be:
vars:
ramsize: "{{ ansible_memtotal_mb * 0.8 }}"
Solution 2:
One little thing to add. If you presume the math multiplication has precedence before jinja filter (| sign), you're wrong ;-)
With values like
total_rate: 150
host_ratio: 14 # percentual
"{{ total_rate*host_ratio*0.01|int }}" => 0 because 0.01|int = 0
"{{ (total_rate*host_ratio*0.01)|int) }}" => 21 as one expects