From 5e094c0a955103875ff9a18b8e9d29eb5d00cfe1 Mon Sep 17 00:00:00 2001 From: David Simansky Date: Mon, 9 Oct 2023 11:03:54 +0200 Subject: [PATCH] Fix potential redefined error with kubeconfig flag --- environment/client_config.go | 8 ++++++-- environment/client_config_test.go | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/environment/client_config.go b/environment/client_config.go index aef33927ef..0b51857aa1 100644 --- a/environment/client_config.go +++ b/environment/client_config.go @@ -44,8 +44,12 @@ func (c *ClientConfig) InitFlags(fs *flag.FlagSet) { fs.StringVar(&c.ServerURL, "server", "", "The address of the Kubernetes API server. Overrides any value in kubeconfig. Only required if out-of-cluster.") - fs.StringVar(&c.Kubeconfig, "kubeconfig", os.Getenv("KUBECONFIG"), - "Path to a kubeconfig. Only required if out-of-cluster.") + if f := fs.Lookup("kubeconfig"); f != nil { + c.Kubeconfig = f.Value.String() + } else { + fs.StringVar(&c.Kubeconfig, "kubeconfig", os.Getenv("KUBECONFIG"), + "Path to a kubeconfig. Only required if out-of-cluster.") + } fs.IntVar(&c.Burst, "kube-api-burst", int(envVarOrDefault("KUBE_API_BURST", 0)), "Maximum burst for throttle.") diff --git a/environment/client_config_test.go b/environment/client_config_test.go index b5f83b16f2..2819039ee6 100644 --- a/environment/client_config_test.go +++ b/environment/client_config_test.go @@ -48,3 +48,24 @@ func TestInitFlag(t *testing.T) { t.Errorf("ClientConfig mismatch: diff(-want,+got):\n%s", cmp.Diff(expect, c)) } } + +// TestInitFlagWithKubeconfing verify flag conflict error "flag redefined: kubeconfig" +func TestInitFlagWithKubeconfing(t *testing.T) { + t.Setenv("KUBECONFIG", "myconfig") + + c := new(ClientConfig) + flags := flag.NewFlagSet("test", flag.ExitOnError) + flags.String("kubeconfig", "/test/path", "") + c.InitFlags(flags) + + // Call parse() here as InitFlags does not call it. + flags.Parse([]string{}) + + expect := &ClientConfig{ + Kubeconfig: "/test/path", + } + + if !cmp.Equal(c, expect) { + t.Errorf("ClientConfig mismatch: diff(-want,+got):\n%s", cmp.Diff(expect, c)) + } +}