<p>The Operator-SDK for Kubernetes Operators has a <a href="https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/controller/controllerutil#SetControllerReference" rel="nofollow noreferrer"><code>ctrl.SetControllerReference()</code></a> function, which claims it enables automatically garbage collecting objects when the managing Custom Resource is deleted.</p>
<p>Sometimes it doesn't seem to delete anything. What did I do wrong?</p>

I'll Eat My Hat
<p><code>ctrl.SetControllerReference()</code> only changes <code>metadata.ownerReferences</code> on the local object.</p>
<p>It doesn't automatically call <code>reconciler.Update()</code> for you.
So the changes were never persisted, and the <code>Owner</code> never changed.</p>
<p>The correct way to create an object is to call <code>ctrl.SetControllerReference()</code> before you call <code>reconciler.Create()</code>, e.g.</p>
<pre class="lang-golang prettyprint-override"><code>if err := ctrl.SetControllerReference(mycrd, secret, r.Scheme); err != nil {
    log.Error(err, &quot;Failed to set controller reference&quot;)
    return err
}

log.Info(&quot;Creating a new Secret&quot;, &quot;Secret.Namespace&quot;, secret.Namespace, &quot;Secret.Name&quot;, secret.Name)
if err = r.Create(ctx, secret); err != nil {
    log.Error(err, &quot;Failed to create new Secret&quot;, &quot;Secret.Namespace&quot;, secret.Namespace, &quot;Secret.Name&quot;, secret.Name)
    return err
}
</code></pre>
