Simple Math with String to Int

14 views
Skip to first unread message

M F

unread,
Mar 2, 2020, 9:14:41 PM3/2/20
to Ansible Project
Hi All,

Im having trouble with setting a fact, doing some math, and having the result be an INT

To start, i set the base Var

set_fact: SOMENUMBER = 8

Ansible stores this value as a String

Later, i need to divide that number by 2 and get the result as an INT

set_fact: myvar = "{{ SOMENUMBER / 2) }}"

Even then though, Ansible stores it as a string.

If I do this, i get an INT, but its a FLOAT 4.0 instead of 4

set_fact: myvar = "{{ ((SOMENUMBER|int) / 2) }}"

I am having to resort to doing the following to get my answer of 4

set_fact: myvar = "{{ ((SOMENUMBER|int) / 2)|replace('.0','') }}"

Is there a better way to take a single integer stored as a string, and perform math and output an INT more simply?

TIA!

Vladimir Botka

unread,
Mar 3, 2020, 1:08:08 AM3/3/20
to M F, ansible...@googlegroups.com
On Mon, 2 Mar 2020 18:14:41 -0800 (PST)
M F <mikefi...@gmail.com> wrote:

> I am having to resort to doing the following to get my answer of 4
>
> set_fact: myvar = "{{ ((SOMENUMBER|int) / 2)|replace('.0','') }}"
>
> Is there a better way to take a single integer stored as a string, and
> perform math and output an INT more simply?

I'm afraid there isn't any. Jinja is a template engine, hence the default
output is a string. This was the intention of the developers, I think.
Otherwise one would have to explicitly convert the output of mathematics
expressions to strings.

Some notes to the examples:

* The output of the example isn't INT. It's a string. The consequent task
confirms this

- debug:
msg: Variable myvar is a string
when: myvar is string

* Also the following task will fail

- debug:
msg: "{{ myvar + 4 }}"

with error message:

"Unexpected templating type error occurred on ({{ myvar + 4 }}):
coercing to Unicode: need string or buffer, int found"

* Instead the conversion to integer works as expected

- debug:
msg: "{{ myvar|int + 4 }}"

gives:

"msg": "8"


HTH
-vlado

Martin Krizek

unread,
Mar 3, 2020, 2:07:58 AM3/3/20
to ansible...@googlegroups.com
Jinja2 native types introduced in Ansible 2.7 should be what you want:
https://docs.ansible.com/ansible/latest/reference_appendices/config.html#default-jinja2-native

Martin

M F

unread,
Mar 3, 2020, 3:16:06 PM3/3/20
to Ansible Project
Thank You

I will check that out

Much appreciated

Reply all
Reply to author
Forward
0 new messages