gokubernetesclient-gokubernetes-go-client

How to access my pod in k8s using go-client


I am using go-client to access k8s resources in my environment. There are APIs to get/list pods, namespaces, etc.

How do I access the pod that I am currently running on?


Solution

  • You can Expose Pod Information to Containers Through Environment Variables using pod fields:

    apiVersion: v1
    kind: Pod
    metadata:
      name: dapi-envars-fieldref
    spec:
      containers:
        - name: test-container
          ...
          ...
          env:
            - name: MY_NODE_NAME
              valueFrom:
                fieldRef:
                  fieldPath: spec.nodeName
            - name: MY_POD_NAME
              valueFrom:
                fieldRef:
                  fieldPath: metadata.name
            - name: MY_POD_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: MY_POD_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: MY_POD_SERVICE_ACCOUNT
              valueFrom:
                fieldRef:
                  fieldPath: spec.serviceAccountName
      restartPolicy: Never
    

    then simply look up these env vars in your Go code:

    log.Printf("MY_POD_NAME: %q", os.Getenv("MY_POD_NAME"))