Controllers creating/watching resources in different namespace than their Custom Resource

2k views Asked by At

I have a controller which Reconciles MyKind Custom Resource in 'foo' namespace. Within the reconcile loop, it creates a deployment MyDeployment in 'bar' namespace. I am wondering how can I setup a watch on the MyDeployment created in 'bar' namespace which is different than namespace ('foo') where the custom resource live.

I tried setting up my manager with the following, but it doesnt seem to work since the deployment I am trying to watch are in different namespace hence the controller is not able to receive any events for the CRUD operation on the deployment.

    return controllerruntime.NewControllerManagedBy(mgr).
        For(&v1alpha1.MyKind{}).
        Owns(&appsv1.Deployment{}).
        Complete(r)
}

Is there any custom watch that I can configure my controller with in order to receive events for the deployment in a different namespace.

Note: I tried handler.EnqueueRequestsFromMapFunc, IIUC it also reconciles for Kinds in the same namespace.

2

There are 2 answers

3
Hazim On

You can specify namespaces in the manager options by passing in a ctrl.Options{} object, while creating it.

namespace := "namespace1,namespace2"
options := ctrl.Options{
        .
        .
        .
        Namespace: cache.MultiNamespacedCacheBuilder(strings.Split(namespace, ","))
    }

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), options)
0
Vajira Prabuddhaka On

You can use MultiNamespacedCacheBuilder as the NewCache function when creating manager. This can be set in manager.Options.

For example:

namespace := "ns1,ns1"
options := ctrl.Options{
    .
    .
    .
    NewCache: cache.MultiNamespacedCacheBuilder(strings.Split(namespace, ","))
}

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), options)