diff --git a/pkg/kubectl/cmd/cmd.go b/pkg/kubectl/cmd/cmd.go index c2026de45b1..b67830809d6 100644 --- a/pkg/kubectl/cmd/cmd.go +++ b/pkg/kubectl/cmd/cmd.go @@ -196,6 +196,18 @@ func getKubeNamespace(cmd *cobra.Command) string { return result } +// getExplicitKubeNamespace returns the value of the namespace a +// user explicitly provided on the command line, or false if no +// such namespace was specified. +func getExplicitKubeNamespace(cmd *cobra.Command) (string, bool) { + if ns := getFlagString(cmd, "namespace"); len(ns) > 0 { + return ns, true + } + // TODO: determine when --ns-path is set but equal to the default + // value and return its value and true. + return "", false +} + func getKubeConfig(cmd *cobra.Command) *client.Config { config := &client.Config{} diff --git a/pkg/kubectl/cmd/resource.go b/pkg/kubectl/cmd/resource.go index 570b894482e..b20de67d4ba 100644 --- a/pkg/kubectl/cmd/resource.go +++ b/pkg/kubectl/cmd/resource.go @@ -145,3 +145,14 @@ func ResourceFromFile(filename string, typer runtime.ObjectTyper, mapper meta.RE return } + +// CompareNamespaceFromFile returns an error if the namespace the user has provided on the CLI +// or via the default namespace file does not match the namespace of an input file. This +// prevents a user from unintentionally updating the wrong namespace. +func CompareNamespaceFromFile(cmd *cobra.Command, namespace string) error { + defaultNamespace := getKubeNamespace(cmd) + if defaultNamespace != namespace { + return fmt.Errorf("The namespace from the provided file %q does not match the namespace %q. You must pass '--namespace=%s' to perform this operation.", namespace, defaultNamespace, namespace) + } + return nil +} diff --git a/pkg/kubectl/cmd/update.go b/pkg/kubectl/cmd/update.go index a28fc549ad0..c9d262ca780 100644 --- a/pkg/kubectl/cmd/update.go +++ b/pkg/kubectl/cmd/update.go @@ -47,6 +47,9 @@ Examples: client, err := f.Client(cmd, mapping) checkErr(err) + err = CompareNamespaceFromFile(cmd, namespace) + checkErr(err) + err = kubectl.NewRESTHelper(client, mapping).Update(namespace, name, true, data) checkErr(err) fmt.Fprintf(out, "%s\n", name)