Introduction
If you have worked with any programming language, you might have heard of Finalizers, mostly implemented by using functions or methods like .finalize()
. The purpose of finalizers is to perform the final cleanup.
In Kubernetes also, there is a concept of Finalizers
. In this post, we’ll learn about the Finalizers
in context of Kubernetes.
What are Finalizers ?
π Finalizers are namespaced keys that tell Kubernetes to wait until specific conditions are met before it fully deletes resources marked for deletion.
π When you delete a k8s object with finalizers specified, the k8s API marks the object for deletion by populating .metadata.deletionTimestamp
π The target object remains in the terminating state until the actions specified in the finalizers is complete. After completion, the controller removes the relevant finalizers from the target object.
π When the metadata.finalizers
field is empty, Kubernetes considers the deletion complete and deletes the object.
How Finalizers Work?
π The finalizers can be specified in metadata.finalizers
field of a manifest file.
π When you attempt to delete the resource with finalizers specified, the API server does the following:
πΉModifies the object to add a metadata.deletionTimestamp
field with the time you started the deletion.
πΉPrevents the object from being removed until its metadata.finalizers
field is empty.
πΉ Returns a 202
status code (HTTP “Accepted”)
π The controller managing that finalizer notices the update to the object setting the metadata.deletionTimestamp
, indicating deletion of the object has been requested.
π The controller then attempts to satisfy the requirements of the finalizers specified for that resource. Each time a finalizer condition is satisfied, the controller removes that key from the resource’s finalizers field.
π When the finalizers field is emptied, an object with a deletionTimestamp
field set is automatically deleted.
An example of Finalizers
π A common example of a finalizer is kubernetes.io/pv-protection
, which prevents accidental deletion of PersistentVolume
objects.
π When a PersistentVolume
object is in use by a Pod, Kubernetes adds the pv-protection
finalizer.
π If you try to delete the PersistentVolume
, it enters a Terminating
status, but the controller can’t delete it because the finalizer exists.
π When the Pod stops using the PersistentVolume
, Kubernetes clears the pv-protection
finalizer, and the controller deletes the volume.