1

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.

  • can you add the output of `k get pod -n kube-system kube-apiserver-master -o yaml |grep -i auth` , replace it with the name of your master node. – P.... Mar 14 '22 at 13:22
  • - --anonymous-auth=false - --enable-bootstrap-token-auth=true - --token-auth-file=/etc/kubernetes/tokens/known_tokens.csv - --authorization-mode=Node,RBAC – Ollie Abbey Mar 14 '22 at 13:43

1 Answers1

1

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.

P....
  • 17,421
  • 2
  • 32
  • 52
  • Awesome, thank you very much! Because I was wanting to pipe the output of my `kubectl` command through `yq`, I've assigned the output of `k get cm` to a variable and tested that for null so I can exit if it's not there; but closing stdin was the bit I was looking for. Thanks again. – Ollie Abbey Mar 15 '22 at 08:16