List containers when given container is not found

This commit is contained in:
Arda Güçlü 2026-02-12 09:47:30 +03:00
parent 89900005ee
commit 94047f3cfb
4 changed files with 16 additions and 1 deletions

View file

@ -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

View file

@ -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 {

View file

@ -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 {

View file

@ -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