bash - 在 bash 中检查 kubectl 连接

标签 bash kubectl

我正在使用 aws eks,希望有一个小型 shell 函数来检查 kubectl 是否可以与集群通信,如果不能,则显示更好的错误消息。

这是我的脚本:

_validate_kube_connectivity() 
{
        echo -n "kubernetes connectivity using kubectl..."
        kubectl get ns default

        if [[ ! "$?" -eq 0 ]]; then
            notok "failed (pls activate via AWS creds)"
            exit
        fi
        ok "yes"
}

但是,当没有 AWS 凭证时,它不会出现“IF”语句,这就是我在控制台中看到的内容:

kubernetes connectivity using kubectl...Unable to locate credentials. You can configure credentials by running "aws configure".
Unable to locate credentials. You can configure credentials by running "aws configure".
Unable to locate credentials. You can configure credentials by running "aws configure".
Unable to locate credentials. You can configure credentials by running "aws configure".
Unable to locate credentials. You can configure credentials by running "aws configure".
Unable to connect to the server: getting credentials: exec: executable aws failed with exit code 255

那么如何在 bash 中解决此类情况?

最佳答案

不是 kube 用户,但你可以尝试:

_validate_kube_connectivity() {
  if ! output=$(kubectl get ns default 2>&1); then
    printf 'notok failed (pls activate via AWS creds)\n' >&2
    exit 1
  fi

  printf 'kubernetes connectivity using kubectl...'
  kubectl get ns default
}

  • 上述解决方案使用命令替换将 kubectl 的输出保存在名为 output 的变量中。该作业具有有用的退出状态。

mentioned通过 @kamilCuk ,您可以打印作业中的错误消息。 "$output" 的值而不是您的自定义错误消息。类似的东西

_validate_kube_connectivity() {
  if ! output=$(kubectl get ns default 2>&1); then
    printf '%s\n' "$output" >&2
    exit 1
  fi
  printf 'kubernetes connectivity using kubectl...\n'
  kubectl get ns default
}

否则,您可以通过将错误消息重定向到 /dev/null 来静音该错误消息

_validate_kube_connectivity() {
  if ! kubectl get ns default >/dev/null 2>&1; then
    printf 'notok failed (pls activate via AWS creds)\n' >&2
    exit 1
  fi
  printf 'kubernetes connectivity using kubectl...\n'
  kubectl get ns default
}

我建议使用变量赋值,因为它会捕获来自 kubectl 的真实错误消息,为什么?这是来自 kubectl

的错误消息
The connection to the server localhost:8080 was refused - did you specify the right host or port?

关于bash - 在 bash 中检查 kubectl 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69959819/

相关文章:

bash - 使用 ffmpeg 和 youtube-dl 从 Youtube 视频下载几秒钟的音频结果 [youtube] : No such file or directory error

bash - 为什么找不到 imagemagick mogrify 命令以及如何解决这个问题?

kubernetes - Kubectl 等待 statefulset 的一个 pod 准备就绪?

kubernetes - 如何在EKS中添加或修复kube-dns?

kubernetes api 服务器在普罗米修斯(kube-state-metrics)中显示 - -"forbidden: User\"系统 :anonymous\"cannot get path\"/metrics\"",

go - 使用 golang 代码部署 kubernetes Pod

docker - 如何退出因网络错误而卡住的 `kubectl exec` 命令?

bash - 如何获取wget下载的文件的文件名

bash - Bash 文件中 $ 的转义字符

bash 脚本在获取时产生不同的结果