- construct that desired Deployment,
- set an owner reference so the parent WebApp controls the child,
- look up whether the child already exists, and
- create it if it does not (the get-or-create pattern).
Minimal imports (starting point)
Start with the minimal imports you already had for the controller:Expanded imports (recognize not-found and build lookup keys)
Add the API error helper and types so the controller can detect “not found” and form lookup keys:apierrors.IsNotFound(err) and work with metadata types.
Final import set (needed by Get/Create and setting owner refs)
We addtypes, controllerutil, runtime, and the controller-runtime client so the Get/Create and SetControllerReference code compiles and runs:
Always keep imports minimal but explicit. Add
apierrors to check for IsNotFound and controllerutil to set owner references. This makes your controller resilient to the common “get or create” reconciliation pattern.Wiring the Deployment in Reconcile
After you fetch the WebApp resource inside Reconcile, call the deployment helper and set the controller reference on the desired Deployment. The helper returns an*appsv1.Deployment representing the state you want in the cluster.
desiredDeployis the desired child object.controllerutil.SetControllerReferencesets the owner reference so garbage collection and ownership semantics work.
error value which you must check.
Lookup (get-or-create) and create-if-missing
Declare an emptyfound Deployment and query the API server using a NamespacedName made from the desired deployment’s namespace and name. If the Get returns a “not found” error, create the desired Deployment. Otherwise, if another error occurred, return it.
Complete Get-or-create pattern:
When calling
SetControllerReference, ensure the owner and object types are valid and the scheme includes the owner type. Otherwise SetControllerReference will return an error and reconciliation should stop.Example deployment helper
We intentionally keep the Deployment shape consistent with the WebApp spec. The helper returns a Deployment configured with labels, replicas, and a Pod template using the WebApp image.Build and test locally
After wiring the controller, run a local build to ensure there are no compile-time errors, then run the manager and apply the sample WebApp manifest:webapp-sample confirms the parent WebApp created the child workload successfully.