Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 477 of 8027. Package Management and AutomationFree lesson

Handling Resource Ownership and Garbage Collection

You will configure owner references to ensure that dependent resources are automatically deleted when the parent custom resource is removed.

In this lesson, you will learn how to automate the cleanup of dependent Kubernetes resources by establishing parent-child relationships through ownerReferences.

When building custom controllers or managing complex applications, you often create secondary resources (like ConfigMaps or Jobs) that exist solely to support a primary custom resource. If you delete your primary resource, those secondary resources become "orphaned," cluttering your cluster. Kubernetes solves this via Garbage Collection, triggered by the metadata.ownerReferences field.

Establishing Ownership

To link a dependent resource to a parent, you add an ownerReference to the dependent's metadata. This field requires the apiVersion, kind, name, and uid of the parent object. When the Kubernetes Garbage Collector identifies that a parent object has been deleted, it automatically locates all objects that claim it as an owner and deletes them as well.

Here is how a ConfigMap might define a parent custom resource as its owner:

apiVersion: v1
kind: ConfigMap
metadata:
  name: my-app-config
  ownerReferences:
  - apiVersion: mycompany.com/v1
    kind: MyApplication
    name: my-main-app
    uid: a1b2c3d4-e5f6-g7h8-i9j0
    blockOwnerDeletion: true
    controller: true

Key Configuration Flags

  • controller: true: This indicates that the resource is managed by the controller associated with the parent.
  • blockOwnerDeletion: true: This is a safety feature. It prevents the parent resource from being fully removed until all its "blocking" children have been successfully deleted by the garbage collector.

By setting these values, you ensure your cluster remains clean and consistent. You no longer need to write manual cleanup logic in your Go controllers for every sub-resource created; the Kubernetes API server handles the lifecycle synchronization automatically. This declarative approach keeps your operator code focused on business logic rather than housekeeping chores.

Key Takeaway: By setting ownerReferences on dependent resources, you delegate the lifecycle management of those resources to Kubernetes, ensuring they are automatically purged when their parent is deleted.