Home > Software design >  Exit kubectl command rather than prompt for login
Exit kubectl command rather than prompt for login

Time:03-15

I'm writing a utility script to retrieve and parse some kubernetes config maps, and typically I'll be authenticated using an oidc token.

In the event when I'm not authenticated, how can I make my kubectl command exit with a failure rather than prompt for a username and password?

Here's my current implementation:

#!/bin/bash

# Prompts me with "Please enter Username:", and I'd like to exit instead.
kubectl get cm -n my-namespace

Thanks in advance.

CodePudding user response:

You may use </dev/null in your command to close the std input for the command. Check the example below, where kubectl would print the result normally if things are fine(not prompted), else it will print error text.

Using a known good kubeconfig file:

kubectl  get pod --kubeconfig good_kube_config </dev/null
No resources found in default namespace.

Using a kubeconfig with misconfigured username:

kubectl  get pod --kubeconfig bad_kube_config </dev/null
Please enter Username: error: EOF

You can use something like the below in your script, note that this would print an error on all the failures regardless of their relation with user/pass prompt.

if !  kubectl get cm -n my-namespace </dev/null 2>/dev/null;then
      echo "Error: Somthing is wrong!"
      exit 1;
fi

If you want to be very specific to user/pass error, then suggest you use a kubectl get command to run a test by greping "Username" string, then proceed.

Note: To simulate the same prompt, I renamed the user name in my kubeconfig file.

  • Related