externalsecret_controller.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  1. /*
  2. Copyright © 2025 ESO Maintainer Team
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. // Package externalsecret implements the controller for managing ExternalSecret resources
  14. package externalsecret
  15. import (
  16. "context"
  17. "encoding/json"
  18. "errors"
  19. "fmt"
  20. "maps"
  21. "slices"
  22. "strings"
  23. "time"
  24. "github.com/go-logr/logr"
  25. "github.com/prometheus/client_golang/prometheus"
  26. v1 "k8s.io/api/core/v1"
  27. "k8s.io/apimachinery/pkg/api/equality"
  28. apierrors "k8s.io/apimachinery/pkg/api/errors"
  29. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  30. "k8s.io/apimachinery/pkg/fields"
  31. "k8s.io/apimachinery/pkg/labels"
  32. "k8s.io/apimachinery/pkg/runtime"
  33. "k8s.io/apimachinery/pkg/runtime/schema"
  34. "k8s.io/apimachinery/pkg/types"
  35. "k8s.io/client-go/rest"
  36. "k8s.io/client-go/tools/record"
  37. "k8s.io/utils/ptr"
  38. ctrl "sigs.k8s.io/controller-runtime"
  39. "sigs.k8s.io/controller-runtime/pkg/builder"
  40. "sigs.k8s.io/controller-runtime/pkg/client"
  41. "sigs.k8s.io/controller-runtime/pkg/controller"
  42. "sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
  43. "sigs.k8s.io/controller-runtime/pkg/handler"
  44. "sigs.k8s.io/controller-runtime/pkg/predicate"
  45. "sigs.k8s.io/controller-runtime/pkg/reconcile"
  46. esv1 "github.com/external-secrets/external-secrets/apis/externalsecrets/v1"
  47. // Metrics.
  48. "github.com/external-secrets/external-secrets/pkg/controllers/externalsecret/esmetrics"
  49. ctrlmetrics "github.com/external-secrets/external-secrets/pkg/controllers/metrics"
  50. "github.com/external-secrets/external-secrets/pkg/controllers/util"
  51. "github.com/external-secrets/external-secrets/pkg/esutils"
  52. "github.com/external-secrets/external-secrets/pkg/esutils/resolvers"
  53. // Loading registered generators.
  54. _ "github.com/external-secrets/external-secrets/pkg/generator/register"
  55. // Loading registered providers.
  56. _ "github.com/external-secrets/external-secrets/pkg/provider/register"
  57. )
  58. const (
  59. fieldOwnerTemplate = "externalsecrets.external-secrets.io/%v"
  60. fieldOwnerTemplateSha = "externalsecrets.external-secrets.io/sha3/%x"
  61. // ExternalSecretFinalizer is the finalizer for ExternalSecret resources.
  62. ExternalSecretFinalizer = "externalsecrets.external-secrets.io/externalsecret-cleanup"
  63. // condition messages for "SecretSynced" reason.
  64. msgSynced = "secret synced"
  65. msgSyncedRetain = "secret retained due to DeletionPolicy=Retain"
  66. // condition messages for "SecretDeleted" reason.
  67. msgDeleted = "secret deleted due to DeletionPolicy=Delete"
  68. // condition messages for "SecretMissing" reason.
  69. msgMissing = "secret will not be created due to CreationPolicy=Merge"
  70. // condition messages for "SecretSyncedError" reason.
  71. msgErrorGetSecretData = "could not get secret data from provider"
  72. msgErrorDeleteSecret = "could not delete secret"
  73. msgErrorDeleteOrphaned = "could not delete orphaned secrets"
  74. msgErrorUpdateSecret = "could not update secret"
  75. msgErrorUpdateImmutable = "could not update secret, target is immutable"
  76. msgErrorBecomeOwner = "failed to take ownership of target secret"
  77. msgErrorIsOwned = "target is owned by another ExternalSecret"
  78. // log messages.
  79. logErrorGetES = "unable to get ExternalSecret"
  80. logErrorUpdateESStatus = "unable to update ExternalSecret status"
  81. logErrorGetSecret = "unable to get Secret"
  82. logErrorPatchSecret = "unable to patch Secret"
  83. logErrorSecretCacheNotSynced = "controller caches for Secret are not in sync"
  84. logErrorUnmanagedStore = "unable to determine if store is managed"
  85. // error formats.
  86. errConvert = "error applying conversion strategy %s to keys: %w"
  87. errRewrite = "error applying rewrite to keys: %w"
  88. errDecode = "error applying decoding strategy %s to data: %w"
  89. errGenerate = "error using generator: %w"
  90. errInvalidKeys = "invalid secret keys (TIP: use rewrite or conversionStrategy to change keys): %w"
  91. errFetchTplFrom = "error fetching templateFrom data: %w"
  92. errApplyTemplate = "could not apply template: %w"
  93. errExecTpl = "could not execute template: %w"
  94. errMutate = "unable to mutate secret %s: %w"
  95. errUpdate = "unable to update secret %s: %w"
  96. errUpdateNotFound = "unable to update secret %s: not found"
  97. errDeleteCreatePolicy = "unable to delete secret %s: creationPolicy=%s is not Owner"
  98. errSecretCachesNotSynced = "controller caches for secret %s are not in sync"
  99. // event messages.
  100. eventCreated = "secret created"
  101. eventUpdated = "secret updated"
  102. eventDeleted = "secret deleted due to DeletionPolicy=Delete"
  103. eventDeletedOrphaned = "secret deleted because it was orphaned"
  104. eventMissingProviderSecret = "secret does not exist at provider using spec.dataFrom[%d]"
  105. eventMissingProviderSecretKey = "secret does not exist at provider using spec.dataFrom[%d] (key=%s)"
  106. )
  107. // these errors are explicitly defined so we can detect them with `errors.Is()`.
  108. var (
  109. ErrSecretImmutable = fmt.Errorf("secret is immutable")
  110. ErrSecretIsOwned = fmt.Errorf("secret is owned by another ExternalSecret")
  111. ErrSecretSetCtrlRef = fmt.Errorf("could not set controller reference on secret")
  112. ErrSecretRemoveCtrlRef = fmt.Errorf("could not remove controller reference on secret")
  113. )
  114. const indexESTargetSecretNameField = ".metadata.targetSecretName"
  115. // Reconciler reconciles a ExternalSecret object.
  116. type Reconciler struct {
  117. client.Client
  118. SecretClient client.Client
  119. Log logr.Logger
  120. Scheme *runtime.Scheme
  121. RestConfig *rest.Config
  122. ControllerClass string
  123. RequeueInterval time.Duration
  124. ClusterSecretStoreEnabled bool
  125. EnableFloodGate bool
  126. EnableGeneratorState bool
  127. recorder record.EventRecorder
  128. }
  129. // Reconcile implements the main reconciliation loop
  130. // for watched objects (ExternalSecret, ClusterSecretStore and SecretStore),
  131. // and updates/creates a Kubernetes secret based on them.
  132. func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, err error) {
  133. log := r.Log.WithValues("ExternalSecret", req.NamespacedName)
  134. resourceLabels := ctrlmetrics.RefineNonConditionMetricLabels(map[string]string{"name": req.Name, "namespace": req.Namespace})
  135. start := time.Now()
  136. syncCallsError := esmetrics.GetCounterVec(esmetrics.SyncCallsErrorKey)
  137. // use closures to dynamically update resourceLabels
  138. defer func() {
  139. esmetrics.GetGaugeVec(esmetrics.ExternalSecretReconcileDurationKey).With(resourceLabels).Set(float64(time.Since(start)))
  140. esmetrics.GetCounterVec(esmetrics.SyncCallsKey).With(resourceLabels).Inc()
  141. }()
  142. externalSecret := &esv1.ExternalSecret{}
  143. err = r.Get(ctx, req.NamespacedName, externalSecret)
  144. if err != nil {
  145. if apierrors.IsNotFound(err) {
  146. // NOTE: this does not actually set the condition on the ExternalSecret, because it does not exist
  147. // this is a hack to disable metrics for deleted ExternalSecrets, see:
  148. // https://github.com/external-secrets/external-secrets/pull/612
  149. conditionSynced := NewExternalSecretCondition(esv1.ExternalSecretDeleted, v1.ConditionFalse, esv1.ConditionReasonSecretDeleted, "Secret was deleted")
  150. SetExternalSecretCondition(&esv1.ExternalSecret{
  151. ObjectMeta: metav1.ObjectMeta{
  152. Name: req.Name,
  153. Namespace: req.Namespace,
  154. },
  155. }, *conditionSynced)
  156. return ctrl.Result{}, nil
  157. }
  158. log.Error(err, logErrorGetES)
  159. syncCallsError.With(resourceLabels).Inc()
  160. return ctrl.Result{}, err
  161. }
  162. // Handle deletion with finalizer
  163. if !externalSecret.GetDeletionTimestamp().IsZero() {
  164. // Always attempt cleanup to handle edge case where finalizer might be removed externally
  165. if err := r.cleanupManagedSecrets(ctx, log, externalSecret); err != nil {
  166. log.Error(err, "failed to cleanup managed secrets")
  167. return ctrl.Result{}, err
  168. }
  169. // Remove finalizer if it exists
  170. if updated := controllerutil.RemoveFinalizer(externalSecret, ExternalSecretFinalizer); updated {
  171. if err := r.Update(ctx, externalSecret); err != nil {
  172. return ctrl.Result{}, err
  173. }
  174. }
  175. return ctrl.Result{}, nil
  176. }
  177. // Add finalizer if it doesn't exist
  178. if updated := controllerutil.AddFinalizer(externalSecret, ExternalSecretFinalizer); updated {
  179. if err := r.Update(ctx, externalSecret); err != nil {
  180. return ctrl.Result{}, err
  181. }
  182. }
  183. // if extended metrics is enabled, refine the time series vector
  184. resourceLabels = ctrlmetrics.RefineLabels(resourceLabels, externalSecret.Labels)
  185. // skip this ExternalSecret if it uses a ClusterSecretStore and the feature is disabled
  186. if shouldSkipClusterSecretStore(r, externalSecret) {
  187. log.V(1).Info("skipping ExternalSecret, ClusterSecretStore feature is disabled")
  188. return ctrl.Result{}, nil
  189. }
  190. // skip this ExternalSecret if it uses any SecretStore not managed by this controller
  191. skip, err := shouldSkipUnmanagedStore(ctx, req.Namespace, r, externalSecret)
  192. if err != nil {
  193. log.Error(err, logErrorUnmanagedStore)
  194. syncCallsError.With(resourceLabels).Inc()
  195. return ctrl.Result{}, err
  196. }
  197. if skip {
  198. log.V(1).Info("skipping ExternalSecret, uses unmanaged SecretStore")
  199. return ctrl.Result{}, nil
  200. }
  201. // the target secret name defaults to the ExternalSecret name, if not explicitly set
  202. secretName := externalSecret.Spec.Target.Name
  203. if secretName == "" {
  204. secretName = externalSecret.Name
  205. }
  206. // fetch the existing secret (from the partial cache)
  207. // - please note that the ~partial cache~ is different from the ~full cache~
  208. // so there can be race conditions between the two caches
  209. // - the WatchesMetadata(v1.Secret{}) in SetupWithManager() is using the partial cache
  210. // so we might receive a reconcile request before the full cache is updated
  211. // - furthermore, when `--enable-managed-secrets-caching` is true, the full cache
  212. // will ONLY include secrets with the "managed" label, so we cant use the full cache
  213. // to reliably determine if a secret exists or not
  214. secretPartial := &metav1.PartialObjectMetadata{}
  215. secretPartial.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("Secret"))
  216. err = r.Get(ctx, client.ObjectKey{Name: secretName, Namespace: externalSecret.Namespace}, secretPartial)
  217. if err != nil && !apierrors.IsNotFound(err) {
  218. log.Error(err, logErrorGetSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  219. syncCallsError.With(resourceLabels).Inc()
  220. return ctrl.Result{}, err
  221. }
  222. // if the secret exists but does not have the "managed" label, add the label
  223. // using a PATCH so it is visible in the cache, then requeue immediately
  224. if secretPartial.UID != "" && secretPartial.Labels[esv1.LabelManaged] != esv1.LabelManagedValue {
  225. fqdn := fqdnFor(externalSecret.Name)
  226. patch := client.MergeFrom(secretPartial.DeepCopy())
  227. if secretPartial.Labels == nil {
  228. secretPartial.Labels = make(map[string]string)
  229. }
  230. secretPartial.Labels[esv1.LabelManaged] = esv1.LabelManagedValue
  231. err = r.Patch(ctx, secretPartial, patch, client.FieldOwner(fqdn))
  232. if err != nil {
  233. log.Error(err, logErrorPatchSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  234. syncCallsError.With(resourceLabels).Inc()
  235. return ctrl.Result{}, err
  236. }
  237. return ctrl.Result{Requeue: true}, nil
  238. }
  239. // fetch existing secret (from the full cache)
  240. // NOTE: we are using the `r.SecretClient` which we only use for managed secrets.
  241. // when `enableManagedSecretsCache` is true, this is a cached client that only sees our managed secrets,
  242. // otherwise it will be the normal controller-runtime client which may be cached or make direct API calls,
  243. // depending on if `enabledSecretCache` is true or false.
  244. existingSecret := &v1.Secret{}
  245. err = r.SecretClient.Get(ctx, client.ObjectKey{Name: secretName, Namespace: externalSecret.Namespace}, existingSecret)
  246. if err != nil && !apierrors.IsNotFound(err) {
  247. log.Error(err, logErrorGetSecret, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  248. syncCallsError.With(resourceLabels).Inc()
  249. return ctrl.Result{}, err
  250. }
  251. // ensure the full cache is up-to-date
  252. // NOTE: this prevents race conditions between the partial and full cache.
  253. // we return an error so we get an exponential backoff if we end up looping,
  254. // for example, during high cluster load and frequent updates to the target secret by other controllers.
  255. if secretPartial.UID != existingSecret.UID || secretPartial.ResourceVersion != existingSecret.ResourceVersion {
  256. err = fmt.Errorf(errSecretCachesNotSynced, secretName)
  257. log.Error(err, logErrorSecretCacheNotSynced, "secretName", secretName, "secretNamespace", externalSecret.Namespace)
  258. syncCallsError.With(resourceLabels).Inc()
  259. return ctrl.Result{}, err
  260. }
  261. // refresh will be skipped if ALL the following conditions are met:
  262. // 1. refresh interval is not 0
  263. // 2. resource generation of the ExternalSecret has not changed
  264. // 3. the last refresh time of the ExternalSecret is within the refresh interval
  265. // 4. the target secret is valid:
  266. // - it exists
  267. // - it has the correct "managed" label
  268. // - it has the correct "data-hash" annotation
  269. if !shouldRefresh(externalSecret) && isSecretValid(existingSecret, externalSecret) {
  270. log.V(1).Info("skipping refresh")
  271. return r.getRequeueResult(externalSecret), nil
  272. }
  273. // update status of the ExternalSecret when this function returns, if needed.
  274. // NOTE: we use the ability of deferred functions to update named return values `result` and `err`
  275. // NOTE: we dereference the DeepCopy of the status field because status fields are NOT pointers,
  276. // so otherwise the `equality.Semantic.DeepEqual` will always return false.
  277. currentStatus := *externalSecret.Status.DeepCopy()
  278. defer func() {
  279. // if the status has not changed, we don't need to update it
  280. if equality.Semantic.DeepEqual(currentStatus, externalSecret.Status) {
  281. return
  282. }
  283. // update the status of the ExternalSecret, storing any error in a new variable
  284. // if there was no new error, we don't need to change the `result` or `err` values
  285. updateErr := r.Status().Update(ctx, externalSecret)
  286. if updateErr == nil {
  287. return
  288. }
  289. // if we got an update conflict, we should requeue immediately
  290. if apierrors.IsConflict(updateErr) {
  291. log.V(1).Info("conflict while updating status, will requeue")
  292. // we only explicitly request a requeue if the main function did not return an `err`.
  293. // otherwise, we get an annoying log saying that results are ignored when there is an error,
  294. // as errors are always retried.
  295. if err == nil {
  296. result = ctrl.Result{Requeue: true}
  297. }
  298. return
  299. }
  300. // for other errors, log and update the `err` variable if there is no error already
  301. // so the reconciler will requeue the request
  302. log.Error(updateErr, logErrorUpdateESStatus)
  303. if err == nil {
  304. err = updateErr
  305. }
  306. }()
  307. // retrieve the provider secret data.
  308. dataMap, err := r.GetProviderSecretData(ctx, externalSecret)
  309. if err != nil {
  310. r.markAsFailed(msgErrorGetSecretData, err, externalSecret, syncCallsError.With(resourceLabels))
  311. return ctrl.Result{}, err
  312. }
  313. // if no data was found we can delete the secret if needed.
  314. if len(dataMap) == 0 {
  315. switch externalSecret.Spec.Target.DeletionPolicy {
  316. // delete secret and return early.
  317. case esv1.DeletionPolicyDelete:
  318. // safeguard that we only can delete secrets we own.
  319. // this is also implemented in the es validation webhook.
  320. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  321. creationPolicy := externalSecret.Spec.Target.CreationPolicy
  322. if creationPolicy != esv1.CreatePolicyOwner {
  323. err = fmt.Errorf(errDeleteCreatePolicy, secretName, creationPolicy)
  324. r.markAsFailed(msgErrorDeleteSecret, err, externalSecret, syncCallsError.With(resourceLabels))
  325. return ctrl.Result{}, nil
  326. }
  327. // delete the secret, if it exists
  328. if existingSecret.UID != "" {
  329. err = r.Delete(ctx, existingSecret)
  330. if err != nil && !apierrors.IsNotFound(err) {
  331. r.markAsFailed(msgErrorDeleteSecret, err, externalSecret, syncCallsError.With(resourceLabels))
  332. return ctrl.Result{}, err
  333. }
  334. r.recorder.Event(externalSecret, v1.EventTypeNormal, esv1.ReasonDeleted, eventDeleted)
  335. }
  336. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretDeleted, msgDeleted)
  337. return r.getRequeueResult(externalSecret), nil
  338. // In case provider secrets don't exist the kubernetes secret will be kept as-is.
  339. case esv1.DeletionPolicyRetain:
  340. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretSynced, msgSyncedRetain)
  341. return r.getRequeueResult(externalSecret), nil
  342. // noop, handled below
  343. case esv1.DeletionPolicyMerge:
  344. }
  345. }
  346. // mutationFunc is a function which can be applied to a secret to make it match the desired state.
  347. mutationFunc := func(secret *v1.Secret) error {
  348. // get information about the current owner of the secret
  349. // - we ignore the API version as it can change over time
  350. // - we ignore the UID for consistency with the SetControllerReference function
  351. currentOwner := metav1.GetControllerOf(secret)
  352. ownerIsESKind := false
  353. ownerIsCurrentES := false
  354. if currentOwner != nil {
  355. currentOwnerGK := schema.FromAPIVersionAndKind(currentOwner.APIVersion, currentOwner.Kind).GroupKind()
  356. ownerIsESKind = currentOwnerGK.String() == esv1.ExtSecretGroupKind
  357. ownerIsCurrentES = ownerIsESKind && currentOwner.Name == externalSecret.Name
  358. }
  359. // if another ExternalSecret is the owner, we should return an error
  360. // otherwise the controller will fight with itself to update the secret.
  361. // note, this does not prevent other controllers from owning the secret.
  362. if ownerIsESKind && !ownerIsCurrentES {
  363. return fmt.Errorf("%w: %s", ErrSecretIsOwned, currentOwner.Name)
  364. }
  365. // if the CreationPolicy is Owner, we should set ourselves as the owner of the secret
  366. if externalSecret.Spec.Target.CreationPolicy == esv1.CreatePolicyOwner {
  367. err = controllerutil.SetControllerReference(externalSecret, secret, r.Scheme)
  368. if err != nil {
  369. return fmt.Errorf("%w: %w", ErrSecretSetCtrlRef, err)
  370. }
  371. }
  372. // if the creation policy is not Owner, we should remove ourselves as the owner
  373. // this could happen if the creation policy was changed after the secret was created
  374. if externalSecret.Spec.Target.CreationPolicy != esv1.CreatePolicyOwner && ownerIsCurrentES {
  375. err = controllerutil.RemoveControllerReference(externalSecret, secret, r.Scheme)
  376. if err != nil {
  377. return fmt.Errorf("%w: %w", ErrSecretRemoveCtrlRef, err)
  378. }
  379. }
  380. // initialize maps within the secret so it's safe to set values
  381. if secret.Annotations == nil {
  382. secret.Annotations = make(map[string]string)
  383. }
  384. if secret.Labels == nil {
  385. secret.Labels = make(map[string]string)
  386. }
  387. if secret.Data == nil {
  388. secret.Data = make(map[string][]byte)
  389. }
  390. // set the immutable flag on the secret if requested by the ExternalSecret
  391. if externalSecret.Spec.Target.Immutable {
  392. secret.Immutable = ptr.To(true)
  393. }
  394. // only apply the template if the secret is mutable or if the secret is new (has no UID)
  395. // otherwise we would mutate an object that is immutable and already exists
  396. objectDoesNotExistOrCanBeMutated := secret.GetUID() == "" || !externalSecret.Spec.Target.Immutable
  397. if objectDoesNotExistOrCanBeMutated {
  398. // get the list of keys that are managed by this ExternalSecret
  399. keys, err := getManagedDataKeys(secret, externalSecret.Name)
  400. if err != nil {
  401. return err
  402. }
  403. // remove any data keys that are managed by this ExternalSecret, so we can re-add them
  404. // this ensures keys added by templates are not left behind when they are removed from the template
  405. for _, key := range keys {
  406. delete(secret.Data, key)
  407. }
  408. // WARNING: this will remove any labels or annotations managed by this ExternalSecret
  409. // so any updates to labels and annotations should be done AFTER this point
  410. err = r.ApplyTemplate(ctx, externalSecret, secret, dataMap)
  411. if err != nil {
  412. return fmt.Errorf(errApplyTemplate, err)
  413. }
  414. }
  415. // we also use a label to keep track of the owner of the secret
  416. // this lets us remove secrets that are no longer needed if the target secret name changes
  417. if externalSecret.Spec.Target.CreationPolicy == esv1.CreatePolicyOwner {
  418. lblValue := esutils.ObjectHash(fmt.Sprintf("%v/%v", externalSecret.Namespace, externalSecret.Name))
  419. secret.Labels[esv1.LabelOwner] = lblValue
  420. } else {
  421. // the label should not be set if the creation policy is not Owner
  422. delete(secret.Labels, esv1.LabelOwner)
  423. }
  424. secret.Labels[esv1.LabelManaged] = esv1.LabelManagedValue
  425. secret.Annotations[esv1.AnnotationDataHash] = esutils.ObjectHash(secret.Data)
  426. return nil
  427. }
  428. switch externalSecret.Spec.Target.CreationPolicy {
  429. case esv1.CreatePolicyNone:
  430. log.V(1).Info("secret creation skipped due to CreationPolicy=None")
  431. err = nil
  432. case esv1.CreatePolicyMerge:
  433. // update the secret, if it exists
  434. if existingSecret.UID != "" {
  435. err = r.updateSecret(ctx, existingSecret, mutationFunc, externalSecret, secretName)
  436. } else {
  437. // if the secret does not exist, we wait until the next refresh interval
  438. // rather than returning an error which would requeue immediately
  439. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretMissing, msgMissing)
  440. return r.getRequeueResult(externalSecret), nil
  441. }
  442. case esv1.CreatePolicyOrphan:
  443. // create the secret, if it does not exist
  444. if existingSecret.UID == "" {
  445. err = r.createSecret(ctx, mutationFunc, externalSecret, secretName)
  446. } else {
  447. // if the secret exists, we should update it
  448. err = r.updateSecret(ctx, existingSecret, mutationFunc, externalSecret, secretName)
  449. }
  450. case esv1.CreatePolicyOwner:
  451. // we may have orphaned secrets to clean up,
  452. // for example, if the target secret name was changed
  453. err = r.deleteOrphanedSecrets(ctx, externalSecret, secretName)
  454. if err != nil {
  455. r.markAsFailed(msgErrorDeleteOrphaned, err, externalSecret, syncCallsError.With(resourceLabels))
  456. return ctrl.Result{}, err
  457. }
  458. // create the secret, if it does not exist
  459. if existingSecret.UID == "" {
  460. err = r.createSecret(ctx, mutationFunc, externalSecret, secretName)
  461. } else {
  462. // if the secret exists, we should update it
  463. err = r.updateSecret(ctx, existingSecret, mutationFunc, externalSecret, secretName)
  464. }
  465. }
  466. if err != nil {
  467. // if we got an update conflict, we should requeue immediately
  468. if apierrors.IsConflict(err) {
  469. log.V(1).Info("conflict while updating secret, will requeue")
  470. return ctrl.Result{Requeue: true}, nil
  471. }
  472. // detect errors indicating that we failed to set ourselves as the owner of the secret
  473. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  474. if errors.Is(err, ErrSecretSetCtrlRef) {
  475. r.markAsFailed(msgErrorBecomeOwner, err, externalSecret, syncCallsError.With(resourceLabels))
  476. return ctrl.Result{}, nil
  477. }
  478. // detect errors indicating that the secret has another ExternalSecret as owner
  479. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  480. if errors.Is(err, ErrSecretIsOwned) {
  481. r.markAsFailed(msgErrorIsOwned, err, externalSecret, syncCallsError.With(resourceLabels))
  482. return ctrl.Result{}, nil
  483. }
  484. // detect errors indicating that the secret is immutable
  485. // NOTE: this error cant be fixed by retrying so we don't return an error (which would requeue immediately)
  486. if errors.Is(err, ErrSecretImmutable) {
  487. r.markAsFailed(msgErrorUpdateImmutable, err, externalSecret, syncCallsError.With(resourceLabels))
  488. return ctrl.Result{}, nil
  489. }
  490. r.markAsFailed(msgErrorUpdateSecret, err, externalSecret, syncCallsError.With(resourceLabels))
  491. return ctrl.Result{}, err
  492. }
  493. r.markAsDone(externalSecret, start, log, esv1.ConditionReasonSecretSynced, msgSynced)
  494. return r.getRequeueResult(externalSecret), nil
  495. }
  496. // getRequeueResult create a result with requeueAfter based on the ExternalSecret refresh interval.
  497. func (r *Reconciler) getRequeueResult(externalSecret *esv1.ExternalSecret) ctrl.Result {
  498. // default to the global requeue interval
  499. // note, this will never be used because the CRD has a default value of 1 hour
  500. refreshInterval := r.RequeueInterval
  501. if externalSecret.Spec.RefreshInterval != nil {
  502. refreshInterval = externalSecret.Spec.RefreshInterval.Duration
  503. }
  504. // if the refresh interval is <= 0, we should not requeue
  505. if refreshInterval <= 0 {
  506. return ctrl.Result{}
  507. }
  508. // if the last refresh time is not set, requeue after the refresh interval
  509. // note, this should not happen, as we only call this function on ExternalSecrets
  510. // that have been reconciled at least once
  511. if externalSecret.Status.RefreshTime.IsZero() {
  512. return ctrl.Result{RequeueAfter: refreshInterval}
  513. }
  514. timeSinceLastRefresh := time.Since(externalSecret.Status.RefreshTime.Time)
  515. // if the last refresh time is in the future, we should requeue immediately
  516. // note, this should not happen, as we always refresh an ExternalSecret
  517. // that has a last refresh time in the future
  518. if timeSinceLastRefresh < 0 {
  519. return ctrl.Result{Requeue: true}
  520. }
  521. // if there is time remaining, requeue after the remaining time
  522. if timeSinceLastRefresh < refreshInterval {
  523. return ctrl.Result{RequeueAfter: refreshInterval - timeSinceLastRefresh}
  524. }
  525. // otherwise, requeue immediately
  526. return ctrl.Result{Requeue: true}
  527. }
  528. func (r *Reconciler) markAsDone(externalSecret *esv1.ExternalSecret, start time.Time, log logr.Logger, reason, msg string) {
  529. oldReadyCondition := GetExternalSecretCondition(externalSecret.Status, esv1.ExternalSecretReady)
  530. newReadyCondition := NewExternalSecretCondition(esv1.ExternalSecretReady, v1.ConditionTrue, reason, msg)
  531. SetExternalSecretCondition(externalSecret, *newReadyCondition)
  532. externalSecret.Status.RefreshTime = metav1.NewTime(start)
  533. externalSecret.Status.SyncedResourceVersion = ctrlutil.GetResourceVersion(externalSecret.ObjectMeta)
  534. // if the status or reason has changed, log at the appropriate verbosity level
  535. if oldReadyCondition == nil || oldReadyCondition.Status != newReadyCondition.Status || oldReadyCondition.Reason != newReadyCondition.Reason {
  536. if newReadyCondition.Reason == esv1.ConditionReasonSecretDeleted {
  537. log.Info("deleted secret")
  538. } else {
  539. log.Info("reconciled secret")
  540. }
  541. } else {
  542. log.V(1).Info("reconciled secret")
  543. }
  544. }
  545. func (r *Reconciler) markAsFailed(msg string, err error, externalSecret *esv1.ExternalSecret, counter prometheus.Counter) {
  546. r.recorder.Event(externalSecret, v1.EventTypeWarning, esv1.ReasonUpdateFailed, err.Error())
  547. conditionSynced := NewExternalSecretCondition(esv1.ExternalSecretReady, v1.ConditionFalse, esv1.ConditionReasonSecretSyncedError, msg)
  548. SetExternalSecretCondition(externalSecret, *conditionSynced)
  549. counter.Inc()
  550. }
  551. func (r *Reconciler) cleanupManagedSecrets(ctx context.Context, log logr.Logger, externalSecret *esv1.ExternalSecret) error {
  552. // Only delete secrets if DeletionPolicy is Delete
  553. if externalSecret.Spec.Target.DeletionPolicy != esv1.DeletionPolicyDelete {
  554. log.V(1).Info("skipping secret deletion due to DeletionPolicy", "policy", externalSecret.Spec.Target.DeletionPolicy)
  555. return nil
  556. }
  557. secretName := externalSecret.Spec.Target.Name
  558. if secretName == "" {
  559. secretName = externalSecret.Name
  560. }
  561. var secret v1.Secret
  562. err := r.Get(ctx, types.NamespacedName{Name: secretName, Namespace: externalSecret.Namespace}, &secret)
  563. if err != nil {
  564. if apierrors.IsNotFound(err) {
  565. return nil
  566. }
  567. return err
  568. }
  569. // Only delete if we own it
  570. if metav1.IsControlledBy(&secret, externalSecret) {
  571. if err := r.Delete(ctx, &secret); err != nil && !apierrors.IsNotFound(err) {
  572. return err
  573. }
  574. log.V(1).Info("deleted managed secret", "secret", secretName)
  575. }
  576. return nil
  577. }
  578. func (r *Reconciler) deleteOrphanedSecrets(ctx context.Context, externalSecret *esv1.ExternalSecret, secretName string) error {
  579. ownerLabel := esutils.ObjectHash(fmt.Sprintf("%v/%v", externalSecret.Namespace, externalSecret.Name))
  580. // we use a PartialObjectMetadataList to avoid loading the full secret objects
  581. // and because the Secrets partials are always cached due to WatchesMetadata() in SetupWithManager()
  582. secretListPartial := &metav1.PartialObjectMetadataList{}
  583. secretListPartial.SetGroupVersionKind(v1.SchemeGroupVersion.WithKind("SecretList"))
  584. listOpts := &client.ListOptions{
  585. LabelSelector: labels.SelectorFromSet(map[string]string{
  586. esv1.LabelOwner: ownerLabel,
  587. }),
  588. Namespace: externalSecret.Namespace,
  589. }
  590. if err := r.List(ctx, secretListPartial, listOpts); err != nil {
  591. return err
  592. }
  593. // delete all secrets that are not the target secret
  594. for _, secretPartial := range secretListPartial.Items {
  595. if secretPartial.GetName() != secretName {
  596. err := r.Delete(ctx, &secretPartial)
  597. if err != nil && !apierrors.IsNotFound(err) {
  598. return err
  599. }
  600. r.recorder.Event(externalSecret, v1.EventTypeNormal, esv1.ReasonDeleted, eventDeletedOrphaned)
  601. }
  602. }
  603. return nil
  604. }
  605. // createSecret creates a new secret with the given mutation function.
  606. func (r *Reconciler) createSecret(ctx context.Context, mutationFunc func(secret *v1.Secret) error, es *esv1.ExternalSecret, secretName string) error {
  607. fqdn := fqdnFor(es.Name)
  608. // define and mutate the new secret
  609. newSecret := &v1.Secret{
  610. ObjectMeta: metav1.ObjectMeta{
  611. Name: secretName,
  612. Namespace: es.Namespace,
  613. },
  614. Data: make(map[string][]byte),
  615. }
  616. if err := mutationFunc(newSecret); err != nil {
  617. return err
  618. }
  619. // note, we set field owner even for Create
  620. if err := r.Create(ctx, newSecret, client.FieldOwner(fqdn)); err != nil {
  621. return err
  622. }
  623. // set the binding reference to the secret
  624. // https://github.com/external-secrets/external-secrets/pull/2263
  625. es.Status.Binding = v1.LocalObjectReference{Name: newSecret.Name}
  626. r.recorder.Event(es, v1.EventTypeNormal, esv1.ReasonCreated, eventCreated)
  627. return nil
  628. }
  629. func (r *Reconciler) updateSecret(ctx context.Context, existingSecret *v1.Secret, mutationFunc func(secret *v1.Secret) error, es *esv1.ExternalSecret, secretName string) error {
  630. fqdn := fqdnFor(es.Name)
  631. // fail if the secret does not exist
  632. // this should never happen because we check this before calling this function
  633. if existingSecret.UID == "" {
  634. return fmt.Errorf(errUpdateNotFound, secretName)
  635. }
  636. // set the binding reference to the secret
  637. // https://github.com/external-secrets/external-secrets/pull/2263
  638. es.Status.Binding = v1.LocalObjectReference{Name: secretName}
  639. // mutate a copy of the existing secret with the mutation function
  640. updatedSecret := existingSecret.DeepCopy()
  641. if err := mutationFunc(updatedSecret); err != nil {
  642. return fmt.Errorf(errMutate, updatedSecret.Name, err)
  643. }
  644. // if the secret does not need to be updated, return early
  645. if equality.Semantic.DeepEqual(existingSecret, updatedSecret) {
  646. return nil
  647. }
  648. // if the existing secret is immutable, we can only update the object metadata
  649. if ptr.Deref(existingSecret.Immutable, false) {
  650. // check if the metadata was changed
  651. metadataChanged := !equality.Semantic.DeepEqual(existingSecret.ObjectMeta, updatedSecret.ObjectMeta)
  652. // check if the immutable data/type was changed
  653. var dataChanged bool
  654. if metadataChanged {
  655. // update the `existingSecret` object with the metadata from `updatedSecret`
  656. // this lets us compare the objects to see if the immutable data/type was changed
  657. existingSecret.ObjectMeta = *updatedSecret.ObjectMeta.DeepCopy()
  658. dataChanged = !equality.Semantic.DeepEqual(existingSecret, updatedSecret)
  659. // because we use labels and annotations to keep track of the secret,
  660. // we need to update the metadata, regardless of if the immutable data was changed
  661. // NOTE: we are using the `existingSecret` object here, as we ONLY want to update the metadata,
  662. // and we previously copied the metadata from the `updatedSecret` object
  663. if err := r.Update(ctx, existingSecret, client.FieldOwner(fqdn)); err != nil {
  664. // if we get a conflict, we should return early to requeue immediately
  665. // note, we don't wrap this error so we can handle it in the caller
  666. if apierrors.IsConflict(err) {
  667. return err
  668. }
  669. return fmt.Errorf(errUpdate, existingSecret.Name, err)
  670. }
  671. } else {
  672. // we know there was some change in the secret (or we would have returned early)
  673. // we know the metadata was NOT changed (metadataChanged == false)
  674. // so, the only thing that could have changed is the immutable data/type fields
  675. dataChanged = true
  676. }
  677. // if the immutable data was changed, we should return an error
  678. if dataChanged {
  679. return fmt.Errorf(errUpdate, existingSecret.Name, ErrSecretImmutable)
  680. }
  681. }
  682. // update the secret
  683. if err := r.Update(ctx, updatedSecret, client.FieldOwner(fqdn)); err != nil {
  684. // if we get a conflict, we should return early to requeue immediately
  685. // note, we don't wrap this error so we can handle it in the caller
  686. if apierrors.IsConflict(err) {
  687. return err
  688. }
  689. return fmt.Errorf(errUpdate, updatedSecret.Name, err)
  690. }
  691. r.recorder.Event(es, v1.EventTypeNormal, esv1.ReasonUpdated, eventUpdated)
  692. return nil
  693. }
  694. // getManagedDataKeys returns the list of data keys in a secret which are managed by a specified owner.
  695. func getManagedDataKeys(secret *v1.Secret, fieldOwner string) ([]string, error) {
  696. return getManagedFieldKeys(secret, fieldOwner, func(fields map[string]any) []string {
  697. dataFields := fields["f:data"]
  698. if dataFields == nil {
  699. return nil
  700. }
  701. df, ok := dataFields.(map[string]any)
  702. if !ok {
  703. return nil
  704. }
  705. return slices.Collect(maps.Keys(df))
  706. })
  707. }
  708. func getManagedFieldKeys(
  709. secret *v1.Secret,
  710. fieldOwner string,
  711. process func(fields map[string]any) []string,
  712. ) ([]string, error) {
  713. fqdn := fqdnFor(fieldOwner)
  714. var keys []string
  715. for _, v := range secret.ObjectMeta.ManagedFields {
  716. if v.Manager != fqdn {
  717. continue
  718. }
  719. fields := make(map[string]any)
  720. err := json.Unmarshal(v.FieldsV1.Raw, &fields)
  721. if err != nil {
  722. return nil, fmt.Errorf("error unmarshaling managed fields: %w", err)
  723. }
  724. for _, key := range process(fields) {
  725. if key == "." {
  726. continue
  727. }
  728. keys = append(keys, strings.TrimPrefix(key, "f:"))
  729. }
  730. }
  731. return keys, nil
  732. }
  733. func shouldSkipClusterSecretStore(r *Reconciler, es *esv1.ExternalSecret) bool {
  734. return !r.ClusterSecretStoreEnabled && es.Spec.SecretStoreRef.Kind == esv1.ClusterSecretStoreKind
  735. }
  736. // shouldSkipUnmanagedStore iterates over all secretStore references in the externalSecret spec,
  737. // fetches the store and evaluates the controllerClass property.
  738. // Returns true if any storeRef points to store with a non-matching controllerClass.
  739. func shouldSkipUnmanagedStore(ctx context.Context, namespace string, r *Reconciler, es *esv1.ExternalSecret) (bool, error) {
  740. var storeList []esv1.SecretStoreRef
  741. if es.Spec.SecretStoreRef.Name != "" {
  742. storeList = append(storeList, es.Spec.SecretStoreRef)
  743. }
  744. for _, ref := range es.Spec.Data {
  745. if ref.SourceRef != nil {
  746. storeList = append(storeList, ref.SourceRef.SecretStoreRef)
  747. }
  748. }
  749. for _, ref := range es.Spec.DataFrom {
  750. if ref.SourceRef != nil && ref.SourceRef.SecretStoreRef != nil {
  751. storeList = append(storeList, *ref.SourceRef.SecretStoreRef)
  752. }
  753. // verify that generator's controllerClass matches
  754. if ref.SourceRef != nil && ref.SourceRef.GeneratorRef != nil {
  755. _, obj, err := resolvers.GeneratorRef(ctx, r.Client, r.Scheme, namespace, ref.SourceRef.GeneratorRef)
  756. if err != nil {
  757. if apierrors.IsNotFound(err) {
  758. // skip non-existent generators
  759. continue
  760. }
  761. if errors.Is(err, resolvers.ErrUnableToGetGenerator) {
  762. // skip generators that we can't get (e.g. due to being invalid)
  763. continue
  764. }
  765. return false, err
  766. }
  767. skipGenerator, err := shouldSkipGenerator(r, obj)
  768. if err != nil {
  769. return false, err
  770. }
  771. if skipGenerator {
  772. return true, nil
  773. }
  774. }
  775. }
  776. for _, ref := range storeList {
  777. var store esv1.GenericStore
  778. switch ref.Kind {
  779. case esv1.SecretStoreKind, "":
  780. store = &esv1.SecretStore{}
  781. case esv1.ClusterSecretStoreKind:
  782. store = &esv1.ClusterSecretStore{}
  783. namespace = ""
  784. default:
  785. return false, fmt.Errorf("unsupported secret store kind: %s", ref.Kind)
  786. }
  787. err := r.Get(ctx, types.NamespacedName{
  788. Name: ref.Name,
  789. Namespace: namespace,
  790. }, store)
  791. if err != nil {
  792. if apierrors.IsNotFound(err) {
  793. // skip non-existent stores
  794. continue
  795. }
  796. return false, err
  797. }
  798. class := store.GetSpec().Controller
  799. if class != "" && class != r.ControllerClass {
  800. return true, nil
  801. }
  802. }
  803. return false, nil
  804. }
  805. func shouldRefresh(es *esv1.ExternalSecret) bool {
  806. switch es.Spec.RefreshPolicy {
  807. case esv1.RefreshPolicyCreatedOnce:
  808. if es.Status.SyncedResourceVersion == "" || es.Status.RefreshTime.IsZero() {
  809. return true
  810. }
  811. return false
  812. case esv1.RefreshPolicyOnChange:
  813. if es.Status.SyncedResourceVersion == "" || es.Status.RefreshTime.IsZero() {
  814. return true
  815. }
  816. return es.Status.SyncedResourceVersion != ctrlutil.GetResourceVersion(es.ObjectMeta)
  817. case esv1.RefreshPolicyPeriodic:
  818. return shouldRefreshPeriodic(es)
  819. default:
  820. return shouldRefreshPeriodic(es)
  821. }
  822. }
  823. func shouldRefreshPeriodic(es *esv1.ExternalSecret) bool {
  824. // if the refresh interval is 0, and we have synced previously, we should not refresh
  825. if es.Spec.RefreshInterval.Duration <= 0 && es.Status.SyncedResourceVersion != "" {
  826. return false
  827. }
  828. // if the ExternalSecret has been updated, we should refresh
  829. if es.Status.SyncedResourceVersion != ctrlutil.GetResourceVersion(es.ObjectMeta) {
  830. return true
  831. }
  832. // if the last refresh time is zero, we should refresh
  833. if es.Status.RefreshTime.IsZero() {
  834. return true
  835. }
  836. // if the last refresh time is in the future, we should refresh
  837. if es.Status.RefreshTime.Time.After(time.Now()) {
  838. return true
  839. }
  840. // if the last refresh time + refresh interval is before now, we should refresh
  841. return es.Status.RefreshTime.Add(es.Spec.RefreshInterval.Duration).Before(time.Now())
  842. }
  843. // isSecretValid checks if the secret exists, and it's data is consistent with the calculated hash.
  844. func isSecretValid(existingSecret *v1.Secret, es *esv1.ExternalSecret) bool {
  845. // Secret is always valid with `CreationPolicy=Orphan`
  846. if es.Spec.Target.CreationPolicy == esv1.CreatePolicyOrphan {
  847. return true
  848. }
  849. if existingSecret.UID == "" {
  850. return false
  851. }
  852. // if the managed label is missing or incorrect, then it's invalid
  853. if existingSecret.Labels[esv1.LabelManaged] != esv1.LabelManagedValue {
  854. return false
  855. }
  856. // if the data-hash annotation is missing or incorrect, then it's invalid
  857. // this is how we know if the data has chanced since we last updated the secret
  858. if existingSecret.Annotations[esv1.AnnotationDataHash] != esutils.ObjectHash(existingSecret.Data) {
  859. return false
  860. }
  861. return true
  862. }
  863. // SetupWithManager returns a new controller builder that will be started by the provided Manager.
  864. func (r *Reconciler) SetupWithManager(mgr ctrl.Manager, opts controller.Options) error {
  865. r.recorder = mgr.GetEventRecorderFor("external-secrets")
  866. // index ExternalSecrets based on the target secret name,
  867. // this lets us quickly find all ExternalSecrets which target a specific Secret
  868. if err := mgr.GetFieldIndexer().IndexField(context.Background(), &esv1.ExternalSecret{}, indexESTargetSecretNameField, func(obj client.Object) []string {
  869. es := obj.(*esv1.ExternalSecret)
  870. // if the target name is set, use that as the index
  871. if es.Spec.Target.Name != "" {
  872. return []string{es.Spec.Target.Name}
  873. }
  874. // otherwise, use the ExternalSecret name
  875. return []string{es.Name}
  876. }); err != nil {
  877. return err
  878. }
  879. // predicate function to ignore secret events unless they have the "managed" label
  880. secretHasESLabel := predicate.NewPredicateFuncs(func(object client.Object) bool {
  881. value, hasLabel := object.GetLabels()[esv1.LabelManaged]
  882. return hasLabel && value == esv1.LabelManagedValue
  883. })
  884. return ctrl.NewControllerManagedBy(mgr).
  885. WithOptions(opts).
  886. For(&esv1.ExternalSecret{}).
  887. // we cant use Owns(), as we don't set ownerReferences when the creationPolicy is not Owner.
  888. // we use WatchesMetadata() to reduce memory usage, as otherwise we have to process full secret objects.
  889. WatchesMetadata(
  890. &v1.Secret{},
  891. handler.EnqueueRequestsFromMapFunc(r.findObjectsForSecret),
  892. builder.WithPredicates(predicate.ResourceVersionChangedPredicate{}, secretHasESLabel),
  893. ).
  894. Complete(r)
  895. }
  896. func (r *Reconciler) findObjectsForSecret(ctx context.Context, secret client.Object) []reconcile.Request {
  897. externalSecretsList := &esv1.ExternalSecretList{}
  898. listOps := &client.ListOptions{
  899. FieldSelector: fields.OneTermEqualSelector(indexESTargetSecretNameField, secret.GetName()),
  900. Namespace: secret.GetNamespace(),
  901. }
  902. err := r.List(ctx, externalSecretsList, listOps)
  903. if err != nil {
  904. return []reconcile.Request{}
  905. }
  906. requests := make([]reconcile.Request, len(externalSecretsList.Items))
  907. for i := range externalSecretsList.Items {
  908. requests[i] = reconcile.Request{
  909. NamespacedName: types.NamespacedName{
  910. Name: externalSecretsList.Items[i].GetName(),
  911. Namespace: externalSecretsList.Items[i].GetNamespace(),
  912. },
  913. }
  914. }
  915. return requests
  916. }