Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible, how to check if a variable is not null?

Tags:

ansible

I have this var I a role that I use to add authorized keys to a linux user, so foo can either be a string with a single ssh public key or a list of multiple public keys.

By default foo is defined but empty so it can be tested even if the user doesn't set it, that way no related tasks are done if it's empty.

I'd normaly use when: foo or when: not foo and it was working great, except that now ansible trow a depreciation warning saying :

[DEPRECATION WARNING]: evaluating None as a bare variable, this behaviour will go away and you might need to add |bool to the expression in the future. Also see CONDITIONAL_BARE_VARS configuration toggle.. This feature will be removed in version 2.12. Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.

I tried when: foo|bool as mentionned but it returns false every time the variable is filled with a string that's not yes, true, Yes...

foo is defined doesn't work since the var is defined

foo != "" doesn't work because the var is null not a empty string

foo | length > 0 doesn't work because null doesn't have a length

I'm honestly out of ideas here.

like image 833
Junn Sorran Avatar asked Feb 19 '20 15:02

Junn Sorran


1 Answers

I think the answer is right there in the error. "evaluating None as a bare variable" suggests that foo evaluated to None. So you need:

when: foo != None

like image 88
debren27 Avatar answered Sep 29 '22 22:09

debren27