1

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

Can you guys suggest ?

Big Bansal
  • 73
  • 2
  • 7

2 Answers2

3

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=${NAMESPACE}\
    --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 jq because I'm unsure whether it's possible to use kubectl's JSONPath to range over a Service's labels and reformat these as needed. Even using jq, my command's messy:

  1. Get the Service's selector as {"k1":"v1","k2":"v2",...}
  2. Convert this to "k1=v1","k2=v2",...
  3. Trim the extra (?) "

If you want to do this for all Namespaces, you can wrap everything in:

NAMESPACES=$(kubectl get namespaces --output=name)
for NAMESPACE in ${NAMESPACE}
do
  ...
done
Big Bansal
  • 73
  • 2
  • 7
DazWilkin
  • 32,823
  • 5
  • 47
  • 88
0

You can get information about a pods service from it's environment variables. ( ref: https://kubernetes.io/docs/concepts/services-networking/connect-applications-service/#environment-variables)

kubectl exec <pod_name> -- printenv | grep SERVICE

Example:

Getting details about pod Getting details about

Getting service from environment variable Getting service from environment variable

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    That isn't what he's asking for. OP, look through all the environment variables and see if you find anything useful. Look for "SERVICE_NAME" perhaps. – David M. Karr Oct 22 '21 at 22:03