From 48409ad603e6199e2957e371f0d55bbc4bc521bc Mon Sep 17 00:00:00 2001 From: Andy Goldstein Date: Tue, 23 May 2017 15:31:40 -0400 Subject: [PATCH] Fix in-cluster kubectl --namespace override Before this change, if the config was empty, ConfirmUsable() would return an "invalid configuration" error instead of examining and honoring the value of the --namespace flag. This change looks at the overrides first, and returns the overridden value if it exists before attempting to check if the config is usable. This is most applicable to in-cluster clients, where they don't have a kubeconfig but they do have a token and can use KUBERNETES_SERVICE_HOST/_PORT. Kubernetes-commit: 23e32b100fb9745b70203c30716697bd03926313 --- tools/clientcmd/client_config.go | 14 +++++++++----- tools/clientcmd/client_config_test.go | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 5 deletions(-) diff --git a/tools/clientcmd/client_config.go b/tools/clientcmd/client_config.go index 1f180408..103648f1 100644 --- a/tools/clientcmd/client_config.go +++ b/tools/clientcmd/client_config.go @@ -296,6 +296,14 @@ func canIdentifyUser(config restclient.Config) bool { // Namespace implements ClientConfig func (config *DirectClientConfig) Namespace() (string, bool, error) { + if config.overrides != nil && config.overrides.Context.Namespace != "" { + // In the event we have an empty config but we do have a namespace override, we should return + // the namespace override instead of having config.ConfirmUsable() return an error. This allows + // things like in-cluster clients to execute `kubectl get pods --namespace=foo` and have the + // --namespace flag honored instead of being ignored. + return config.overrides.Context.Namespace, true, nil + } + if err := config.ConfirmUsable(); err != nil { return "", false, err } @@ -309,11 +317,7 @@ func (config *DirectClientConfig) Namespace() (string, bool, error) { return v1.NamespaceDefault, false, nil } - overridden := false - if config.overrides != nil && config.overrides.Context.Namespace != "" { - overridden = true - } - return configContext.Namespace, overridden, nil + return configContext.Namespace, false, nil } // ConfigAccess implements ClientConfig diff --git a/tools/clientcmd/client_config_test.go b/tools/clientcmd/client_config_test.go index 0cbff3f8..9c08ff89 100644 --- a/tools/clientcmd/client_config_test.go +++ b/tools/clientcmd/client_config_test.go @@ -504,3 +504,25 @@ func matchByteArg(expected, got []byte, t *testing.T) { t.Errorf("Expected %v, got %v", expected, got) } } + +func TestNamespaceOverride(t *testing.T) { + config := &DirectClientConfig{ + overrides: &ConfigOverrides{ + Context: clientcmdapi.Context{ + Namespace: "foo", + }, + }, + } + + ns, overridden, err := config.Namespace() + + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + if !overridden { + t.Errorf("Expected overridden = true") + } + + matchStringArg("foo", ns, t) +}