How to correctly garbage collect objects using Operator SDK?

4/23/2021

The Operator-SDK for Kubernetes Operators has a ctrl.SetControllerReference() function, which claims it enables automatically garbage collecting objects when the managing Custom Resource is deleted.

Sometimes it doesn't seem to delete anything. What did I do wrong?

-- I'll Eat My Hat
kubernetes
kubernetes-operator
operator-sdk

1 Answer

4/23/2021

ctrl.SetControllerReference() only changes metadata.ownerReferences on the local object.

It doesn't automatically call reconciler.Update() for you. So the changes were never persisted, and the Owner never changed.

The correct way to create an object is to call ctrl.SetControllerReference() before you call reconciler.Create(), e.g.

if err := ctrl.SetControllerReference(mycrd, secret, r.Scheme); err != nil {
	log.Error(err, "Failed to set controller reference")
	return err
}

log.Info("Creating a new Secret", "Secret.Namespace", secret.Namespace, "Secret.Name", secret.Name)
if err = r.Create(ctx, secret); err != nil {
	log.Error(err, "Failed to create new Secret", "Secret.Namespace", secret.Namespace, "Secret.Name", secret.Name)
	return err
}
-- I'll Eat My Hat
Source: StackOverflow