【问题标题】:check kubectl connectivity in bash检查 bash 中的 kubectl 连接性
【发布时间】:2023-03-30 06:32:02
【问题描述】:

我正在使用 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 中解决这种情况呢?

【问题讨论】:

    标签: bash kubectl


    【解决方案1】:

    不是 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 的变量中。分配具有有用的退出状态。

    作为@kamilCukmentioned,您可以打印作业中的错误消息。 "$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?
    

    【讨论】:

    • 输出并没有真正使用,你可以在最后一行echo "$output",对吧?
    • 谢谢!像魅力一样工作!
    猜你喜欢
    • 2014-01-15
    • 1970-01-01
    • 2015-11-18
    • 1970-01-01
    • 2019-06-04
    • 1970-01-01
    • 2017-11-23
    • 2018-01-19
    相关资源
    最近更新 更多