I'm using aws eks and want to have a small shell func to check if kubectl can communicate with the cluster and if not display a nicer error msg.
this is my script:
_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"
}
however when there are no AWS credentials it is not going to "IF" statement and this is what I see in console:
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
so how do I solve such cases in bash?
CodePudding user response:
Not a kube user but you can try:
_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
}
- The above solution saves the output of
kubectl
in a variable namedoutput
using command substitution. The assignment has a useful exit status.
As mentioned by @kamilCuk, you can print the error message from the assignment. The value of "$output"
instead of your custom error message. Something like
_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
}
Otherwise you can just silence the error message by redirecting it to /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
}
I suggest to use the variable assignment since it will capture the real error message from kubectl
, Why? Here is my error message from kubectl
The connection to the server localhost:8080 was refused - did you specify the right host or port?