How to use arithmetic when setting a variable value in Ansible?


Ansible Problem Overview

I would like to use a system fact for a host times a number/percentage as a base for a variable. What I am trying to do specifically is use the ansible_memtotal_mb value and multiply it by .80 to get a ramsize to then use in setting a Couchbase value. I have been trying different variations of the line below. I'm not ever sure that it is possible, but any help would be appreciated.

  ramsize: '"{{ ansible_memtotal_mb }}" * .80'

Ansible Solutions

Solution 1 - Ansible

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:

  ramsize: "{{ ansible_memtotal_mb * 0.8 }}"

Solution 2 - Ansible

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


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAValentiView Question on Stackoverflow
Solution 1 - Ansibletedder42View Answer on Stackoverflow
Solution 2 - AnsibledosmanakView Answer on Stackoverflow