"when" attribute in a play

Today I needed to add a condition to a play in my playbook. If it is true, the tasks are executed.

I’d expect this intuitive code to work:

  • hosts:all
    become:yes
    when:
    tasks:


Unfortunately, “when” is not a valid attribute of the play and I’m required to do it in a less intuitive way: e.g. replicate the when attribute for all tasks (worst solution), move all tasks to a single block of tasks and assign a when attribute to it or moving the play to a separate yaml and conditionally include it. All these solutions seem more cumbersome than just setting the when attribute to a play. Is there a reason why it is not supported?

Thanks in advance!

That’s a really hard question to answer. My question to you would be why can’t you just block it?

Regards,

Joe.

you can always create a main.yml in your role, then just conditionally import entire playbooks (like ‘some_playbook.yml’ in this case) such as:

$ cat main.yml

  • import_tasks: some_playbook.yml

when: inventory_hostname_short|regex_search(‘host1|otherhost2’)

Or any other conditional that works with ‘when’

Test the condition in the first task. For example

  - hosts: all
    tasks:
      - meta: end_play
        when: not condition|default('false')|bool
      - debug:
          msg: Start play