How to remove ownerRef from kubernetes secret using kopf

83 views Asked by At

can you please help me with the problem I'm facing? I use an kubernetes operator based on python and kopf for copying secrets from a namespace to one or more other namespaces, based on annotations. The code is working as expected, except when the secret has ownerRef. In that case it is deleted by garbage collector with reason OwnerRefInvalidNamespace

I was looking into solving this with kopf.remove_owner_reference, or kopf.adopt, but with no luck. parse_target_namespaces just returns the list of target namespaces where the secret is to be copied.

    @kopf.on.create('', 'v1', 'secrets', annotations={'synator/sync': 'yes'}, when=watch_namespace)
    @kopf.on.update('', 'v1', 'secrets', annotations={'synator/sync': 'yes'}, when=watch_namespace)
    def update_secret(body, meta, spec, status, old, new, diff, **kwargs):
        api = kubernetes.client.CoreV1Api()
        namespace_response = api.list_namespace()
        namespaces = [nsa.metadata.name for nsa in namespace_response.items]
        namespaces.remove(meta.namespace)

        secret = api.read_namespaced_secret(meta.name, meta.namespace)
        secret.metadata.annotations.pop('synator/sync')
        secret.metadata.resource_version = None
        secret.metadata.uid = None
        for ns in parse_target_namespaces(meta, namespaces):
            secret.metadata.namespace = ns
            # try to pull the Secret object then patch it, try creating it if we can't
            try:
                api.read_namespaced_secret(meta.name, ns)
                #kopf.remove_owner_reference(secret, owner=None)
                api.patch_namespaced_secret(meta.name, ns, secret)
            except kubernetes.client.rest.ApiException as e:
                print(e.args)
                #kopf.remove_owner_reference(secret, owner=None)
                #kopf.adopt(secret, strict=True, forced=True, nested='spec.template')
                api.create_namespaced_secret(ns, secret)

I was looking into solving this with kopf.remove_owner_reference, or kopf.adopt, but with no luck. Please help if you can. Thanks

1

There are 1 answers

0
Slaviša Milojković On

The solution was pretty simple... Removing reference from metadata body.

secret.metadata.owner_references = None