On Sun, May 16, 2021 at 1:55 AM Scott Mcdermott <sc...@smemsh.net> wrote:
>
> Hello, why does short circuit only works for the first two cases:
>
> - hosts: localhost
>   become: false
>   vars:
>     ivar: '{{hostvars[inventory_hostname].dne}}'
>   tasks:
>     - debug:
>         msg: "works: {{'foo' or dne}}"
>     - debug:
>         msg: "works: {{'bar' or hostvars[inventory_hostname].dne}}"
>     - debug:
>         msg: "fails: {{'baz' or ivar}}
>
> The third debug will generate an error:
>
>     The task includes an option with an undefined variable.
>     The error was: {{hostvars[inventory_hostname].dne}}:
>     'ansible.vars.hostvars.HostVarsVars object' has no attribute 'dne'
>
> Why is it even looking up in hostvars at all? The non-empty
> string should evaluate True, so why is it reading the ORed
> condition?  The same thing happens with "if true else" and
> ternary(true, ...) filter.  It seems that it's properly
> short-circuiting in the first two cases, because the variable
> "dne" does not exist, and there is no error.  Even more
> confusing, the expansion of host vars is the exact same in cases
> 2 and 3, it's only going through an indirect variable in case 3.
>
> This seems to happen regardless of the source of variables ie
> extra vars, vars_files, etc.
>
> Is this a bug, or what am I missing?

This is effectively a side-effect of functionality in Ansible's
templating engine that allows nesting variables, like `ivar:
'{{hostvars[inventory_hostname].dne}}'` in your example. The second
operand of `or` is actually resolved somewhere within Jinja templating
machinery in all three cases. The difference is with the third one
where Ansible's extended templating functionality gets `ivar` and
tries to template it *because it is a template* (=this is what allows
nesting variables) which causes the failure.

There are issues reported asking to change this behavior, see
https://github.com/ansible/ansible/issues/58835 and
https://github.com/ansible/ansible/issues/56017 (or an interesting
example that was filed recently in
https://github.com/ansible/ansible/issues/74594).

The problem is that while changing this might result in expected
behavior in this case, it will break other scenarios. However the
above issues are open so feel free to give your input there.

Hopefully this clarifies the matter a bit.

Thanks,
Martin

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to ansible-project+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/CADDq2EP2zV5OTaZ_z5GY5MOkMX3ejeAUUkLZLkU--8m4E0e2KA%40mail.gmail.com.

Reply via email to