Skip to content

Commit e46adc4

Browse files
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
1 parent 09cfa36 commit e46adc4

File tree

3 files changed

+26
-0
lines changed

3 files changed

+26
-0
lines changed

pkg/kubectl/cmd/cmd.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,18 @@ func getKubeNamespace(cmd *cobra.Command) string {
196196
return result
197197
}
198198

199+
// getExplicitKubeNamespace returns the value of the namespace a
200+
// user explicitly provided on the command line, or false if no
201+
// such namespace was specified.
202+
func getExplicitKubeNamespace(cmd *cobra.Command) (string, bool) {
203+
if ns := getFlagString(cmd, "namespace"); len(ns) > 0 {
204+
return ns, true
205+
}
206+
// TODO: determine when --ns-path is set but equal to the default
207+
// value and return its value and true.
208+
return "", false
209+
}
210+
199211
func getKubeConfig(cmd *cobra.Command) *client.Config {
200212
config := &client.Config{}
201213

pkg/kubectl/cmd/resource.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,3 +145,14 @@ func ResourceFromFile(filename string, typer runtime.ObjectTyper, mapper meta.RE
145145

146146
return
147147
}
148+
149+
// CompareNamespaceFromFile returns an error if the namespace the user has provided on the CLI
150+
// or via the default namespace file does not match the namespace of an input file. This
151+
// prevents a user from unintentionally updating the wrong namespace.
152+
func CompareNamespaceFromFile(cmd *cobra.Command, namespace string) error {
153+
defaultNamespace := getKubeNamespace(cmd)
154+
if defaultNamespace != namespace {
155+
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)
156+
}
157+
return nil
158+
}

pkg/kubectl/cmd/update.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ Examples:
4747
client, err := f.Client(cmd, mapping)
4848
checkErr(err)
4949

50+
err = CompareNamespaceFromFile(cmd, namespace)
51+
checkErr(err)
52+
5053
err = kubectl.NewRESTHelper(client, mapping).Update(namespace, name, true, data)
5154
checkErr(err)
5255
fmt.Fprintf(out, "%s\n", name)

0 commit comments

Comments
 (0)