Home > Net >  Kubernetes - How to get Service Name of a Pod Aligned to
Kubernetes - How to get Service Name of a Pod Aligned to

Time:10-26

I would like to know, how to find service name from the Pod Name in Kubernetes.

Can you guys suggest ?

CodePudding user response:

Services (spec.selector) and Pods (metadata.labels) are bound through shared labels.

So, you want to find all Services that include (some) of the Pod's labels.

kubectl get services \
--selector=${KEY-1}=${VALUE-1},${KEY-2}=${VALUE-2},...
--namespace=${NAMESPACE}

Where ${KEY} and ${VALUE} are the Pod's label(s) key(s) and values(s)

It's challenging though because it's possible for the Service's selector labels to differ from Pod labels. You'd not want there to be no intersection but a Service's labels could well be a subset of any Pods'.

The following isn't quite what you want but you may be able to extend it to do what you want. Given the above, it enumerates the Services in a Namespace and, using each Service's selector labels, it enumerates Pods that select based upon them:


NAMESPACE="..."

SERVICES="$(\
  kubectl get services \
  --namespace=${NAMESPACE} \
  --output=name)"

for SERVICE in ${SERVICES}
do
  SELECTOR=$(\
    kubectl get ${SERVICE} \
    --namespace=monitoring \
    --output=jsonpath="{.spec.selector}" \
    | jq -r '.|to_entries|map("\(.key)=\(.value)")|@csv' \
    | tr -d '"')
  PODS=$(\
    kubectl get pods \
    --selector=${SELECTOR} \
    --namespace=${NAMESPACE} \
    --output=name)
  printf "%s: %s\n" ${SERVICE} ${PODS}
done

NOTE This requires Getting details about

Getting service from environment variable Getting service from environment variable

  • Related