book: Utilize controllerutil.ContainsFinalizer inside kubebuilder book CronJob finalizer example
@@ -66,7 +66,7 @@ func (r *CronJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct
// The object is not being deleted, so if it does not have our finalizer,
// then lets add the finalizer and update the object. This is equivalent
// registering our finalizer.
- if !containsString(cronJob.GetFinalizers(), myFinalizerName) {
+ if !controllerutil.ContainsFinalizer(cronJob, myFinalizerName) {
controllerutil.AddFinalizer(cronJob, myFinalizerName)
if err := r.Update(ctx, cronJob); err != nil {
return ctrl.Result{}, err
@@ -74,7 +74,7 @@ func (r *CronJobReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct
}
} else {
// The object is being deleted
- if containsString(cronJob.GetFinalizers(), myFinalizerName) {
+ if controllerutil.ContainsFinalizer(cronJob, myFinalizerName) {
// our finalizer is present, so lets handle any external dependency
if err := r.deleteExternalResources(cronJob); err != nil {
// if fail to delete the external dependency here, return with error
@@ -106,12 +106,3 @@ func (r *Reconciler) deleteExternalResources(cronJob *batch.CronJob) error {
// multiple times for same object.
}
-// Helper functions to check and remove string from a slice of strings.
-func containsString(slice []string, s string) bool {
- for _, item := range slice {
- if item == s {
- return true
- }
- }
- return false
-}
