Kubernetes:如何使用 K8 的 API 从代码访问当前 运行 pod 的标签值?

Kubernetes: How to access a label value of the current running pod from code using K8's API?

假设我有一个 Kubernetes 集群,其中有 3 个 pods,每个 pod 都有自己的标签值 'name',我真正想要的是每次我 run/open 我的应用程序,我会在控制台输出中看到 pod 的名称(因此它的标签值)。 当然,output/value 每次都可能不同,具体取决于使用的是哪个 pod。

那么,有什么方法可以从代码中访问应用程序 (pod) 运行 的 pod 标签的值吗?

顺便说一句,我的应用程序是基于Java(Spring Boot)的。

谢谢。

您可以使用 Kubernete 的 Downward API 将 Pod 属性传送到 pods 内的容器,而无需使用 Kubernete 的 REST API。来自文档:

It is sometimes useful for a container to have information about itself, but we want to be careful not to over-couple containers to Kubernetes. The downward API allows containers to consume information about themselves or the system and expose that information how they want it, without necessarily coupling to the Kubernetes client or REST API.