Ansible Post Tasks Execution Condition

ansible

I'd like to know, in which condition an Ansible post_task will be executed? If the pre-tasks or roles had any failure, would the post-tasks be executed?

For example, I'd like to clean up the server if and only if it is stopped. In the following script, will the server_dir be removed if server is not stopped correctly?

---

- hosts: webservers

  pre_tasks:
    - shell: echo 'stopping server...'

  roles:
    - { role: stop_server }

  post_tasks:
    - file: path="{{ server_dir }}" state=absent

Best Answer

Tasks under post_tasks will not be executed when the previous tasks failed (meaning that the return code of the task isn't 0). That is the default behavior of Ansible and part of the design of Ansible:

Ansible is actually designed to be a “fail-fast” and ordered system [...]

Ansible test_strategies

fail-fast means Ansible will stop the execution of the whole play as soon as one task fails (as long as you don't set ignore_errors: True parameter for the task.)

The documentation on post_tasks is incomplete but if you write yourself a small test playbook and role you will see that Ansible behaves as expected.

Which makes sense because you might want to use pre_tasks and post_tasks to remove and add a node from and to a cluster and you don't want your node to be added to a cluster when the role didn't executed without errors.