Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if any task in block changed?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading