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.
You have a couple of options.
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:
apiVersion: v1
kind: Pod
metadata:
name: downard-api-example
spec:
containers:
- name: test-container
image: docker.io/alpine:latest
env:
- name: MY_NAMESPACE
valueFrom:
fieldRef:
fieldPath: metadata.namespace
command:
- sh
- -c
- |
while true; do
echo -en '\n'
printenv MY_NAMESPACE
sleep 10
done;
If you examine a container running in Kubernetes, you will find a directory /run/secrets/kubernetes.io/serviceaccount
that contains the following entries:
ca.crt
namespace
token
You can read the namespace from /run/secrets/kubernetes.io/serviceaccount/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?
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.:
export MY_NAMESPACE=some-namespace-name