@@ -18,6 +18,7 @@ import (
18
18
"k8s.io/apimachinery/pkg/util/intstr"
19
19
"k8s.io/apimachinery/pkg/util/wait"
20
20
"k8s.io/client-go/kubernetes"
21
+ "k8s.io/client-go/tools/clientcmd"
21
22
"k8s.io/client-go/tools/portforward"
22
23
"k8s.io/client-go/transport/spdy"
23
24
"k8s.io/utils/pointer"
@@ -299,3 +300,43 @@ func enableLocalForwardForPod(
299
300
}
300
301
return forwardedPorts [0 ].Local , stopChan , nil
301
302
}
303
+
304
+ // GetClientConfig replicates the behavior of clientcmd.BuildConfigFromFlags with zap logging and
305
+ // support for an optional config context. If path is not provided, use of in-cluster config will
306
+ // be attempted.
307
+ func GetClientConfig (log logging.Logger , path string , context string ) (* restclient.Config , error ) {
308
+ if len (path ) == 0 {
309
+ log .Warn ("--kubeconfig not set. Using the inClusterConfig. This might not work." )
310
+ kubeconfig , err := restclient .InClusterConfig ()
311
+ if err == nil {
312
+ return kubeconfig , nil
313
+ }
314
+ log .Warn ("failed to create inClusterConfig, falling back to default config" ,
315
+ zap .Error (err ),
316
+ )
317
+ }
318
+ overrides := & clientcmd.ConfigOverrides {}
319
+ if len (context ) > 0 {
320
+ overrides .CurrentContext = context
321
+ }
322
+ return clientcmd .NewNonInteractiveDeferredLoadingClientConfig (
323
+ & clientcmd.ClientConfigLoadingRules {
324
+ ExplicitPath : path ,
325
+ },
326
+ overrides ,
327
+ ).ClientConfig ()
328
+ }
329
+
330
+ // GetClientset returns a kubernetes clientset for the provided kubeconfig path and context.
331
+ func GetClientset (log logging.Logger , path string , context string ) (* kubernetes.Clientset , error ) {
332
+ clientConfig , err := GetClientConfig (log , path , context )
333
+ if err != nil {
334
+ return nil , fmt .Errorf ("failed to get client config: %w" , err )
335
+ }
336
+
337
+ clientset , err := kubernetes .NewForConfig (clientConfig )
338
+ if err != nil {
339
+ return nil , fmt .Errorf ("failed to create clientset: %w" , err )
340
+ }
341
+ return clientset , nil
342
+ }
0 commit comments