Why “Finalizers” are used in Kubernetes?

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.

References

πŸ”— Finalizers in Kubernetes (Kubernetes documentation)

"Knowledge Sharing Is Powerful"
Scroll to Top