What is the proper way to check multiple conditions before running a task?

I have this task:

  • name: ensure nfs mountpoints exist
    file: path={{ item[1].path }} state=directory group={{ item[1].group }} owner={{ item[1].owner }} mode={{ item[1].mode }}
    when: nfs_automount_use AND item[1].path != 0
    with_items: nfs_automount.mountpoints|dictsort
    notify: restart nfs_automount
    tags: nfs_automount

In my group_vars file, nfs_automount_use is set to true.

In my host_vars/hostname file, nfs_automount_use is set to false.

When I run the task, I get:

TASK: [ensure nfs mountpoints exist] ******************************************
fatal: [hostname] => error while evaluating conditional: {% if nfs_automount_use AND item[1].path != 0 %} True {% else %} False {% endif %}
FATAL: all hosts have already failed – aborting

If I run the task with:

when: item[1].path != 0

It iterates through the nfs_automount.mountpoints as expected.

when: nfs_automount_use

It skips the task like I want.

So, what am I doing wrong? Or is this a bug?

Found a way around the issue. When you are including a task file, you can add the when condition. Like:

  • include: nfs_automount.yml
    when: nfs_automount_use

If I set the var to false, it skips all the tasks in the yml file. :slight_smile:

Though, there still should be a way I can use normal boolean logic in the when conditional… At least I think.

At least I have a decent, in some ways, actually better method to do what I was trying to do.

Yep!

Also you can do when conditions as lists, which is how this works internally.

If the first is False, it will not evaluate the rest either.

Additionally

when: nfs_automount_use AND item[1].path != 0

when: nfs_automount is defined and item is defined and …

Technically also should work and short-circuit.