Wait for kubernetes job to complete on either failure/success using command line

前端 未结 3 1692
暖寄归人
暖寄归人 2021-02-18 17:39

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
         


        
3条回答
  •  隐瞒了意图╮
    2021-02-18 18:02

    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.

提交回复
热议问题