diff --git a/pkg/cli/connect_helm.go b/pkg/cli/connect_helm.go index fe128629e..873bb9ec7 100644 --- a/pkg/cli/connect_helm.go +++ b/pkg/cli/connect_helm.go @@ -88,6 +88,11 @@ func ConnectHelm(ctx context.Context, options *ConnectOptions, globalFlags *flag } func (cmd *connectHelm) connect(ctx context.Context, vCluster *find.VCluster, command []string) error { + if connected, _ := checkIfAlreadyConnected(ctx, vCluster); connected { + cmd.Log.Infof("already connected to vcluster %q", vCluster.Name) + return nil + } + // prepare clients and find vcluster err := cmd.prepare(ctx, vCluster) if err != nil { @@ -693,3 +698,32 @@ func (cmd *connectHelm) waitForVCluster(ctx context.Context, vKubeConfig clientc return nil } + +func checkIfAlreadyConnected(ctx context.Context, vCluster *find.VCluster) (bool, error) { + currentContext, _, err := find.CurrentContext() + if err != nil { + return false, err + } + if currentContext == find.VClusterContextName(vCluster.Name, vCluster.Namespace, vCluster.Context) { + kubeConfig, err := vCluster.ClientFactory.ClientConfig() + if err != nil { + return false, err + } + + vKubeClient, err := kubernetes.NewForConfig(kubeConfig) + if err != nil { + return false, err + } + + timeoutCtx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + // Use the timeout context in the Get call + _, err = vKubeClient.CoreV1().ServiceAccounts("default").Get(timeoutCtx, "default", metav1.GetOptions{}) + if err != nil { + return false, err + } + return true, nil + } + return false, nil +}