Skip to content

Commit dbef5e3

Browse files
authored
Merge pull request kubernetes#88998 from zhouya0/kubectl_apply_generate_name_error_message
Add kubectl apply generate name error message
2 parents 3be451d + c91ef26 commit dbef5e3

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

staging/src/k8s.io/kubectl/pkg/cmd/apply/apply.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -399,6 +399,14 @@ func (o *ApplyOptions) applyOneObject(info *resource.Info) error {
399399
klog.V(4).Infof("error recording current command: %v", err)
400400
}
401401

402+
if len(info.Name) == 0 {
403+
metadata, _ := meta.Accessor(info.Object)
404+
generatedName := metadata.GetGenerateName()
405+
if len(generatedName) > 0 {
406+
return fmt.Errorf("from %s: cannot use generate name with apply", generatedName)
407+
}
408+
}
409+
402410
helper := resource.NewHelper(info.Client, info.Mapping).
403411
DryRun(o.DryRunStrategy == cmdutil.DryRunServer).
404412
WithFieldManager(o.FieldManager)

staging/src/k8s.io/kubectl/pkg/cmd/apply/apply_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ const (
9797
filenameRCPatchTest = "../../../testdata/apply/patch.json"
9898
dirName = "../../../testdata/apply/testdir"
9999
filenameRCJSON = "../../../testdata/apply/rc.json"
100+
filenamePodGeneratedName = "../../../testdata/apply/pod-generated-name.yaml"
100101

101102
filenameWidgetClientside = "../../../testdata/apply/widget-clientside.yaml"
102103
filenameWidgetServerside = "../../../testdata/apply/widget-serverside.yaml"
@@ -1410,3 +1411,22 @@ func TestDontAllowForceApplyWithServerDryRun(t *testing.T) {
14101411

14111412
t.Fatalf(`expected error "%s"`, expectedError)
14121413
}
1414+
1415+
func TestDontAllowApplyWithPodGeneratedName(t *testing.T) {
1416+
expectedError := "error: from testing-: cannot use generate name with apply"
1417+
cmdutil.BehaviorOnFatal(func(str string, code int) {
1418+
if str != expectedError {
1419+
t.Fatalf(`expected error "%s", but got "%s"`, expectedError, str)
1420+
}
1421+
})
1422+
1423+
tf := cmdtesting.NewTestFactory().WithNamespace("test")
1424+
defer tf.Cleanup()
1425+
tf.ClientConfigVal = cmdtesting.DefaultClientConfig()
1426+
1427+
ioStreams, _, _, _ := genericclioptions.NewTestIOStreams()
1428+
cmd := NewCmdApply("kubectl", tf, ioStreams)
1429+
cmd.Flags().Set("filename", filenamePodGeneratedName)
1430+
cmd.Flags().Set("dry-run", "client")
1431+
cmd.Run(cmd, []string{})
1432+
}
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
kind: Pod
2+
apiVersion: v1
3+
metadata:
4+
generateName: testing-
5+
spec:
6+
containers:
7+
- image: nginx
8+
name: nginx

0 commit comments

Comments
 (0)