Implementing a custom Finalizer to Kubernetes resources

9/7/2019

Seems easy peasy to implement custom finalizers if I'm implementing my Kubernetes CRD: the code snippet is quite easy since the first delete request on the object sets a value for the metadata.deletionTimestamp field instead of deleting the object that triggers the custom controller watching the object to execute any finalizers it handles.

However, let's imagine I'd like to set a custom finalizer for a default Kubernetes resource like a Namespace, a Deployment or whatever: is that possible or not?

-- prometherion
kubernetes

1 Answer

9/8/2019

Ok, tested a little bit taking Namespace as an example.

# k create ns my-namespace
namespace/my-namespace created

# k edit ns my-namespace
(... adding the .metadata.finalizers list)

# k get ns my-namespace -o yaml
apiVersion: v1
kind: Namespace
metadata:
  creationTimestamp: "2019-09-08T06:50:25Z"
  finalizers:
  - prometherion/do-something
  name: my-namespace
  resourceVersion: "1131"
  selfLink: /api/v1/namespaces/my-namespace
  uid: 75b5bae8-1d5b-44c6-86bc-e632341aabfd
spec:
  finalizers:
  - kubernetes
status:
  phase: Active

# k delete ns my-namespace
namespace "my-namespace" deleted

If I open another terminal, I can see the resource in Terminating state.

# k get ns my-namespace
NAME           STATUS        AGE
my-namespace   Terminating   6m8s

So, actually the resource is marked to be deleted since I got a deletionTimestamp:

k get ns my-namespace -o jsonpath='{.metadata.deletionTimestamp}'
2019-09-08T06:58:07

To complete the deletion, I just need a simple Watch (using the Kubernetes Go Client) to get the change of the object (or a Dynamic Admission Controll to get the event, process my business logic in async mode (like a pre delete hook) and remove my fully-qualified Finalizer... just for sake of simplicity, I tested removing it with kubectl and it worked.

Just for information, Finalizer must be fully qualified since there's a validation process, so it must be declared according to the pattern prometherion/whatever_you_want, taking care the first part must adhere to DNS-1123 specification.

-- prometherion
Source: StackOverflow