Romain Pelissier
Romain Pelissier

Reputation: 11

How to detect the current node where a pod is running in python

So I am not a good coder in python or an kubernetes expert but I have a project that need to do this:

Right now, I have only in python a way to connect to the K8s api and get the list of nodes of a cluster but I do not found a way to detect while running as a pod, which node the pod is currently running. Found some infos here https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/CoreV1Api.md#read_namespaced_pod but not sure how to combine runing the code in a pod and getting the pod own info.. I saw this also how to get the host name of the node where a POD is running from within POD but not sure if I have to add something to the pod or the info comes as a environement variable already in a pod.

Upvotes: 1

Views: 591

Answers (1)

Amila Senadheera
Amila Senadheera

Reputation: 13265

You can use the downward API to get pod details to specific container as below:

apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: my-daemon-set
  namespace: my-namespace
spec:
  selector:
    matchLabels:
      name: app-name
  template:
    metadata:
      labels:
        name: app-name
    spec:
      containers:
      - name: my-image-name
        image: my-image:v1
        env:
        - name: MY_NODE_NAME
          valueFrom:
            fieldRef:
              fieldPath: spec.nodeName
        resources:
          limits:
            memory: 200Mi
          requests:
            cpu: 100m
            memory: 200Mi

More info in Expose Pod Information to Containers Through Environment Variables

Upvotes: 0

Related Questions