Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 507
Viraj Avatar asked Feb 04 '26 11:02

Viraj


2 Answers

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;
like image 121
csenga Avatar answered Feb 07 '26 00:02

csenga


When using spring cloud like:

dependencyManagement {
  imports {
    mavenBom("org.springframework.cloud:spring-cloud-dependencies:2023.0.3")
  }
}

dependencies {
  ...
  implementation("org.springframework.cloud:spring-cloud-starter-kubernetes-client-config")
  ...
}

You can retrieve a bean of KubernetesClientPodUtils with:

@Autowired
KubernetesClientPodUtils k8sClient;

Then the namespace with:

String namespace = k8sClient.currentPod().get().getMetadata().getNamespace();

Also you can use:

@Autowired
KubernetesNamespaceProvider k8sNsProvider;
...
String namespace = k8sNsProvider.getNamespace();
like image 40
Geoffrey Avatar answered Feb 06 '26 23:02

Geoffrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!