Skip to content

Commit cff3f84

Browse files
committed
Use installed namespace if WATCH_NAMESPACE not set
Signed-off-by: Joel Smith <joelsmith@redhat.com>
1 parent c39d74a commit cff3f84

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

main.go

+18-5
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import (
2121
"fmt"
2222
"os"
2323
"runtime"
24+
"strings"
2425

2526
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
2627
// to ensure that exec-entrypoint and run can make use of them.
@@ -46,6 +47,10 @@ var (
4647
setupLog = ctrl.Log.WithName("setup")
4748
)
4849

50+
const (
51+
serviceAccountNamespaceFile = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
52+
)
53+
4954
func init() {
5055
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
5156

@@ -134,12 +139,20 @@ func main() {
134139
}
135140

136141
// getWatchNamespace returns the namespace the operator should be watching for changes
137-
// it tries to read this information from env variable `WATCH_NAMESPACE`
138-
// if not set, namespace `keda` is used
142+
// It tries to read this information from env variable `WATCH_NAMESPACE`. If not set
143+
// or empty, it attempts to determine which namespace it is running in via the
144+
// automounted service account data. If unavailable, namespace `keda` is used
139145
func getWatchNamespace() string {
140-
ns, found := os.LookupEnv("WATCH_NAMESPACE")
141-
if !found {
142-
return "keda"
146+
var ns string
147+
var found bool
148+
if ns, found = os.LookupEnv("WATCH_NAMESPACE"); found && len(ns) > 0 {
149+
setupLog.Info(fmt.Sprintf("Using watch namespace '%s' from environment variable WATCH_NAMESPACE", ns))
150+
} else if nsBytes, err := os.ReadFile(serviceAccountNamespaceFile); err == nil {
151+
ns = strings.TrimSpace(string(nsBytes))
152+
setupLog.Info(fmt.Sprintf("Using watch namespace '%s' from service account namespace specified in %s", ns, serviceAccountNamespaceFile))
153+
} else {
154+
ns = "keda"
155+
setupLog.Info(fmt.Sprintf("Using default watch namespace '%s'", ns))
143156
}
144157
return ns
145158
}

0 commit comments

Comments
 (0)