Is it possible to execute a task in Ansible only if at least one task in a specific block was changed?
So, something like this:
- name: Tasks block
block:
- name: Task 1
# ...
- name: Task 2
# ...
- name: Task 3
# ...
- name: Task 4
# ...
- name: Task 5
# ...
- name: Conditional task
when: block_result.changed
# ...
I know it is possible by registering a variable for each task in the block, then check every single one of them.
But is it possible to be done on the level of block? This is especially possible to avoid defining a lot of variables in case I have many tasks in one block.
My main goal is to evaluate the whole changed/not changed after the whole block is finished, so that the conditional task is executed only once if needed.
>Solution :
Your use case seems like the perfect fit for a handler.
If you need to trigger it at this exact location in your playbook, you will also need a meta: flush_handlers task, in order to trigger the handlers right away, and not at the end of all the tasks.
tasks:
- block:
- name: Task 1
shell: "true"
changed_when: false
- name: Task 2
shell: "true"
changed_when: true
- name: Task 3
shell: "true"
changed_when: false
notify:
- Conditional task
- name: Flush handlers
meta: flush_handlers
- debug:
msg: I run after the handler
handlers:
- name: Conditional task
debug:
msg: Running this conditional task now
Output of a play with the above code:
TASK [Task 1] *****************************************************
ok: [localhost]
TASK [Task 2] *****************************************************
changed: [localhost]
TASK [Task 3] *****************************************************
ok: [localhost]
TASK [Flush handlers] *********************************************
RUNNING HANDLER [Conditional task] ********************************
ok: [localhost] =>
msg: Running this conditional task now
TASK [debug] ******************************************************
ok: [localhost] =>
msg: I run after the handler