externalsecret_controller.go 40 KB

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