24

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?

flyer
  • 9,280
  • 11
  • 46
  • 62

2 Answers2

51

Try the file:

/var/run/secrets/kubernetes.io/serviceaccount/namespace
Graham Dumpleton
  • 57,726
  • 6
  • 119
  • 134
6

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

slintes
  • 740
  • 5
  • 9
  • 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 :D – flyer Sep 07 '17 at 02:32
  • @flyer which solution did you end up following? – user2700022 Dec 07 '19 at 12:50
  • @user2700022 use `/var/run/secrets/kubernetes.io/serviceaccount/namespace` as the answer accepted – flyer Dec 08 '19 at 01:43