diff --git a/pkg/utils/kubernetes/networking/services.go b/pkg/utils/kubernetes/networking/services.go index 169234397..aec162f12 100644 --- a/pkg/utils/kubernetes/networking/services.go +++ b/pkg/utils/kubernetes/networking/services.go @@ -93,37 +93,34 @@ func WaitForConnectionOnServicePort(ctx context.Context, c kubernetes.Interface, // Recreate EndpointSlices for the lb service with proper metadata. tempEndpointSlices := endpointSlices.DeepCopy().Items for i := range tempEndpointSlices { + epsName := fmt.Sprintf("%s-%d", lbServiceName, i) tempEndpointSlices[i].ObjectMeta = metav1.ObjectMeta{ Namespace: namespace, - Name: fmt.Sprintf("%s-%d", lbServiceName, i), + Name: epsName, Labels: map[string]string{ discoveryv1.LabelServiceName: lbServiceName, // Maps EndpointSlice to Service. correspondingSvcNameLabel: name, }, } - _, err = c.DiscoveryV1().EndpointSlices(namespace).Create(ctx, &tempEndpointSlices[i], metav1.CreateOptions{}) - if err != nil { + if _, err = c.DiscoveryV1().EndpointSlices(namespace).Create(ctx, &tempEndpointSlices[i], metav1.CreateOptions{}); err != nil { return err } - } - - defer func() { - for _, eps := range tempEndpointSlices { - err := c.DiscoveryV1().EndpointSlices(namespace).Delete(ctx, eps.Name, metav1.DeleteOptions{}) + // For each successfully created temporary EndpointSlice ensure deletion on return from the function. + defer func(namespace, epsName string) { + err := c.DiscoveryV1().EndpointSlices(namespace).Delete(ctx, epsName, metav1.DeleteOptions{}) if err != nil && !errors.IsNotFound(err) { - fmt.Printf("failed to delete endpoints %s/%s after testing, error %v\n", - namespace, eps.Name, err, + fmt.Printf("failed to delete EndpointSlice %s/%s after testing, error %v\n", + namespace, epsName, err, ) } - } - }() + }(namespace, epsName) + } } _, err = c.CoreV1().Services(namespace).Create(ctx, tempLoadBalancer, metav1.CreateOptions{}) if err != nil { return err } - defer func() { err := c.CoreV1().Services(namespace).Delete(ctx, lbServiceName, metav1.DeleteOptions{}) if err != nil && !errors.IsNotFound(err) {