What is the best way to wait for kubernetes job to be complete? I noticed a lot of suggestions to use:
kubectl wait --for=condition=complete job/myjob
>
You can leverage the behaviour when --timeout=0
.
In this scenario, the command line returns immediately with either result code 0 or 1. Here's an example:
retval_complete=1
retval_failed=1
while [[ $retval_complete -ne 0 ]] && [[ $retval_failed -ne 0 ]]; do
sleep 5
output=$(kubectl wait --for=condition=failed job/job-name --timeout=0 2>&1)
retval_failed=$?
output=$(kubectl wait --for=condition=complete job/job-name --timeout=0 2>&1)
retval_complete=$?
done
if [ $retval_failed -eq 0 ]; then
echo "Job failed. Please check logs."
exit 1
fi
So when either condition=failed
or condition=complete
is true, execution will exit the while loop (retval_complete
or retval_failed
will be 0
).
Next, you only need to check and act on the condition you want. In my case, I want to fail fast and stop execution when the job fails.