检查 bash 中的 kubectl 连接

check kubectl connectivity in bash

我正在使用 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 的变量中。该作业具有有用的退出状态。

作为 by @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?