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 ?
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;
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With