How to get the current namespace in a Pod?
Asked Answered
V

2

25

One way I could think of is to set an environment which value is the namespace of the Pod when defining the Pod.
Getting the namespace dynamically without requiring changes for Pod will be better because it lessens the burden of constructing a Pod.

So is there a way to get current namespace in a Pod?

Vulcan answered 5/9, 2017 at 2:17 Comment(0)
N
55

Try the file:

/var/run/secrets/kubernetes.io/serviceaccount/namespace
Nautilus answered 5/9, 2017 at 2:25 Comment(0)
W
7

you don't need to set a static namespace env variable in the pod spec if you want to use env variables, you can use the "Downward API" for letting k8s fill it dynamically with the current namespace. See https://kubernetes.io/docs/tasks/inject-data-application/environment-variable-expose-pod-information/#the-downward-api

Witling answered 6/9, 2017 at 12:9 Comment(3)
Yes, but it also needs to set an environment variable when defining the Pod Spec though the value is derived from Pod metadata or from serviceAccount file. These methods seem similar because they all try to get the current namespace from the serviceAccountFile. Thanks very much and this gives me another solution which I didn't think of :DVulcan
@Vulcan which solution did you end up following?Hopple
@Hopple use /var/run/secrets/kubernetes.io/serviceaccount/namespace as the answer acceptedVulcan

© 2022 - 2024 — McMap. All rights reserved.