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?
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
}