From a95618c76ec97a962793fc52c2b5fe8bf9c42d01 Mon Sep 17 00:00:00 2001 From: Juan Hernandez Date: Thu, 11 Apr 2024 12:42:00 +0200 Subject: [PATCH] Support creation of non-namespaced objects in `CreateK8sCR` Kubernetes forbids the creation of object in one namespace with owners in another namespace, or the creation of non-namespaced objects with namespaced owners. But the `CreateK8sCR` function doesn't support. We will need that in order to create cluster roles and cluster role bindings. This patch changes the function so that it will not try to set an owner if the namespace of the object and the namespace of the owner are different. Signed-off-by: Juan Hernandez --- internal/controllers/utils/utils.go | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/internal/controllers/utils/utils.go b/internal/controllers/utils/utils.go index 06c538b1..db17f0bc 100644 --- a/internal/controllers/utils/utils.go +++ b/internal/controllers/utils/utils.go @@ -26,9 +26,16 @@ func CreateK8sCR(ctx context.Context, c client.Client, // Get the name and namespace of the object: key := client.ObjectKeyFromObject(newObject) oranUtilsLog.Info("[CreateK8sCR] Resource", "name", key.Name) - // Set owner reference. - if err = controllerutil.SetControllerReference(ownerObject, newObject, runtimeScheme); err != nil { - return err + + // We can set the owner reference only for objects that live in the same namespace, as cross + // namespace owners are forbidden. This also applies to non-namespaced objects like cluster + // roles or cluster role bindings; those have empty namespaces so the equals comparison + // should also work. + if ownerObject.GetNamespace() == key.Namespace { + err = controllerutil.SetControllerReference(ownerObject, newObject, runtimeScheme) + if err != nil { + return err + } } // Check if the CR already exists.