fix(replay): resolve cluster config through the standard chain

- fall back from in-cluster to KUBECONFIG and ~/.kube/config so a
  cluster-less host reports a clear error instead of a raw token path
- regression test for explicit kubeconfig loading
This commit is contained in:
lakshit verma 2026-08-06 06:09:24 +05:30
parent 0baf78ddb7
commit c6d43a9d15
No known key found for this signature in database
GPG key ID: EB498AFC60A7A01A
2 changed files with 49 additions and 4 deletions

View file

@ -134,13 +134,20 @@ func (pl *Plan) dynamicClient(kubeconfig, targetContext string) (dynamic.Interfa
return dyn, nil
}
// restConfig builds a rest.Config from a kubeconfig path and context, falling
// back to the in-cluster configuration when the path is empty.
// restConfig builds a rest.Config from a kubeconfig path and context. When the
// path is empty it resolves through the standard chain: in-cluster, then the
// KUBECONFIG env var, then ~/.kube/config.
func restConfig(kubeconfig, contextName string) (*rest.Config, error) {
if kubeconfig == "" {
cfg, err := rest.InClusterConfig()
if cfg, err := rest.InClusterConfig(); err == nil {
return cfg, nil
}
cfg, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
clientcmd.NewDefaultClientConfigLoadingRules(),
&clientcmd.ConfigOverrides{},
).ClientConfig()
if err != nil {
return nil, fmt.Errorf("replay: in-cluster config: %w", err)
return nil, fmt.Errorf("replay: no cluster connection (no in-cluster service account and no kubeconfig): %w", err)
}
return cfg, nil
}

View file

@ -0,0 +1,38 @@
package replay
import (
"os"
"path/filepath"
"testing"
)
func TestRestConfigFromKubeconfig(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "config")
content := `apiVersion: v1
kind: Config
clusters:
- name: demo
cluster:
server: https://demo.example:6443
contexts:
- name: demo
context:
cluster: demo
user: demo
current-context: demo
users:
- name: demo
user: {}
`
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatalf("write kubeconfig: %v", err)
}
cfg, err := restConfig(path, "demo")
if err != nil {
t.Fatalf("restConfig: %v", err)
}
if cfg.Host != "https://demo.example:6443" {
t.Errorf("host = %q, want https://demo.example:6443", cfg.Host)
}
}