Kubernetes: How to get other pods' name from within a pod?

6/7/2021

I'd like to find out the other pods' name running in the same single-host cluster. All pods are single-application containers. I have pod A (written in Java) that acts as a TCP/IP server and a few other pods (written in C++) connect to the server.

In pod A, I can get IP address of clients (other pods). How do I get their pods' name? I can't run kubectl commands because pod A has no kubectl installed.

Thanks,

-- Kevin N
kubernetes

1 Answer

6/8/2021

You can directly call kube-apiserver with cURL.

  • First you need to have a serviceaccount binded to clusterrole to be able to send requests to apiserver.

    kubectl create clusterrole listpods --verb=get,list,watch --resource=pods

    kubectl create clusterrolebinding listpods --clusterrole=listpods --serviceaccount=default:default

  • Get a shell inside a container

    kubectl exec -it deploy/YOUR_DEPLOYMENT -- sh

  • Define necessary parameters for your cURL, run below commands inside container

    APISERVER=https://kubernetes.default.svc SERVICEACCOUNT=/var/run/secrets/kubernetes.io/serviceaccount NAMESPACE=$(cat ${SERVICEACCOUNT}/namespace) TOKEN=$(cat ${SERVICEACCOUNT}/token) CACERT=${SERVICEACCOUNT}/ca.crt

  • Send pods list request to apiserver

    curl -s -k -H "Authorization: Bearer $TOKEN" -H 'Accept: application/json' $APISERVER/api/v1/pods | jq "[ .items[] | .metadata.name ]"

Done ! It will return you a json list of "kubectl get pods"

For more examples, you can check OpenShift RestAPI Reference. Also, if you are planning to do some programmatic stuff, I advice you to checkout official kubernetes-clients.

Credits for jq improvement to @moonkotte

-- efdestegul
Source: StackOverflow