如何使用 go-client 在 k8s 中访问我的 pod

How to access my pod in k8s using go-client

我正在使用 go-client 访问我环境中的 k8s 资源。有 get/list pods、命名空间等的 API

如何访问我目前 运行 所在的 pod?

你可以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

然后只需在您的 Go 代码中查找这些环境变量:

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