Odd case where I cannot figure out how to eliminate {{ }} in a when: clause

All - I’m trying to dynamically set facts in a loop. (Long story short, for a list of keys, if the key isn’t defined, I want to replace the key with the value from a register variable.) I have a playbook that works, but it requires the use of {{ }} in a when: clause, and Ansible is complaining. Can anyone figure out how to rewrite the when: without {{ }} ?

`
$ cat y.yml

Since you variable name is in a variable you need to lookup the variable

   when: hostvars[inventory_hostname][item.key] is not defined

You are actually the 'exception' so it is fine for your use {{ }} in
when because you actually mean to do double interpolation.

He also wanted to remove the that Ansible is complaining as I understood it, and then {{ }} need to be removed.

yes, but your example only handles 'hostvars', which the ones he is
trying to interpolate happen not to be, you need the 'vars' lookup
instead.

I always use vars since it works great but I know you are not very fond of that.

I was initially going to post this
  when: vars[item.key] is not defined

but just before I posted changed it to
  when: hostvars[inventory_hostname][item.key] is not defined
and as you say, it doesn't work.

The problem with the vars lookup is it fails if the variable is not defined and the default=None is not working.

  - debug: msg="{{ lookup('vars', 'no_existing_var', default=None) }}"

gives error
  The task includes an option with an undefined variable. The error was: No variable found with this name: no_existing_var

This means you need to put a string that you would never use as default, something like this
  when: lookup('vars', item.key, default='the varible is not defined') == 'the varible is not defined'

This works but is not a very elegant solution as the test "is not defined"

Thank you both, and apologies for not responding sooner (got yanked onto something else). vars worked great.

Rob

my issue with 'vars' is that it is not templated for all values, it
was never meant for direct use and we don't even use internally
anymore and we hope to remove soon.

the `vars` lookup does template values correctly and was created for
that purpose.

vars lookup is not a very good substitute IMHO since it can't handle undefined variable very well.
So that leaves us with vars for the foreseeable future.