From 7da6054f066a0e9a0dfcd60b36363eb23d7831f8 Mon Sep 17 00:00:00 2001 From: Prithak Sharma Date: Mon, 18 Sep 2023 08:04:37 +0100 Subject: [PATCH] feat: add support for --context flag - add support for --context flag so that Kubernetes context can be passed as a parameter --- pkg/cmd/root.go | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/pkg/cmd/root.go b/pkg/cmd/root.go index e2565ee..9957f61 100644 --- a/pkg/cmd/root.go +++ b/pkg/cmd/root.go @@ -25,6 +25,7 @@ var ( serializer *kjson.Serializer scanTimeOut int scanURL string + kubeContext string // kubernetes context to use that is present in the kubeconfig ) func Execute() { @@ -33,8 +34,11 @@ func Execute() { rootCmd.PersistentFlags().IntVarP(&scanTimeOut, "timeout", "t", 120, "Scan timeout in seconds") rootCmd.PersistentFlags().StringVarP(&scanURL, "url", "u", "https://v2.kubesec.io", "URL to send the request for scanning") rootCmd.PersistentFlags().StringVarP(&kubeconfig, "kubeconfig", "k", "", "Path to kubeconfig, overrides KUBECONFIG environment variable") + rootCmd.PersistentFlags().StringVarP(&kubeContext, "context", "c", "", "kubernetes context to use in kubeconfig") - serializer = kjson.NewYAMLSerializer(kjson.DefaultMetaFactory, scheme.Scheme, scheme.Scheme) + serializer = kjson.NewSerializerWithOptions(kjson.DefaultMetaFactory, scheme.Scheme, scheme.Scheme, kjson.SerializerOptions{ + Yaml: true, + }) // commands rootCmd.AddCommand(versionCmd) @@ -56,6 +60,7 @@ func newKubeClient(kubeconfig string) (*kubernetes.Clientset, error) { } clientset, err := kubernetes.NewForConfig(config) + if err != nil { return nil, fmt.Errorf("Unable to create a new Clienset: %w", err) } @@ -73,6 +78,11 @@ func newClientConfig(kubeconfig string) (*rest.Config, error) { configOverrides := &clientcmd.ConfigOverrides{} + // if kubeContext is not empty, it will override the current context + if kubeContext != "" { + configOverrides.CurrentContext = kubeContext + } + kubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides) config, err := kubeConfig.ClientConfig()