diff --git a/authentik/managed/manager.py b/authentik/managed/manager.py index 17b88c791..71dc96e18 100644 --- a/authentik/managed/manager.py +++ b/authentik/managed/manager.py @@ -1,5 +1,5 @@ """Managed objects manager""" -from typing import Type +from typing import Callable, Optional, Type from structlog.stdlib import get_logger @@ -28,14 +28,28 @@ class EnsureOp: class EnsureExists(EnsureOp): """Ensure object exists, with kwargs as given values""" + created_callback: Optional[Callable] + + def __init__( + self, + obj: Type[ManagedModel], + managed_uid: str, + created_callback: Optional[Callable] = None, + **kwargs, + ) -> None: + super().__init__(obj, managed_uid, **kwargs) + self.created_callback = created_callback + def run(self): self._kwargs.setdefault("managed", self._managed_uid) - self._obj.objects.update_or_create( + obj, created = self._obj.objects.update_or_create( **{ "managed": self._managed_uid, "defaults": self._kwargs, } ) + if created and self.created_callback is not None: + self.created_callback(obj) class ObjectManager: diff --git a/authentik/outposts/managed.py b/authentik/outposts/managed.py index 9983c0d86..c74d4f313 100644 --- a/authentik/outposts/managed.py +++ b/authentik/outposts/managed.py @@ -2,7 +2,13 @@ from dataclasses import asdict from authentik.managed.manager import EnsureExists, ObjectManager -from authentik.outposts.models import Outpost, OutpostConfig, OutpostType +from authentik.outposts.models import ( + DockerServiceConnection, + KubernetesServiceConnection, + Outpost, + OutpostConfig, + OutpostType, +) MANAGED_OUTPOST = "goauthentik.io/outposts/embedded" @@ -11,10 +17,20 @@ class OutpostManager(ObjectManager): """Outpost managed objects""" def reconcile(self): + def outpost_created(outpost: Outpost): + """When outpost is initially created, and we already have a service connection, + auto-assign it.""" + if KubernetesServiceConnection.objects.exists(): + outpost.service_connection = KubernetesServiceConnection.objects.first() + elif DockerServiceConnection.objects.exists(): + outpost.service_connection = DockerServiceConnection.objects.first() + outpost.save() + return [ EnsureExists( Outpost, MANAGED_OUTPOST, + created_callback=outpost_created, name="authentik Embedded Outpost", type=OutpostType.PROXY, _config=asdict(