<p>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</p>
<pre><code>@Bean
public MeterRegistryCustomizer&lt;MeterRegistry&gt; metricsCommonTags() {
return registry -&gt; {
  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());
};
</code></pre>
<p>}</p>
<p>currently <code>getKubeNamespace</code> return hard coded value. How can i get which namespace this pod is running ?</p>

<p>Kubernetes has a feature for accessing such fields, it's called the <a href="https://kubernetes.io/docs/tasks/inject-data-application/downward-api-volume-expose-pod-information/" rel="nofollow noreferrer">Downward API</a> .</p>
<p>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:</p>
<pre><code>- name: NAMESPACE
  valueFrom:
    fieldRef:
      fieldPath: metadata.namespace
</code></pre>
<p>After that, the environment variable can be read by Spring:</p>
<pre><code>@Value(&quot;${NAMESPACE}&quot;)
private String namespace;
</code></pre>
