Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja/ansible convert string to boolean

I need the simple thing - if variable is false or empty string, then evaluate to false. Otherwise evaluate to true.

I tried bool(var) but I'm getting:

UndefinedError: 'bool' is undefined

Then I tried var | bool but even though var is non-empty, that evaluates to false. How to make that condition work??

like image 819
akostadinov Avatar asked Mar 07 '16 12:03

akostadinov


2 Answers

I've found a possible solution in ruby style:

    when: not not var

But it's rather ugly. Forgot to say that without not not the var evaluates to a string so ansible errors out. I hope for a better answer so please add another answer if you have.

like image 71
akostadinov Avatar answered Oct 03 '22 01:10

akostadinov


Your main problem is that anything other than "true" is going to get evaluated as false when using var | bool.

If you are always providing it as a string (eg. var: '' or var: 'false') then you can just check for string equality:

when: condition == 'false' or condition == ''

Optionally adding the boolean check as well if you have that possibility:

when: not condition or condition == 'false' or condition == ''

Alternatively you could default to a boolean and optionally override. For example you might have a role that has a conditional task:

roles/foo/tasks/main.yml

- name: echo foobar
  shell: echo 'foobar'
  when: echo_foo

roles/foo/defaults/main.yml

echo_foo: false

But then we might override this at a group or hosts vars level:

group_vars/foobar-nodes.yml

echo_foo: true
like image 42
ydaetskcoR Avatar answered Oct 03 '22 00:10

ydaetskcoR