mirror of
https://github.com/vee1e/krply.git
synced 2026-09-01 17:57:03 +00:00
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:
parent
0baf78ddb7
commit
c6d43a9d15
2 changed files with 49 additions and 4 deletions
|
|
@ -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
|
||||
}
|
||||
|
|
|
|||
38
internal/replay/apply_test.go
Normal file
38
internal/replay/apply_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue