kubectl command to find a particular pod status as ready

1/14/2021

I wanted to hit a command which searches pod with the service name and identify its pod's status as "Ready"

I tried some of the commands but it does not work and it does not search with service-name.

kubectl get svc | grep my-service | --output="jsonpath={.status.containerStatuses[*].ready}" | cut -d' ' -f2

I tried to use the loop also, but the script does not give the desired output.

Can you please help me figure out the exact command?

-- sagar verma
containers
kubectl
kubernetes
kubernetes-helm
kubernetes-pod

2 Answers

1/14/2021

If I understood you correctly, you want to find if specific Pod connected to specific Endpoint - is in "Ready" status .

Using JSON PATH you can display all Pods in specific namespace with their status:<br>

$ kubectl get pod -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}'

If you are looking for status for Pods connected to specific Endpoint, you can use below script:

#!/bin/bash

endpointName="web-1"

for podName in $(kubectl get endpoints  $endpointName -o=jsonpath={.subsets[*].addresses[*].targetRef.name}); do
    if [ ! -z $podName ]; then
        kubectl get pod -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}' | grep $podName
    fi
done

for podName in $(kubectl get endpoints  $endpointName -o=jsonpath={.subsets[*].notReadyAddresses[*].targetRef.name}); do
    if [ ! -z $podName ]; then
        kubectl get pod -o=jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.status.phase}{"\n"}{end}' | grep $podName
    fi
done

Please note that you need to change Endpoint name to your needs, in above example I use web-1 name.

If this response doesn't answer your question, please specify your exact purpose.

-- matt_j
Source: StackOverflow

1/14/2021

every service create a endpoints which contain the podIp and other info for service. you can just use that endpoints to get you pods. . it will show you the ready pod for your my-service.

use this command:

kubectl get endpoints -n <Name_space> <service_name> -o json | jq -r 'select(.subsets != null) | select(.subsets[].addresses != null) | .subsets[].addresses[].targetRef.name'

for you the command will be:

kubectl get endpoints my-service -o json | jq -r 'select(.subsets != null) | select(.subsets[].addresses != null) | .subsets[].addresses[].targetRef.name'

you can run the script for getting the pod status

#!/usr/bin/env bash
for podname in $(kubectl get endpoints my-service -o json | jq -r 'select(.subsets != null) | .subsets[].addresses[].targetRef.name')
do
kubectl get pods -n demo  $podname  -o json | jq -r ' select(.status.conditions[].type == "Ready") | .status.conditions[].type ' | grep -x Ready

done
-- Emon46
Source: StackOverflow