我正在使用aws,并且希望有一个小的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中解决这类案件呢?
发布于 2021-11-14 02:40:10
不是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 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?https://stackoverflow.com/questions/69959819
复制相似问题