Condition before lookup

Hello list,

I’m having a problem with adding a condition before a lookup plugin.

A simplified example that everyone can reproduce is this:

`

  • debug: msg=“This debug message should not be triggerd since some_dict is not defined”
    when: some_dict is defined
    with_dict: some_dict
    `

That doesn’t work because with_dict is processed before the condition is checked. That’s not wrong, that’s a good feature, because it enables you to do things like this:

`

  • debug: msg=“Only process item a”
    when: item == “a”
    with_items:
  • a
  • b
    `

How could I solve my problem with having a condition before the task fails, because some_dict is not defined in my first example?

Not even an ignore_errors: yes helps in this case. I guess because it is a fatal error raised by the plugin and not simply a failed task.

`
TASK: [debug msg=“This debug message should not be triggerd since some_dict is not defined”] ***
fatal: [test1.local] => with_dict expects a dict

FATAL: all hosts have already failed – aborting
`

Thanks,
Daniel

OK, I found a workaround. My task actually is inside a role. Therefore I was able to define a default value for some_dict.

myRole/defaults/main.yml:

some_dict: {}

The condition still is ignored, but with no elements nothing is processed, obviously.

Is there another solution to this? If this task would not be inside a role (yes, I know you always should work with roles ;)) I wouldn’t be able to define a default value.

Cheers,
Daniel

conditionals are for tasks, not for lookups, these always get executed

Not really a solution for the problem, is it? :wink:

actually the solution is what you already used or

with_dict: some_dict|default({})

Ah, great, didn’t know you can use default in the yml itself. Only had been using it in jinja templates. Thanks, that works and is more elegant that creating the additional defaults file.

"with_" fields are 'auto templated', you can use jinja2 in all fields
that are so

For some further elucidation, it should be pointed out that the “when” gets evaluated for every step of the loop, which is why it can’t be applied to decide whether to loop in the first place.

when: foo is defined and
with_items: foo

Will work as a looping construct, if you don’t want to the default trick.