jws
jws

Reputation: 2774

How to get self pod with kubernetes client-go

I have a kubernetes service, written in Go, and am using client-go to access the kubernetes apis.

I need the Pod of the service's own pod.

The PodInterface allows me to iterate all pods, but what I need is a "self" concept to get the currently running pod that is executing my code.

It appears by reading /var/run/secrets/kubernetes.io/serviceaccount/namespace and searching pods in the namespace for the one matching hostname, I can determine the "self" pod.

Is this the proper solution?

Upvotes: 3

Views: 2015

Answers (1)

Kamol Hasan
Kamol Hasan

Reputation: 13546

Expose the POD_NAME and POD_NAMESPACE to your pod as environment variables. Later use those values to get your own pod object.

apiVersion: v1
kind: Pod
metadata:
  name: dapi-envars-fieldref
spec:
  containers:
    - name: test-container
      image: k8s.gcr.io/busybox
      command: [ "sh", "-c"]
      args:
      - while true; do
          echo -en '\n';
          printenv MY_POD_NAME MY_POD_NAMESPACE;
          sleep 10;
        done;
      env:
        - name: MY_POD_NAME
          valueFrom:
            fieldRef:
              fieldPath: metadata.name
        - name: MY_POD_NAMESPACE
          valueFrom:
            fieldRef:
              fieldPath: metadata.namespace
  restartPolicy: Never

Ref: environment-variable-expose-pod-information

Upvotes: 4

Related Questions