diff --git a/src/internal/controller/zitadelcluster_controller.go b/src/internal/controller/zitadelcluster_controller.go index 222e3bd..230e114 100644 --- a/src/internal/controller/zitadelcluster_controller.go +++ b/src/internal/controller/zitadelcluster_controller.go @@ -279,7 +279,7 @@ func (r *ZitadelClusterReconciler) reconcileInitJob(ctx context.Context, zitadel key := client.ObjectKeyFromObject(zitadel) key.Name = "init-job-" + key.Name - // Build the desired InitJob + // Build the desired job desiredInitJob, err := r.Builder.BuildInitJob(zitadel, key) if err != nil { return ctrl.Result{}, fmt.Errorf("error building InitJob: %v", err) @@ -291,12 +291,50 @@ func (r *ZitadelClusterReconciler) reconcileInitJob(ctx context.Context, zitadel if !errors.IsNotFound(err) { return ctrl.Result{}, fmt.Errorf("error getting InitJob: %v", err) } - // If job not found, create the InitJob + // If job is not found, create the job if err := r.Create(ctx, desiredInitJob); err != nil { return ctrl.Result{}, fmt.Errorf("error creating InitJob: %v", err) } return ctrl.Result{}, nil } + + // Compare the image in the existing job with the desired image + existingImage := existingJob.Spec.Template.Spec.Containers[0].Image + desiredImage := desiredInitJob.Spec.Template.Spec.Containers[0].Image + + // If the images don't match, delete the existing job and wait for deletion + if existingImage != desiredImage { + + if err := r.Delete(ctx, &existingJob); err != nil { + return ctrl.Result{}, fmt.Errorf("error deleting existing InitJob: %v", err) + } + + // Wait for the job to be fully deleted before creating a new one + for { + err := r.Get(ctx, key, &existingJob) + if errors.IsNotFound(err) { + break // Job has been deleted, we can proceed + } + if err != nil { + return ctrl.Result{}, fmt.Errorf("error checking if InitJob is deleted: %v", err) + } + // Sleep for a short interval to avoid tight loop + time.Sleep(1 * time.Second) + } + + // Now create the new job + if err := r.Create(ctx, desiredInitJob); err != nil { + return ctrl.Result{}, fmt.Errorf("error creating new InitJob: %v", err) + } + } + if err := r.Get(ctx, key, &existingJob); err != nil { + return ctrl.Result{}, fmt.Errorf("error fetching existing InitJob status: %v", err) + } + + if existingJob.Status.Succeeded != 1 { // Replace with actual success condition + return ctrl.Result{}, fmt.Errorf("InitJob is not successful, current status: %v", existingJob.Status) + } + // If the job exists and the image matches, no action is needed return ctrl.Result{}, nil }