"when" attribute in a play

28 views
Skip to first unread message

alan....@gmail.com

unread,
Dec 18, 2020, 4:04:22 PM12/18/20
to Ansible Project
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: <condition>
  tasks:
    <task1>
    ...
    <taskn>

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!

joseph.alexanderiii

unread,
Dec 18, 2020, 4:12:16 PM12/18/20
to ansible...@googlegroups.com
That's a really hard question to answer.  My question to you would be why can't you just block it? 

Regards, 

Joe. 
--
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-proje...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ansible-project/584da1a8-3b58-4a91-ac47-5d1934e36368n%40googlegroups.com.

Michael Mullay

unread,
Dec 18, 2020, 4:42:11 PM12/18/20
to ansible...@googlegroups.com
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'




Vladimir Botka

unread,
Dec 18, 2020, 6:33:16 PM12/18/20
to ansible...@googlegroups.com
On Fri, 18 Dec 2020 13:01:52 -0800 (PST)
"alan....@gmail.com" <alan....@gmail.com> wrote:

> - hosts:all
> become:yes
> when: <condition>
> tasks:
> <task1>

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

--
Vladimir Botka
Reply all
Reply to author
Forward
0 new messages