mirror of
https://github.com/k3s-io/kubernetes.git
synced 2025-07-23 03:41:45 +00:00
kubectl should error when namespace doesn't match file for update
A user who runs `kubectl update -f foo.json` where foo.json is a resource in a namespace that does not match $(kubectl namespace) may not intend to update the resource in that other namespace. For now, return an error when the user does not explicitly set the namespace via the CLI: # foo.json in 'one', current is 'two' $ kubectl update -f foo.json # FAILS $ kubectl update --namespace=one -f foo.json # SUCCEEDS
This commit is contained in:
parent
09cfa364c5
commit
e46adc4cd0
@ -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{}
|
||||
|
||||
|
@ -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
|
||||
}
|
||||
|
@ -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)
|
||||
|
Loading…
Reference in New Issue
Block a user