From 251d235ae6f5f4dd0cbf1b856cdc0eaa8a9dc654 Mon Sep 17 00:00:00 2001 From: onuryilmaz Date: Fri, 13 Nov 2026 20:33:22 +0100 Subject: [PATCH 1/5] fix(sync): skip contexts with missing authinfo instead of failing When --include-not-ready is set, some ClusterKubeconfigs have contexts in their spec but no corresponding authinfo (e.g. the secret is absent so only partial spec data is present). mergeKubeconfig was returning a fatal error for these, failing the entire sync. Skip such contexts with a debug-level log instead. The authinfo check is applied to both the mergeIdenticalUsers=true and =false paths. Signed-off-by: onuryilmaz --- cmd/sync.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cmd/sync.go b/cmd/sync.go index 3e4971f..9a09db9 100644 --- a/cmd/sync.go +++ b/cmd/sync.go @@ -763,7 +763,8 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap // However, to be safe, generate a new managedAuthName. serverAuth, exists := serverConfig.AuthInfos[serverAuthName] if !exists || serverAuth == nil { - return fmt.Errorf("AuthInfo %s referenced in context %s does not exist or is nil", serverAuthName, serverName) + slog.Debug("skipping context: authinfo missing from server config", "context", serverName, "authinfo", serverAuthName) + continue } uniqueKey := generateAuthInfoKey(serverAuth) hash := sha256.Sum256([]byte(uniqueKey)) @@ -779,6 +780,10 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap if preSeedName, ok := preSeedAuthInfoMap[serverCtx.AuthInfo]; ok { managedAuthInfoName = preSeedName } else { + if _, exists := serverConfig.AuthInfos[serverCtx.AuthInfo]; !exists { + slog.Debug("skipping context: authinfo missing from server config", "context", serverName, "authinfo", serverCtx.AuthInfo) + continue + } managedAuthInfoName = managedNameFunc(serverCtx.AuthInfo) } } From bce64e264d785505dfe4c4aa4421eff52512352a Mon Sep 17 00:00:00 2001 From: onuryilmaz Date: Fri, 13 Nov 2026 20:33:45 +0100 Subject: [PATCH 2/5] feat(sync): zero-flag usage via kubeconfig context and connection header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #79. --greenhouse-cluster-namespace no longer required as a flag. Resolution order: explicit flag → ~/.cloudctl.yaml → namespace of the active Greenhouse context (org name == namespace set by bootstrap). When no context is specified, the current-context from the kubeconfig is used, mirroring kubectl behaviour. Write target defaults to ~/.kube/config when neither --remote-cluster-kubeconfig nor KUBECONFIG is set, so a plain `cloudctl sync` works out of the box after bootstrap. Every sync now prints a one-line connection summary (kubeconfig path, context, namespace) before the cluster list, making it immediately clear which Greenhouse org was synced and where the result was written. Internal cleanups: - resolveDisplayPath delegates to resolveWriteTarget (single path-resolution logic) - resolveDisplayContext + namespaceFromKubeconfig merged into loadKubeconfigContext (single kubeconfig load instead of two) - conn built after file-existence check so error messages always show the real context name instead of "(unknown)" Signed-off-by: onuryilmaz --- cmd/output/interactive_printer.go | 12 +++ cmd/output/plain_printer.go | 9 ++ cmd/output/types.go | 18 +++- cmd/root.go | 10 ++- cmd/sync.go | 136 +++++++++++++++++++++++++----- cmd/sync_test.go | 71 +++++++++++++++- 6 files changed, 224 insertions(+), 32 deletions(-) diff --git a/cmd/output/interactive_printer.go b/cmd/output/interactive_printer.go index 0001b4d..cdc3d45 100644 --- a/cmd/output/interactive_printer.go +++ b/cmd/output/interactive_printer.go @@ -179,6 +179,18 @@ func (p *interactivePrinter) printSyncResult(r SyncResult) error { } total := r.Synced + r.Skipped + r.Failed + if r.Connection != nil { + w("%s %s %s %s %s %s\n", + styleFaint.Render("kubeconfig:"), r.Connection.Kubeconfig, + styleFaint.Render("context:"), styleBold.Render(r.Connection.Context), + styleFaint.Render("namespace:"), styleBold.Render(r.Connection.Namespace), + ) + if r.WriteTarget != "" { + w("%s %s\n", styleFaint.Render("writing: "), r.WriteTarget) + } + w("\n") + } + // Collect only clusters that need attention. var issues []ClusterSyncResult for _, c := range r.Clusters { diff --git a/cmd/output/plain_printer.go b/cmd/output/plain_printer.go index 2b43daf..16d88c4 100644 --- a/cmd/output/plain_printer.go +++ b/cmd/output/plain_printer.go @@ -26,6 +26,15 @@ func (p *plainPrinter) Print(v any) error { case SyncResult: total := t.Synced + t.Skipped + t.Failed + if t.Connection != nil { + w("kubeconfig: %s context: %s namespace: %s\n", + t.Connection.Kubeconfig, t.Connection.Context, t.Connection.Namespace) + if t.WriteTarget != "" { + w("writing: %s\n", t.WriteTarget) + } + w("\n") + } + // List clusters that need attention first. for _, c := range t.Clusters { switch c.Status { diff --git a/cmd/output/types.go b/cmd/output/types.go index 5738d38..db17cf3 100644 --- a/cmd/output/types.go +++ b/cmd/output/types.go @@ -22,10 +22,20 @@ type ClusterSyncResult struct { // SyncResult is the top-level output of the sync command. type SyncResult struct { - Clusters []ClusterSyncResult `json:"clusters" yaml:"clusters"` - Synced int `json:"synced" yaml:"synced"` - Skipped int `json:"skipped" yaml:"skipped"` - Failed int `json:"failed" yaml:"failed"` + // Connection describes where the sync connected to (shown in text output header). + Connection *SyncConnection `json:"connection,omitempty" yaml:"connection,omitempty"` + Clusters []ClusterSyncResult `json:"clusters" yaml:"clusters"` + Synced int `json:"synced" yaml:"synced"` + Skipped int `json:"skipped" yaml:"skipped"` + Failed int `json:"failed" yaml:"failed"` + WriteTarget string `json:"writeTarget,omitempty" yaml:"writeTarget,omitempty"` +} + +// SyncConnection holds the resolved Greenhouse connection details used for a sync. +type SyncConnection struct { + Kubeconfig string `json:"kubeconfig" yaml:"kubeconfig"` + Context string `json:"context" yaml:"context"` + Namespace string `json:"namespace" yaml:"namespace"` } // ClusterVersionResult is the output of the cluster-version command. diff --git a/cmd/root.go b/cmd/root.go index 2af3a95..d9cdd35 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -154,7 +154,10 @@ func setupConfig() error { // First we are trying config provided as a command line parameter. Fail if there was an error // during reading configuration from this specified path. viper.SetConfigFile(configFilePath) - return viper.ReadInConfig() + if err := viper.ReadInConfig(); err != nil { + return fmt.Errorf("failed to read config file %q: %w", configFilePath, err) + } + return nil } else { // Phase 2 // Then we are searching for ".cloudctl.yaml" in current or home directory @@ -194,6 +197,11 @@ func setupConfig() error { } } + if err != nil { + if cf := viper.ConfigFileUsed(); cf != "" { + return fmt.Errorf("failed to read config file %q: %w", cf, err) + } + } return err } diff --git a/cmd/sync.go b/cmd/sync.go index 9a09db9..5dbafba 100644 --- a/cmd/sync.go +++ b/cmd/sync.go @@ -48,10 +48,7 @@ var ( func init() { syncCmd.Flags().StringVarP(&greenhouseClusterKubeconfig, "greenhouse-cluster-kubeconfig", "k", clientcmd.RecommendedHomeFile, "Path to the Greenhouse cluster kubeconfig") syncCmd.Flags().StringVarP(&greenhouseClusterContext, "greenhouse-cluster-context", "c", "", "Context to use from the Greenhouse kubeconfig (defaults to current context)") - syncCmd.Flags().StringVarP(&greenhouseClusterNamespace, "greenhouse-cluster-namespace", "n", "", "Greenhouse organization namespace (required)") - if err := syncCmd.MarkFlagRequired("greenhouse-cluster-namespace"); err != nil { - panic(err) - } + syncCmd.Flags().StringVarP(&greenhouseClusterNamespace, "greenhouse-cluster-namespace", "n", "", "Greenhouse organization namespace") syncCmd.Flags().StringVarP(&remoteClusterKubeconfig, "remote-cluster-kubeconfig", "r", clientcmd.RecommendedHomeFile, "Local kubeconfig file to merge into") syncCmd.Flags().StringVar(&remoteClusterName, "remote-cluster-name", "", "Sync only this cluster by name (default: all ready clusters)") syncCmd.Flags().StringVar(&prefix, "prefix", "cloudctl", "Prefix applied to managed kubeconfig entries to avoid collisions") @@ -100,6 +97,13 @@ local config. Existing non-managed entries are never touched. OIDC credentials are preserved across syncs: id-token and refresh-token are carried forward so you do not need to re-authenticate after every sync. +One-time setup: persist connection defaults in ~/.cloudctl.yaml so you can +run "cloudctl sync" with no flags: + + greenhouse-cluster-namespace: my-org + greenhouse-cluster-context: greenhouse + greenhouse-cluster-kubeconfig: ~/.kube/config + Examples: # Sync all clusters for an organization cloudctl sync -n my-org @@ -113,6 +117,9 @@ Examples: # Preview what would change without writing cloudctl sync -n my-org --dry-run + # No flags after one-time setup via ~/.cloudctl.yaml + cloudctl sync + # Debug mode — shows every cluster/authinfo/context decision on stderr cloudctl sync -n my-org --log-level debug`, RunE: runSync, @@ -133,6 +140,23 @@ func runSync(cmd *cobra.Command, args []string) error { if viper.IsSet("remote-cluster-kubeconfig") && remoteClusterKubeconfig == "" { return fmt.Errorf("--remote-cluster-kubeconfig must not be empty") } + if greenhouseClusterNamespace == "" { + // Fall back to the namespace from the active Greenhouse context (org name == namespace). + // loadKubeconfigContext also resolves the effective context name in one load. + resolvedCtx, ns, err := loadKubeconfigContext(greenhouseClusterContext, greenhouseClusterKubeconfig) + if err != nil { + return fmt.Errorf("greenhouse organization namespace is required: set --greenhouse-cluster-namespace, add 'greenhouse-cluster-namespace: ' to ~/.cloudctl.yaml, or ensure the active context in your kubeconfig has a namespace set (%w)", err) + } + if ns == "" { + return fmt.Errorf("greenhouse organization namespace is required: set --greenhouse-cluster-namespace, add 'greenhouse-cluster-namespace: ' to ~/.cloudctl.yaml, or ensure the active context in your kubeconfig has a namespace set") + } + greenhouseClusterNamespace = ns + // Backfill resolved context so conn and error messages show the real name. + if greenhouseClusterContext == "" { + greenhouseClusterContext = resolvedCtx + } + } + remoteClusterName = viper.GetString("remote-cluster-name") prefix = viper.GetString("prefix") mergeIdenticalUsers = viper.GetBool("merge-identical-users") @@ -157,13 +181,22 @@ func runSync(cmd *cobra.Command, args []string) error { } } - if err := validateAuthType(authType, kubeloginPath); err != nil { - return err + // Resolve the display context name: if not already backfilled by namespace autodetect, + // read current-context from the kubeconfig (one load, no extra I/O on the hot path). + if greenhouseClusterContext == "" { + if resolvedCtx, _, err := loadKubeconfigContext("", greenhouseClusterKubeconfig); err == nil { + greenhouseClusterContext = resolvedCtx + } } - ctxLabel := greenhouseClusterContext - if ctxLabel == "" { - ctxLabel = "(current context)" + conn := &output.SyncConnection{ + Kubeconfig: resolveDisplayPath(greenhouseClusterKubeconfig), + Context: greenhouseClusterContext, + Namespace: greenhouseClusterNamespace, + } + + if err := validateAuthType(authType, kubeloginPath); err != nil { + return err } var ( @@ -171,7 +204,7 @@ func runSync(cmd *cobra.Command, args []string) error { ) centralConfig, err = configWithContext(greenhouseClusterContext, greenhouseClusterKubeconfig) if err != nil { - return fmt.Errorf("failed to build greenhouse kubeconfig (source: %s, context: %s): %w", displayKubeconfig(greenhouseClusterKubeconfig), ctxLabel, err) + return fmt.Errorf("failed to build greenhouse kubeconfig (source: %s, context: %s): %w", conn.Kubeconfig, conn.Context, err) } // Create a scheme and register Greenhouse types. @@ -213,16 +246,21 @@ func runSync(cmd *cobra.Command, args []string) error { ready, notReady := partitionReady(allKubeconfigs) if shouldSkipMerge(ready, notReady, includeNotReady) { - return printer.Print(buildSyncResult(nil, notReady)) + r := buildSyncResult(nil, notReady) + r.Connection = conn + return printer.Print(r) } var localConfig *clientcmdapi.Config if remoteClusterKubeconfig != "" { localConfig, err = clientcmd.LoadFromFile(remoteClusterKubeconfig) + if err != nil { + return fmt.Errorf("failed to load local kubeconfig %q: %w", remoteClusterKubeconfig, err) + } } else { localConfig, err = clientcmd.NewDefaultClientConfigLoadingRules().Load() - } - if err != nil { - return fmt.Errorf("failed to load local kubeconfig: %w", err) + if err != nil { + return fmt.Errorf("failed to load local kubeconfig (%s): %w", displayKubeconfig(""), err) + } } if localConfig == nil { @@ -282,7 +320,9 @@ func runSync(cmd *cobra.Command, args []string) error { err = mergeKubeconfig(localConfig, serverConfig, stubsToPreserve) stopMerge() if err != nil { - _ = printer.Print(buildFailedSyncResult(merged, skipped, err)) + r := buildFailedSyncResult(merged, skipped, err) + r.Connection = conn + _ = printer.Print(r) return fmt.Errorf(`failed to merge ClusterKubeconfig: %w`, err) } @@ -297,11 +337,20 @@ func runSync(cmd *cobra.Command, args []string) error { } if writeErr := writeConfig(localConfig, writeTarget); writeErr != nil { - _ = printer.Print(buildFailedSyncResult(merged, skipped, writeErr)) + r := buildFailedSyncResult(merged, skipped, writeErr) + r.Connection = conn + _ = printer.Print(r) return fmt.Errorf("failed to write merged kubeconfig: %w", writeErr) } - return printer.Print(buildSyncResult(merged, skipped)) + r := buildSyncResult(merged, skipped) + r.Connection = conn + // Only show write target when it differs from the greenhouse kubeconfig source, + // to avoid printing the same path twice. + if writeTarget != conn.Kubeconfig { + r.WriteTarget = writeTarget + } + return printer.Print(r) } // partitionReady splits ClusterKubeconfigs into ready and notReady slices. @@ -780,6 +829,8 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap if preSeedName, ok := preSeedAuthInfoMap[serverCtx.AuthInfo]; ok { managedAuthInfoName = preSeedName } else { + // Only write the context when the authinfo it references exists in serverConfig; + // a context pointing at a missing authinfo would produce a broken kubeconfig entry. if _, exists := serverConfig.AuthInfos[serverCtx.AuthInfo]; !exists { slog.Debug("skipping context: authinfo missing from server config", "context", serverName, "authinfo", serverCtx.AuthInfo) continue @@ -952,12 +1003,51 @@ func resolveWriteTarget(remoteKubeconfig string) (string, error) { if remoteKubeconfig != "" { return remoteKubeconfig, nil } - kc := os.Getenv("KUBECONFIG") - if kc == "" { - return "", fmt.Errorf("cannot determine write target: --remote-cluster-kubeconfig is not set and KUBECONFIG is empty") + // Mirror kubectl's default file selection: first entry in KUBECONFIG, else ~/.kube/config. + if kc := os.Getenv("KUBECONFIG"); kc != "" { + if parts := strings.SplitN(kc, string(os.PathListSeparator), 2); len(parts) > 0 && parts[0] != "" { + return parts[0], nil + } + return "", fmt.Errorf("cannot determine write target: KUBECONFIG=%q contains no usable first path", kc) + } + return clientcmd.RecommendedHomeFile, nil +} + +// resolveDisplayPath returns the concrete file path for the effective kubeconfig. +// When kubeconfigPath is empty (KUBECONFIG env or default), it resolves to the +// first KUBECONFIG entry or ~/.kube/config — the same path that would be read. +// Delegates to resolveWriteTarget so the resolution logic stays in one place. +func resolveDisplayPath(kubeconfigPath string) string { + if kubeconfigPath != "" { + return kubeconfigPath + } + // resolveWriteTarget never returns an error when kubeconfigPath is "". + p, _ := resolveWriteTarget("") + return p +} + +// loadKubeconfigContext resolves the active context name and its namespace from +// the given kubeconfig in a single load. When contextName is explicitly provided +// only the namespace lookup uses the file; otherwise both are read from +// current-context. Returns ("", "", nil) when the context has no namespace set. +func loadKubeconfigContext(contextName, kubeconfigPath string) (activeContext, namespace string, err error) { + var loadingRules *clientcmd.ClientConfigLoadingRules + if kubeconfigPath != "" { + loadingRules = &clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfigPath} + } else { + loadingRules = clientcmd.NewDefaultClientConfigLoadingRules() + } + cfg, err := loadingRules.Load() + if err != nil { + return "", "", fmt.Errorf("failed to load kubeconfig: %w", err) + } + activeContext = contextName + if activeContext == "" { + activeContext = cfg.CurrentContext } - if parts := strings.SplitN(kc, string(os.PathListSeparator), 2); len(parts) > 0 && parts[0] != "" { - return parts[0], nil + ctx, ok := cfg.Contexts[activeContext] + if !ok || ctx == nil { + return activeContext, "", nil } - return "", fmt.Errorf("cannot determine write target: KUBECONFIG=%q contains no usable first path", kc) + return activeContext, ctx.Namespace, nil } diff --git a/cmd/sync_test.go b/cmd/sync_test.go index 07f7446..ac03846 100644 --- a/cmd/sync_test.go +++ b/cmd/sync_test.go @@ -1031,10 +1031,10 @@ func TestWriteTargetFromKUBECONFIG(t *testing.T) { wantErrSubs: "contains no usable first path", }, { - name: "empty remote: KUBECONFIG also empty yields error", - remoteKC: "", - kubeconfig: "", - wantErrSubs: "KUBECONFIG is empty", + name: "empty remote: KUBECONFIG also empty falls back to default", + remoteKC: "", + kubeconfig: "", + wantTarget: clientcmd.RecommendedHomeFile, }, } @@ -1242,3 +1242,66 @@ func TestIncludeNotReady_BypassesEarlyReturnWhenAllNotReady(t *testing.T) { g.Expect(shouldSkipMerge(ready, notReady, false)).To(BeTrue(), "without flag: must skip merge when all clusters not-ready") g.Expect(shouldSkipMerge(ready, notReady, true)).To(BeFalse(), "with flag: must not skip merge when all clusters not-ready") } + +func TestLoadKubeconfigContext(t *testing.T) { + g := NewWithT(t) + + // Write a temp kubeconfig with a context that has a namespace. + cfg := clientcmdapi.NewConfig() + cfg.Clusters["gh"] = &clientcmdapi.Cluster{Server: "https://greenhouse.example.com"} + cfg.AuthInfos["gh-user"] = &clientcmdapi.AuthInfo{} + cfg.Contexts["greenhouse-my-org"] = &clientcmdapi.Context{ + Cluster: "gh", + AuthInfo: "gh-user", + Namespace: "my-org", + } + cfg.CurrentContext = "greenhouse-my-org" + + tmpFile := filepath.Join(t.TempDir(), "kubeconfig") + g.Expect(clientcmd.WriteToFile(*cfg, tmpFile)).To(Succeed()) + + // Default context: both context name and namespace are returned. + activeCtx, ns, err := loadKubeconfigContext("", tmpFile) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(activeCtx).To(Equal("greenhouse-my-org")) + g.Expect(ns).To(Equal("my-org")) + + // Explicit context name works too. + activeCtx, ns, err = loadKubeconfigContext("greenhouse-my-org", tmpFile) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(activeCtx).To(Equal("greenhouse-my-org")) + g.Expect(ns).To(Equal("my-org")) + + // Context with no namespace returns empty namespace, no error. + cfg.Contexts["no-ns"] = &clientcmdapi.Context{Cluster: "gh", AuthInfo: "gh-user"} + g.Expect(clientcmd.WriteToFile(*cfg, tmpFile)).To(Succeed()) + activeCtx, ns, err = loadKubeconfigContext("no-ns", tmpFile) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(activeCtx).To(Equal("no-ns")) + g.Expect(ns).To(BeEmpty()) +} + +func TestSyncCmd_MissingNamespaceError(t *testing.T) { + g := NewWithT(t) + + // A kubeconfig whose active context has no namespace — autodetect yields "". + cfg := clientcmdapi.NewConfig() + cfg.Clusters["gh"] = &clientcmdapi.Cluster{Server: "https://greenhouse.example.com"} + cfg.AuthInfos["gh-user"] = &clientcmdapi.AuthInfo{} + cfg.Contexts["ctx-no-ns"] = &clientcmdapi.Context{Cluster: "gh", AuthInfo: "gh-user"} + cfg.CurrentContext = "ctx-no-ns" + tmpFile := filepath.Join(t.TempDir(), "kubeconfig") + g.Expect(clientcmd.WriteToFile(*cfg, tmpFile)).To(Succeed()) + + // loadKubeconfigContext returns empty namespace for a context without one. + _, ns, err := loadKubeconfigContext("", tmpFile) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(ns).To(BeEmpty(), "context without namespace must yield empty string") + + // The error message produced when namespace is still "" after autodetect + // must mention all three resolution paths. + errMsg := "greenhouse organization namespace is required: set --greenhouse-cluster-namespace, add 'greenhouse-cluster-namespace: ' to ~/.cloudctl.yaml, or ensure the active context in your kubeconfig has a namespace set" + g.Expect(errMsg).To(ContainSubstring("--greenhouse-cluster-namespace")) + g.Expect(errMsg).To(ContainSubstring("~/.cloudctl.yaml")) + g.Expect(errMsg).To(ContainSubstring("namespace")) +} From 7c117e7607cda09c2f10ca9d1bfe135d84939949 Mon Sep 17 00:00:00 2001 From: onuryilmaz Date: Sat, 14 Nov 2026 11:07:58 +0100 Subject: [PATCH 3/5] fix(sync): show full KUBECONFIG source list in connection header resolveDisplayPath reported only the first file from a multi-file KUBECONFIG, so the header could point to the wrong source when the Greenhouse context lived in a later file. Replace with resolveDisplaySources, which returns the full colon-separated KUBECONFIG list verbatim. The write target (first entry, kubectl convention) is resolved separately and shown on the "writing:" line only when it is not already represented in the source list (checked via isWriteTargetInSources). Signed-off-by: onuryilmaz --- cmd/sync.go | 37 +++++++++++++++++--------- cmd/sync_test.go | 69 ++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 94 insertions(+), 12 deletions(-) diff --git a/cmd/sync.go b/cmd/sync.go index 5dbafba..b7f68b0 100644 --- a/cmd/sync.go +++ b/cmd/sync.go @@ -190,7 +190,7 @@ func runSync(cmd *cobra.Command, args []string) error { } conn := &output.SyncConnection{ - Kubeconfig: resolveDisplayPath(greenhouseClusterKubeconfig), + Kubeconfig: resolveDisplaySources(greenhouseClusterKubeconfig), Context: greenhouseClusterContext, Namespace: greenhouseClusterNamespace, } @@ -345,9 +345,10 @@ func runSync(cmd *cobra.Command, args []string) error { r := buildSyncResult(merged, skipped) r.Connection = conn - // Only show write target when it differs from the greenhouse kubeconfig source, - // to avoid printing the same path twice. - if writeTarget != conn.Kubeconfig { + // Show write target only when it is not already expressed by conn.Kubeconfig. + // For a single path they are equal; for a multi-file KUBECONFIG list the write + // target (first entry) is a subset of the list, so we check containment. + if !isWriteTargetInSources(writeTarget, conn.Kubeconfig) { r.WriteTarget = writeTarget } return printer.Print(r) @@ -1013,17 +1014,29 @@ func resolveWriteTarget(remoteKubeconfig string) (string, error) { return clientcmd.RecommendedHomeFile, nil } -// resolveDisplayPath returns the concrete file path for the effective kubeconfig. -// When kubeconfigPath is empty (KUBECONFIG env or default), it resolves to the -// first KUBECONFIG entry or ~/.kube/config — the same path that would be read. -// Delegates to resolveWriteTarget so the resolution logic stays in one place. -func resolveDisplayPath(kubeconfigPath string) string { +// resolveDisplaySources returns the kubeconfig source description for the connection header. +// When kubeconfigPath is explicit it is returned as-is. When KUBECONFIG is set the full +// colon-separated list is returned so multi-file setups are not misrepresented. Otherwise +// ~/.kube/config is returned. +func resolveDisplaySources(kubeconfigPath string) string { if kubeconfigPath != "" { return kubeconfigPath } - // resolveWriteTarget never returns an error when kubeconfigPath is "". - p, _ := resolveWriteTarget("") - return p + if kc := os.Getenv("KUBECONFIG"); kc != "" { + return kc + } + return clientcmd.RecommendedHomeFile +} + +// isWriteTargetInSources reports whether writeTarget is already represented by the +// sources string (which may be a single path or a colon-separated list). +func isWriteTargetInSources(writeTarget, sources string) bool { + for _, p := range strings.Split(sources, string(os.PathListSeparator)) { + if p == writeTarget { + return true + } + } + return false } // loadKubeconfigContext resolves the active context name and its namespace from diff --git a/cmd/sync_test.go b/cmd/sync_test.go index ac03846..3278a09 100644 --- a/cmd/sync_test.go +++ b/cmd/sync_test.go @@ -1056,6 +1056,75 @@ func TestWriteTargetFromKUBECONFIG(t *testing.T) { } } +func TestResolveDisplaySources(t *testing.T) { + sep := string(os.PathListSeparator) + + tests := []struct { + name string + explicitPath string + kubeconfig string + wantSources string + }{ + { + name: "explicit path returned as-is", + explicitPath: "/explicit/kubeconfig", + kubeconfig: "/env/kubeconfig", + wantSources: "/explicit/kubeconfig", + }, + { + name: "single KUBECONFIG entry returned as-is", + explicitPath: "", + kubeconfig: "/single/kubeconfig", + wantSources: "/single/kubeconfig", + }, + { + name: "multi-file KUBECONFIG: full list returned", + explicitPath: "", + kubeconfig: "/first" + sep + "/second" + sep + "/third", + wantSources: "/first" + sep + "/second" + sep + "/third", + }, + { + name: "empty KUBECONFIG falls back to default", + explicitPath: "", + kubeconfig: "", + wantSources: clientcmd.RecommendedHomeFile, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + g := NewWithT(t) + t.Setenv("KUBECONFIG", tc.kubeconfig) + g.Expect(resolveDisplaySources(tc.explicitPath)).To(Equal(tc.wantSources)) + }) + } +} + +func TestIsWriteTargetInSources(t *testing.T) { + sep := string(os.PathListSeparator) + + tests := []struct { + name string + writeTarget string + sources string + want bool + }{ + {"single match", "/a", "/a", true}, + {"single no match", "/b", "/a", false}, + {"multi: first matches", "/a", "/a" + sep + "/b" + sep + "/c", true}, + {"multi: middle matches", "/b", "/a" + sep + "/b" + sep + "/c", true}, + {"multi: last matches", "/c", "/a" + sep + "/b" + sep + "/c", true}, + {"multi: no match", "/d", "/a" + sep + "/b" + sep + "/c", false}, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + g := NewWithT(t) + g.Expect(isWriteTargetInSources(tc.writeTarget, tc.sources)).To(Equal(tc.want)) + }) + } +} + func TestInjectNotReadyStubs_PreservesLocalEntries(t *testing.T) { g := NewWithT(t) From d140a6c53e3c204dee97a290ff85856718ccf64e Mon Sep 17 00:00:00 2001 From: onuryilmaz Date: Sat, 14 Nov 2026 11:15:02 +0100 Subject: [PATCH 4/5] fix(sync): preserve existing entries for contexts with missing authinfo When a ClusterKubeconfig had contexts but no matching authinfo (e.g. a partially-ready cluster under --include-not-ready), the context was already skipped in the merge loop. However the cleanup pass then saw the context's authinfo as unmapped and deleted the existing local managed context, leaving the kubeconfig in a worse state than before. Track skipped server-side contexts in skippedServerContexts and check this set in the cleanup pass before deleting a context as "unmapped authinfo", preserving the existing local entry instead. Also expand leading "~/" in kubeconfig paths read from ~/.cloudctl.yaml (shell tilde-expansion does not apply inside config files). Add expandTilde helper in root.go; update the help example to note that tilde is supported. Signed-off-by: onuryilmaz --- cmd/root.go | 21 ++++++++++++++++++--- cmd/sync.go | 16 +++++++++++++++- 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index d9cdd35..88e9802 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -94,15 +94,30 @@ func init() { // viperKey is the viper key for the flag (e.g. "kubeconfig", "greenhouse-cluster-kubeconfig"). // When the key was not explicitly set by the user (via flag, CLOUDCTL_* env var, or config file) // and the standard KUBECONFIG env var is set, it returns "" so that client-go uses its standard -// multi-file loading rules. An explicitly provided value is always returned as-is. +// multi-file loading rules. An explicitly provided value is always returned as-is, after tilde +// expansion (a leading "~/" is replaced with the user's home directory so that values read from +// ~/.cloudctl.yaml work without shell expansion). func resolveKubeconfig(viperKey, flagValue string) string { if viper.IsSet(viperKey) { - return flagValue + return expandTilde(flagValue) } if os.Getenv("KUBECONFIG") != "" { return "" } - return flagValue + return expandTilde(flagValue) +} + +// expandTilde replaces a leading "~/" with the current user's home directory. +// Paths that do not start with "~/" are returned unchanged. +func expandTilde(path string) string { + if !strings.HasPrefix(path, "~/") { + return path + } + home, err := os.UserHomeDir() + if err != nil { + return path + } + return filepath.Join(home, path[2:]) } // displayKubeconfig returns a human-readable label for the effective kubeconfig source. diff --git a/cmd/sync.go b/cmd/sync.go index b7f68b0..74357d3 100644 --- a/cmd/sync.go +++ b/cmd/sync.go @@ -102,7 +102,7 @@ run "cloudctl sync" with no flags: greenhouse-cluster-namespace: my-org greenhouse-cluster-context: greenhouse - greenhouse-cluster-kubeconfig: ~/.kube/config + greenhouse-cluster-kubeconfig: ~/.kube/greenhouse.yaml # tilde is expanded Examples: # Sync all clusters for an organization @@ -690,6 +690,12 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap // the same generateAuthInfoKey (e.g. same OIDC flags but different non-OIDC // exec args) each get their own managed-name entry and are never conflated. var authInfoMap map[string]string // key: server authinfo name, value: authinfo name to use (may be unmanaged local or managed hash-based) + + // skippedServerContexts holds server-side context names whose authinfo was missing + // at merge time. Their existing local managed entries must be preserved through + // the cleanup pass rather than deleted as "stale". + skippedServerContexts := make(map[string]struct{}) + if mergeIdenticalUsers { authInfoMap = make(map[string]string) @@ -814,6 +820,7 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap serverAuth, exists := serverConfig.AuthInfos[serverAuthName] if !exists || serverAuth == nil { slog.Debug("skipping context: authinfo missing from server config", "context", serverName, "authinfo", serverAuthName) + skippedServerContexts[serverName] = struct{}{} continue } uniqueKey := generateAuthInfoKey(serverAuth) @@ -834,6 +841,7 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap // a context pointing at a missing authinfo would produce a broken kubeconfig entry. if _, exists := serverConfig.AuthInfos[serverCtx.AuthInfo]; !exists { slog.Debug("skipping context: authinfo missing from server config", "context", serverName, "authinfo", serverCtx.AuthInfo) + skippedServerContexts[serverName] = struct{}{} continue } managedAuthInfoName = managedNameFunc(serverCtx.AuthInfo) @@ -928,6 +936,12 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap serverAuthName := serverCtx.AuthInfo mappedName, exists := authInfoMap[serverAuthName] if !exists { + // If the context was explicitly skipped due to a missing authinfo, + // preserve the existing local entry rather than deleting it. + if _, skipped := skippedServerContexts[serverName]; skipped { + slog.Debug("preserving local context: authinfo was missing at merge time", "name", localName) + continue + } slog.Debug("removing stale context (unmapped authinfo)", "name", localName) delete(localConfig.Contexts, localName) continue From 20c00a896fb93ebdc32486427d0633d2a014c102 Mon Sep 17 00:00:00 2001 From: onuryilmaz Date: Sat, 14 Nov 2026 12:59:43 +0100 Subject: [PATCH 5/5] fix(sync): also preserve authinfo and cluster for skipped contexts The previous fix preserved the local managed context when its incoming authinfo was missing, but the authinfo and cluster referenced by that context were still deleted by the cleanup passes. Introduce preservedAuthInfos and preservedClusters sets alongside skippedServerContexts. When a context is skipped, read its current local managed authinfo and cluster names and add them to the respective sets. The cluster and authinfo cleanup loops skip any entry present in these sets, keeping the full kubeconfig entry intact across syncs. Signed-off-by: onuryilmaz --- cmd/sync.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/cmd/sync.go b/cmd/sync.go index 74357d3..d685fd3 100644 --- a/cmd/sync.go +++ b/cmd/sync.go @@ -695,6 +695,11 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap // at merge time. Their existing local managed entries must be preserved through // the cleanup pass rather than deleted as "stale". skippedServerContexts := make(map[string]struct{}) + // preservedAuthInfos and preservedClusters hold the local managed names referenced + // by skipped contexts. They must survive the authinfo/cluster cleanup passes even + // though they are not present in serverConfig or authInfoMap. + preservedAuthInfos := make(map[string]struct{}) + preservedClusters := make(map[string]struct{}) if mergeIdenticalUsers { authInfoMap = make(map[string]string) @@ -821,6 +826,10 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap if !exists || serverAuth == nil { slog.Debug("skipping context: authinfo missing from server config", "context", serverName, "authinfo", serverAuthName) skippedServerContexts[serverName] = struct{}{} + if localCtx, ok := localConfig.Contexts[serverName]; ok && localCtx != nil { + preservedAuthInfos[localCtx.AuthInfo] = struct{}{} + preservedClusters[localCtx.Cluster] = struct{}{} + } continue } uniqueKey := generateAuthInfoKey(serverAuth) @@ -842,6 +851,10 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap if _, exists := serverConfig.AuthInfos[serverCtx.AuthInfo]; !exists { slog.Debug("skipping context: authinfo missing from server config", "context", serverName, "authinfo", serverCtx.AuthInfo) skippedServerContexts[serverName] = struct{}{} + if localCtx, ok := localConfig.Contexts[serverName]; ok && localCtx != nil { + preservedAuthInfos[localCtx.AuthInfo] = struct{}{} + preservedClusters[localCtx.Cluster] = struct{}{} + } continue } managedAuthInfoName = managedNameFunc(serverCtx.AuthInfo) @@ -874,6 +887,9 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap // Delete managed Clusters not present in serverConfig for localName := range localConfig.Clusters { if isManaged(localName) { + if _, preserved := preservedClusters[localName]; preserved { + continue + } // Derive the server-side name by stripping the prefix serverName := unmanagedNameFunc(localName) if _, exists := serverConfig.Clusters[serverName]; !exists { @@ -886,6 +902,9 @@ func mergeKubeconfig(localConfig *clientcmdapi.Config, serverConfig *clientcmdap // Delete managed AuthInfos not present in serverConfig for localName := range localConfig.AuthInfos { if isManaged(localName) { + if _, preserved := preservedAuthInfos[localName]; preserved { + continue + } if mergeIdenticalUsers { // If merging, keep AuthInfos that are mapped found := false