有没有办法让这个脚本检测到 pod 的错误(比如 ErrImagePull)以及它何时失败?

Is there a way that this script, detects an error (like ErrImagePull) with the pod and when it does it fails?

我有一个脚本可以检查命名空间中的 pods,当所有 pods 准备就绪时,它就会成功完成。
我需要做的是以某种方式修改此脚本,如果它在 pod 状态上检测到错误(如 ErrImagePull),它会立即失败。
该脚本以这种方式工作。 scriptname.sh 120 2 - 这意味着脚本运行 120 秒并每 2 秒检查一次。

如果它在 120 秒之前检测到就绪状态,则它会完成,否则它会停留 120 秒并完成。

这是脚本:

#!/usr/bin/env bash

# Copyright 2017, Z Lab Corporation. All rights reserved.
# Copyright 2017, Kubernetes scripts contributors
#
# For the full copyright and license information, please view the LICENSE
# file that was distributed with this source code.

set -e

function __is_pod_ready() {
  [[ "$(kubectl get po "" -o 'jsonpath={.status.conditions[?(@.type=="Ready")].status}')" == 'True' ]]
}

function __pods_ready() {
  local pod

  [[ "$#" == 0 ]] && return 0

  for pod in $pods; do
    __is_pod_ready "$pod" || return 1
  done

  return 0
}

function __wait-until-pods-ready() {
  local period interval i pods

  if [[ $# != 2 ]]; then
    echo "Usage: wait-until-pods-ready PERIOD INTERVAL" >&2
    echo "" >&2
    echo "This script waits for all pods to be ready in the current namespace." >&2

    return 1
  fi

  period=""
  interval=""

  for ((i=0; i<$period; i+=$interval)); do
    pods="$(kubectl get po -o 'jsonpath={.items[*].metadata.name}')"
    if __pods_ready $pods; then
      return 0
    fi

    echo "Waiting for pods to be ready..."
    sleep "$interval"
  done

  echo "Waited for $period seconds, but all pods are not ready yet."
  return 1
}

__wait-until-pods-ready $@
# vim: ft=sh :
kubectl get pods | awk 'NR > 1 &&  != "Running" { =="ImagePullBackOff"?err=2:err=1;exit err }'

这方面的大部分处理很可能可以通过 awk 来实现。通过管道传输 kubectl 命令的输出并检查除 header (NR > 1) 之外的任何不等于“运行”的行。在这些情况下,检查文本“ImagePullBackOff”。如果找到,则以错误代码 2 退出,否则以错误代码 1 退出。在所有其他情况下,即所有 pods 运行,awk 将以 0.

退出

如果要检查其他错误,可以替换 ?带有 if 语句的条件语句等等:

kubectl get pods | awk 'NR > 1 &&  != "Running" { if (=="ImagePullBackOff") { err=2 } if ( == "ErrImagePull") { err=2 } else { err=1 };exit err }'