13

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.

Junn Sorran
  • 317
  • 2
  • 4
  • 12

3 Answers3

19

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

debren27
  • 191
  • 3
10

The thing you are looking for is the default filter, which helpfully has an alias d as in when: foo | d("") or even when: foo | d(False)

Just watch out, default normally only replaces null or None, and not the pythontic idea of truthiness. For that, you'll want to provide it a second argument foo | default("something-else", true) which works in the cases that foo is either null or "" (or likely 0 also)

mdaniel
  • 31,240
  • 5
  • 55
  • 58
0

In my case default filter doesn't works. Just not defaulting defined but unset variable.

There is a working solution

- hosts: 127.0.0.1
  connection: local
  vars:
    foo:
  tasks:
    - name: Ensure foo is set
      ansible.builtin.fail:
        msg: "Foo is not set"
      when: foo is undefined or foo == None or foo | length == 0
    - name: Show var
      ansible.builtin.debug:
        var: foo

There is 3 checks: does foo undefined, does foo set and does foo not empty string.

Azhinu
  • 11
  • 1