I'm writing an operator using Go and Operator-SDK. I would like to assign to variable a namespace name in which operator is running.
- How to access/get operator's namespace?
- I'm using this method to run/debug operator in VSCode and test it locally on Kind/minikube cluster. How to configure VSCode to simulate a namespace name in which operator will be running?
How to get operator's namespace?
You have a couple of options.
Using an environment variable
You can set an environment variable to the name of the namespace in which your operator is deployed by using the downward api. That allows you to put metadata about the pod or cluster into environment variables. For example:
Using serviceaccount information
If you examine a container running in Kubernetes, you will find a directory
/run/secrets/kubernetes.io/serviceaccountthat contains the following entries:You can read the namespace from
/run/secrets/kubernetes.io/serviceaccount/namespaceSetting namespace name during testing
If you use the first option above (exposing the namespace as an environment variable), this makes it trivially easy to provide this information during test -- just set an environment variable locally with the same name. E.g.: