How do I manage finalizers and deletion?

Managing finalizers and deletion in Go applications, especially in Kubernetes custom controllers, is vital for ensuring resources are cleaned up properly. Finalizers allow you to execute custom logic before a resource is fully deleted. Below is an example showing how to implement finalizers in a Go-based controller.

package main import ( "context" "fmt" "time" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" corev1 "k8s.io/api/core/v1" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" ) type MyResource struct { Name string Finalizer string } func main() { kubeconfig := "path/to/your/kubeconfig" config, _ := clientcmd.BuildConfigFromFlags("", kubeconfig) clientset, _ := kubernetes.NewForConfig(config) // Example of adding a finalizer resource := &MyResource{ Name: "example-resource", Finalizer: "example.finalizer.com", } // Simulate resource deletion if err := deleteResourceWithFinalizer(clientset, resource); err != nil { fmt.Println(err) } } func deleteResourceWithFinalizer(clientset *kubernetes.Clientset, resource *MyResource) error { // Check if the resource has a finalizer if resource.Finalizer != "" { // Perform cleanup before deleting fmt.Println("Cleaning up resource:", resource.Name) time.Sleep(2 * time.Second) // Simulating cleanup process // After cleanup, remove finalizer resource.Finalizer = "" fmt.Println("Finalizer removed, resource deleted:", resource.Name) } return nil }

Go Kubernetes Finalizers Resource Management Deletion Management