<p>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?</p>

<p>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.</p>

<p>This is actually two distinct problems:</p>

<blockquote>
  <p>That is, how can a pod identify the concrete Kubernetes node it is running on</p>
</blockquote>

<p>There's two ways you can do this, <a href="https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/" rel="noreferrer">but they both involved the downward API</a>. 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:</p>

<pre><code>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
</code></pre>

<p>Okay, so now you have the pod information and the node information available to your running pod. </p>

<blockquote>
  <p>and then query for a full list of pods on this node only</p>
</blockquote>

<p>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:</p>

<pre><code>#!/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()
</code></pre>
