@@ -21,6 +21,7 @@ import (
21
21
"fmt"
22
22
"os"
23
23
"runtime"
24
+ "strings"
24
25
25
26
// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
26
27
// to ensure that exec-entrypoint and run can make use of them.
46
47
setupLog = ctrl .Log .WithName ("setup" )
47
48
)
48
49
50
+ const (
51
+ serviceAccountNamespaceFile = "/var/run/secrets/kubernetes.io/serviceaccount/namespace"
52
+ )
53
+
49
54
func init () {
50
55
utilruntime .Must (clientgoscheme .AddToScheme (scheme ))
51
56
@@ -134,12 +139,20 @@ func main() {
134
139
}
135
140
136
141
// 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
139
145
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 ))
143
156
}
144
157
return ns
145
158
}
0 commit comments