Running multiple kubectl commands in a bash script

11/19/2019

I'm trying to create a dashboard where I can see the status of my pods within my cluster. So I have a bash script that goes something like:

SERVICE_ONE=$(kubectl get pods | grep service-one | grep -E -- 'CrashLoopBackOff|Terminating|Error|Fail')
SERVICE_TWO=$(kubectl get pods | grep service-two | grep -E -- 'CrashLoopBackOff|Terminating|Error|Fail')
SERVICE_THREE=$(kubectl get pods | grep service-three | grep -E -- 'CrashLoopBackOff|Terminating|Error|Fail')

if [ ${#SERVICE_ONE} = 0 ]
then
  SERVICE_ONE_STATUS="GOOD"
else
  SERVICE_ONE_STATUS="BAD"

I then post these results to a GUI. The only problem is that I have almost 20 of these kubectl commands, which altogether, causes the program to take over 2 minutes to run. I tried doing something like:

KUBE_OUTPUT=$(kubectl get pods)
SERVICE_ONE=$(grep service-one <<< ${KUBE_OUTPUT} | grep -E -- 'CrashLoopBackOff|Terminating|Error|Fail')
SERVICE_TWO=$(grep service-two <<< ${KUBE_OUTPUT} | grep -E -- 'CrashLoopBackOff|Terminating|Error|Fail')
SERVICE_THREE=$(grep service-three <<< ${KUBE_OUTPUT} | grep -E -- 'CrashLoopBackOff|Terminating|Error|Fail')

But this doesn't work since the kube output isn't saved in the same format as when I run it plainly on my terminal (there's spacing issues, no newlines, etc.). I was wondering if there was a better way of executing multiple kubectl commands at once?

-- olivercollins-inhome
bash
kubernetes
shell

1 Answer

11/20/2019

since, running kubectl command every time to get the pod details will take the time.

i tried kubectl get pods with -o=jsonpath something like below

$  VAR=$(kubectl get pods -o=jsonpath="{range .items[*]}{.metadata.name}{'\t'}{.status.phase}{'\n'}{end}"
#x27;\
r' | grep -E -- 'CrashLoopBackOff|T erminating|Error|Fail|Running')

This will filter the result with NAME and STATUS of the pod. the output would be like

$ IFS=' '
$ echo $VAR
my-deployment-55bc8b77dd-8plsw  Running
my-deployment-55bc8b77dd-crlbx  Running
my-deployment-55bc8b77dd-jqqx4  Running
my-deployment-55bc8b77dd-mnm5k  Running
my-deployment-55bc8b77dd-zndvs  Running

Now you can again filter based in the pod name

$ SERVICE=$(echo $VAR | grep my-deployment-55bc8b77dd-8plsw)

the output will be

$ echo $SERVICE
my-deployment-55bc8b77dd-8plsw  Running

now split the result and display the status as you like. Hopw this helps. If this is not what you are looking for. plz put a comment.

Thanks.

-- Sameer Khan
Source: StackOverflow