<p>Kubernetes Supports <a href="https://kubernetes.io/docs/tasks/access-kubernetes-api/custom-resources/custom-resource-definitions/#finalizers" rel="nofollow noreferrer">Finalizer in CR</a> to prevent hard deletion. I had a hard time to find sample code though. Can someone please point to real code snippet? </p>

<p>This sample repository show demo use of <code>Finalizer</code> and <code>Initializer</code>. Finalizer are used here for garbage collection.</p>

<p>Repostory: <a href="https://github.com/hossainemruz/k8s-initializer-finalizer-practice" rel="noreferrer">k8s-initializer-finalizer-practice</a></p>

<p>Here, I have created a custom controller for pods, just like Deployment.</p>

<ol>
<li>I have used <code>Initializer</code> to add <code>busybox</code> sidecar or <code>finalizer</code> to underlying pods. See <a href="https://github.com/hossainemruz/k8s-initializer-finalizer-practice/blob/a63a7a543c747df3f37399876780cdf4f74a7d42/pkg/controller/deploymentcontroller.go#L343" rel="noreferrer">here</a>.</li>
<li>When a <code>CustomDeployment</code> crd is deleted, kubernetes set <code>DeletionTimestamp</code> but does not delete it if it has finalizer. Then controller checks if it has finalizer. If it has finalizer, it deletes its pod and remove the finalizer. Then the crd terminate. See <a href="https://github.com/hossainemruz/k8s-initializer-finalizer-practice/blob/a63a7a543c747df3f37399876780cdf4f74a7d42/pkg/controller/deploymentcontroller.go#L315" rel="noreferrer">here</a>.</li>
</ol>
