Search code examples
kubernetesmicrok8s

Kubernetes - How to get Service Name of a Pod Aligned to


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

Can you guys suggest ?


Solution

  • 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