Skip to content

Commit

Permalink
Use precondition when deleting secrets (elastic#5273)
Browse files Browse the repository at this point in the history
  • Loading branch information
srteam2020 authored and fantapsody committed Jan 3, 2023
1 parent 606d692 commit 17b0b2a
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
3 changes: 2 additions & 1 deletion pkg/controller/association/resources.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"go.elastic.co/apm"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"

Expand Down Expand Up @@ -50,7 +51,7 @@ func deleteOrphanedResources(

// Secret for the `associated` resource doesn't match any `association` - it's not needed anymore and should be deleted.
log.Info("Deleting secret", "namespace", secret.Namespace, "secret_name", secret.Name, "associated_name", associated.Name)
if err := c.Delete(context.Background(), &secret); err != nil && !apierrors.IsNotFound(err) {
if err := c.Delete(context.Background(), &secret, &client.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &secret.UID}}); err != nil && !apierrors.IsNotFound(err) {
return err
}

Expand Down
6 changes: 4 additions & 2 deletions pkg/controller/common/reconciler/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
Expand Down Expand Up @@ -158,7 +159,7 @@ func GarbageCollectSoftOwnedSecrets(c k8s.Client, deletedOwner types.NamespacedN
log.Info("Garbage collecting secret",
"namespace", deletedOwner.Namespace, "secret_name", s.Name,
"owner_name", deletedOwner.Name, "owner_kind", ownerKind)
err := c.Delete(context.Background(), &s)
err := c.Delete(context.Background(), &s, &client.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &s.UID}})
if apierrors.IsNotFound(err) {
// already deleted, all good
continue
Expand Down Expand Up @@ -210,7 +211,8 @@ func GarbageCollectAllSoftOwnedOrphanSecrets(c k8s.Client, ownerKinds map[string
"namespace", secret.Namespace, "secret_name", secret.Name,
"owner_kind", softOwner.Kind, "owner_namespace", softOwner.Namespace, "owner_name", softOwner.Name,
)
if err := c.Delete(context.Background(), &secret); err != nil && !apierrors.IsNotFound(err) {
options := client.DeleteOptions{Preconditions: &metav1.Preconditions{UID: &secret.UID}}
if err := c.Delete(context.Background(), &secret, &options); err != nil && !apierrors.IsNotFound(err) {
return err
}
continue
Expand Down

0 comments on commit 17b0b2a

Please sign in to comment.