简体   繁体   中英

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

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,

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM