javaspring-bootkubernetesspring-cloud

Get k8s namespace inside spring boot application?


I have a spring boot application ( set of services ) deployed in k8s cluster. For micromter metrics I need to dynamically get the namespace this application runs so that i can add that as tag in metrics. Following is my custom tag creation bean

@Bean
public MeterRegistryCustomizer<MeterRegistry> metricsCommonTags() {
return registry -> {
  String hostname = getHostName();
  registry.config().commonTags(TAG_NAME_INSTANCE,hostname);

  final String applicationName = environment.getProperty(SPRING_BOOT_APPLICATION_NAME_PROPERTY_KEY);
  registry.config().commonTags(TAG_NAME_APPLICATION, applicationName);
  registry.config().commonTags(TAG_NAME_APP, applicationName);

  registry.config().commonTags(TAG_NAME_KUBE_NAME_SPACE, getKubeNamespace());
};

}

currently getKubeNamespace return hard coded value. How can i get which namespace this pod is running ?


Solution

  • Kubernetes has a feature for accessing such fields, it's called the Downward API .

    With the help of the Downward API the pod's namespace can be accessed by defining an environment variable in the pod's definition like this:

    - name: NAMESPACE
      valueFrom:
        fieldRef:
          fieldPath: metadata.namespace
    

    After that, the environment variable can be read by Spring:

    @Value("${NAMESPACE}")
    private String namespace;