[k8s] kubectl执行失败后等待一段时间再重试 (Shell实现)

本文介绍了一个Shell脚本,当kubectl执行失败时,该脚本会等待30秒后重试,最多尝试3次,针对MicroK8s未运行、连接超时和连接被拒绝等常见错误进行处理。
摘要由CSDN通过智能技术生成

使用Shell脚本实现功能: kubectl执行失败后,等待30秒后再重试,一共重试3次,代码如下:

#!/bin/bash

KUBECTL_BIN=/var/lib/snapd/snap/bin/kubectl

ERR_MSG_K8S_NOTRUNNING="microk8s is not running"
ERR_MSG_CONNECTION_TIMEOUT="connection timed out"
ERR_MSG_CONNECTION_REFUSED="refused - did you specify the right host or port"

function debuglog() {
    local log_content=${@:1}
    local caller=$(basename "$0")
    echo "`date +"%Y-%m-%d %H:%M:%S"` [$caller] INFO $log_content" 2>&1
}

function api_kubectlX() {
    local retry=$1
    shift
    local args=$@
    local ret=0
    local cmdstr="${args[@]}"
    local tmpfile=$(mktemp)
    for ((i=0;i<$retry;i++)); do
        ${KUBECTL_BIN} $@ 2>"$tmpfile"
        ret=$?
        if [ $ret -eq 0 ]; then
            debuglog "KUBECTL $cmdstr ret: 0"
            break
        fi

        local errinfo=$(< "$tmpfile")
        local need_retry="no"
        if [ -n "$(echo "$errinfo" | grep "$ERR_MSG_K8S_NOTRUNNING")" ]; then
            need_retry="yes"
        elif [ -n "$(echo "$errinfo" | grep "$ERR_MSG_CONNECTION_TIMEOUT")" ]; then
            need_retry="yes"
        elif [ -n "$(echo "$errinfo" | grep "$ERR_MSG_CONNECTION_REFUSED")" ]; then
            need_retry="yes"
        elif [ $ret -eq 143 ]; then # 143 means SIGTERM, just retry
            need_retry="yes"
        else
            need_retry="no"
        fi

        if [ $need_retry != "yes" ]; then
            debuglog "KUBECTL ret: $ret/($errinfo) $cmdstr"
            break
        fi
        debuglog "KUBECTL ret: $ret/($errinfo) (retry:$i) $cmdstr"
        sleep 30
    done
    rm -- ${tmpfile}
    return $ret
}

function api_kubectl() {
    local args=(3 "$@")
    api_kubectlX "${args[@]}"
    return $?
}

# 使用方法:
api_kubectl get ns 
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pcj_888

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值