简体   繁体   中英

Running multiple kubectl commands in a bash script

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?

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}"$'\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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM