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:
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"
The following was helpful in my case, as
meta: end_play
seems to stop the execution for all hosts, not just the one that matches.First establish a fact:
Now include that part that should only executed on this condition:
Lets use what Tymoteusz suggested for roles:
Split your play into two roles where first role will execute the check (and sets some variable holding check's result) and second one will act based on result of the check.
I have created
aaa.yaml
with this content:then role
check
inroles/check/tasks/main.yaml
:and then role
doit
inroles/doit/tasks/main.yaml
:And this was the output:
It is not perfect: looks like you will keep seeing skipping status for all tasks for skipped systems, but might do the trick.
In Ansible 2.2, you can use
end_play
with the meta module:You can also specify
when
for conditionally ending the play: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:
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.
A better and more logical way to solve it may be to do the reverse and rather than fail if there is nothing to upgrade (which is a separate step that does only that) you could append all your upgrading tasks with a conditional depending on the
upgrade
variable. In essence just addto tasks that should be only executed during an upgrade.
It is a bit more work, but it also brings clarity and self contains the logic that affects given task within itself, rather than depending on something way above which may or may not terminate it early.