@@ -10,6 +10,8 @@ import (
1010 "strings"
1111
1212 v1 "k8s.io/api/admission/v1"
13+ apierrors "k8s.io/apimachinery/pkg/api/errors"
14+ "sigs.k8s.io/controller-runtime/pkg/client"
1315 "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
1416)
1517
@@ -18,7 +20,7 @@ import (
1820// +k8s:deepcopy-gen=false
1921// ByoHostValidator validates ByoHosts
2022type ByoHostValidator struct {
21- // Client client.Client
23+ Client client.Client
2224 decoder * admission.Decoder
2325}
2426
@@ -34,7 +36,7 @@ func (v *ByoHostValidator) Handle(ctx context.Context, req admission.Request) ad
3436 case v1 .Create , v1 .Update :
3537 response = v .handleCreateUpdate (& req )
3638 case v1 .Delete :
37- response = v .handleDelete (& req )
39+ response = v .handleDelete (ctx , & req )
3840 default :
3941 response = admission .Allowed ("" )
4042 }
@@ -61,13 +63,29 @@ func (v *ByoHostValidator) handleCreateUpdate(req *admission.Request) admission.
6163 return admission .Allowed ("" )
6264}
6365
64- func (v * ByoHostValidator ) handleDelete (req * admission.Request ) admission.Response {
66+ func (v * ByoHostValidator ) handleDelete (ctx context. Context , req * admission.Request ) admission.Response {
6567 byoHost := & ByoHost {}
6668 err := v .decoder .DecodeRaw (req .OldObject , byoHost )
6769 if err != nil {
6870 return admission .Errored (http .StatusBadRequest , err )
6971 }
7072 if byoHost .Status .MachineRef != nil {
73+ // allow webhook to delete ByoHost when MachineRef is assigned but respective byoMachine doesn't exist
74+ byoMachine := byoHost .Status .MachineRef .Name
75+
76+ // Fetch the ByoMachine instance
77+ byoMachineObj := & ByoMachine {}
78+ err = v .Client .Get (ctx , client.ObjectKey {
79+ Name : byoMachine ,
80+ Namespace : byoHost .Namespace ,
81+ }, byoMachineObj )
82+ if err != nil {
83+ if apierrors .IsNotFound (err ) {
84+ return admission .Allowed ("" )
85+ }
86+ return admission .Denied ("cannot delete ByoHost when byomachine exists" )
87+ }
88+
7189 return admission .Denied ("cannot delete ByoHost when MachineRef is assigned" )
7290 }
7391 return admission .Allowed ("" )
0 commit comments