diff --git a/staging/src/k8s.io/kubectl/pkg/cmd/exec/exec.go b/staging/src/k8s.io/kubectl/pkg/cmd/exec/exec.go index d664ae3c573..e648e1191ae 100644 --- a/staging/src/k8s.io/kubectl/pkg/cmd/exec/exec.go +++ b/staging/src/k8s.io/kubectl/pkg/cmd/exec/exec.go @@ -358,6 +358,11 @@ func (p *ExecOptions) Run() error { return err } containerName = container.Name + } else { + container, _ := podcmd.FindContainerByName(pod, p.ContainerName) + if container == nil { + return fmt.Errorf("container %s is not valid for pod %s out of: %s", p.ContainerName, pod.Name, podcmd.AllContainerNames(pod)) + } } // ensure we can recover the terminal while attached diff --git a/staging/src/k8s.io/kubectl/pkg/polymorphichelpers/logsforobject.go b/staging/src/k8s.io/kubectl/pkg/polymorphichelpers/logsforobject.go index 87968b789d0..064ea910f99 100644 --- a/staging/src/k8s.io/kubectl/pkg/polymorphichelpers/logsforobject.go +++ b/staging/src/k8s.io/kubectl/pkg/polymorphichelpers/logsforobject.go @@ -116,7 +116,7 @@ func logsForObjectWithClient(clientset corev1client.CoreV1Interface, object, opt container, fieldPath := podcmd.FindContainerByName(t, currOpts.Container) if container == nil { - return nil, fmt.Errorf("container %s is not valid for pod %s", currOpts.Container, t.Name) + return nil, fmt.Errorf("container %s is not valid for pod %s out of: %s", currOpts.Container, t.Name, podcmd.AllContainerNames(t)) } ref, err := reference.GetPartialReference(scheme.Scheme, t, fieldPath) if err != nil { diff --git a/staging/src/k8s.io/kubectl/pkg/polymorphichelpers/logsforobject_test.go b/staging/src/k8s.io/kubectl/pkg/polymorphichelpers/logsforobject_test.go index d2ded0d895f..c69785b2c50 100644 --- a/staging/src/k8s.io/kubectl/pkg/polymorphichelpers/logsforobject_test.go +++ b/staging/src/k8s.io/kubectl/pkg/polymorphichelpers/logsforobject_test.go @@ -384,6 +384,12 @@ func TestLogsForObject(t *testing.T) { FieldPath: fmt.Sprintf("spec.containers{%s}", testPodWithOneContainers().Spec.Containers[0].Name), }}, }, + { + name: "pod logs: invalid container name", + obj: testPodWithTwoContainers(), + opts: &corev1.PodLogOptions{Container: "nonexistent"}, + expectedErr: "container nonexistent is not valid for pod foo-two-containers out of: foo-2-c1, foo-2-c2", + }, } for _, test := range tests { diff --git a/test/cmd/exec.sh b/test/cmd/exec.sh index 02ab7c8d522..159c3338387 100755 --- a/test/cmd/exec.sh +++ b/test/cmd/exec.sh @@ -63,6 +63,10 @@ __EOF__ # These must be pass the validate kube::test::if_has_not_string "${output_message}" 'pod or type/name must be specified' + ### Test execute with invalid container name + output_message=$(! kubectl exec test-pod -c nonexistent -- date 2>&1) + kube::test::if_has_string "${output_message}" 'container nonexistent is not valid for pod test-pod out of: kubernetes-pause' + # Clean up kubectl delete pods test-pod