How to find all Kubernetes Pods on the same node from a Pod using the official Python client?

10/12/2018

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?

-- TheDiveO
kubernetes
python

1 Answer

10/12/2018

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()
-- jaxxstorm
Source: StackOverflow