我正在使用 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/