首页 > 解决方案 > 有没有办法让这个脚本检测到 pod 的错误(如 ErrImagePull)以及它何时失败?

问题描述

我有一个脚本可以检查命名空间中的 pod,当所有 pod 准备就绪时,它就会成功完成。
我需要做的是修改这个脚本,如果它在 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 "$1" -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="$1"
  interval="$2"

  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 :

标签: bashshellkubernetessh

解决方案


kubectl get pods | awk 'NR > 1 && $3 != "Running" { $3=="ImagePullBackOff"?err=2:err=1;exit err }'

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

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

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

推荐阅读