Question:
I want to exit without an error (I know about assert and fail modules) when I meet a certain condition. The following code exits but with a failure:
1 2 3 4 5 6 7 8 9 10 |
tasks: - name: Check if there is something to upgrade shell: if apt-get --dry-run upgrade | grep -q "0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded"; then echo "no"; else echo "yes"; fi register: upgrading - name: Exit if nothing to upgrade fail: msg="Nothing to upgrade" when: upgrading.stdout == "no" |
Answer:
Since Ansible 2.2, you can use end_play
with the meta module:
1 2 |
- meta: end_play |
You can also specify when
for conditionally ending the play:
1 2 3 |
- meta: end_play when: upgrading.stdout == "no" |
Note, though, that the task is not listed in the output of ansible-playbook, regardless of whether or not the play actually ends. Also, the task is not counted in the recap. So, you could do something like:
1 2 3 4 5 6 7 8 |
- block: - name: "end play if nothing to upgrade" debug: msg: "nothing to upgrade, ending play" - meta: end_play when: upgrading.stdout == "no" |
which will announce the end of the play right before ending it, only when the condition is met. If the condition is not met, you’ll see the task named end play if nothing to upgrade
appropriately skipped, which would provide more info to the user as to why the play is, or is not, ending.
Of course, this will only end the current play and not all remaining plays in the playbook.