Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ansible

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.

vars:
  ramsize: '"{{ ansible_memtotal_mb }}" * .80'
like image 664
AValenti Avatar asked Nov 03 '15 17:11

AValenti


People also ask

How do you use arithmetic operations in Ansible?

You can use arithmetic calculations in Ansible using the Jinja syntax. This is helpful in many situations where you have stored the output of an operation, and you need to manipulate that value. All usual operation like addition, subtraction, multiplication, division, and modulo are possible.

How do you assign variables in Ansible?

You can define these variables in your playbooks, in your inventory, in re-usable files or roles, or at the command line. You can also create variables during a playbook run by registering the return value or values of a task as a new variable.

What does Set_fact do in Ansible?

This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will be available to subsequent plays during an ansible-playbook run.


2 Answers

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
like image 35
dosmanak Avatar answered Oct 09 '22 02:10

dosmanak


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 }}"
like image 180
tedder42 Avatar answered Oct 09 '22 03:10

tedder42