How can I get a list of the pods running on the same Kubernetes node as my own (privileged) pod, using the official Python Kubernetes client? That is, how can a pod identify the concrete Kubernetes node it is running on and then query for a full list of pods on this node only?
To find the cluster IP address of a Kubernetes pod, use the kubectl get pod command on your local machine, with the option -o wide . This option will list more information, including the node the pod resides on, and the pod's cluster IP. The IP column will contain the internal cluster IP address for each pod.
On Google Kubernetes Engine (GKE), the limit is 100 pods per node, regardless of the type of node. On Azure Kubernetes Service (AKS), the default limit is 30 pods per node but it can be increased up to 250.
The key thing about pods is that when a pod does contain multiple containers, all of them are always run on a single worker node—it never spans multiple worker nodes, as shown in figure 3.1.
I'm making the assumption here that you've deployed a pod to the cluster, and now you're trying to query the node it's running on.
This is actually two distinct problems:
That is, how can a pod identify the concrete Kubernetes node it is running on
There's two ways you can do this, but they both involved the downward API. You can either push the pod name down or push the node name down (or both). You need to do this first to enable the lookups you need. So the pod running the kubernetes python client needs to be deployed like so:
apiVersion: v1
kind: Pod
metadata:
name: example-app
spec:
containers:
- name: python-kubernetes-client
image: my-image
command: [ "start_my_app" ]
env:
- name: MY_NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: MY_POD_NAME
valueFrom:
fieldRef:
fieldPath: metadata.name
restartPolicy: Never
Okay, so now you have the pod information and the node information available to your running pod.
and then query for a full list of pods on this node only
Now that you know the node name the pod is running on, querying for the pods running on it is relatively straightforward using the python API:
#!/usr/bin/env python
from kubernetes import client, config
import os
def main():
# it works only if this script is run by K8s as a POD
config.load_incluster_config()
# use this outside pods
# config.load_kube_config()
# grab the node name from the pod environment vars
node_name = os.environ.get('MY_NODE_NAME', None)
v1 = client.CoreV1Api()
print("Listing pods with their IPs on node: ", node_name)
# field selectors are a string, you need to parse the fields from the pods here
field_selector = 'spec.nodeName='+node_name
ret = v1.list_pod_for_all_namespaces(watch=False, field_selector=field_selector)
for i in ret.items:
print("%s\t%s\t%s" %
(i.status.pod_ip, i.metadata.namespace, i.metadata.name))
if __name__ == '__main__':
main()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With