Get the namespace of k8s cluster-scoped operator

28 Views Asked by At

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.

  1. How to access/get operator's namespace?
  2. 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?
1

There are 1 best solutions below

0
larsks On BEST ANSWER

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:

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;

Using serviceaccount information

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

Setting namespace name during testing

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