Skip to content

Commit 4605c9e

Browse files
committed
Retry VM Delete without Force if Bad Request
Azure Stack returns a 400 error when trying to delete a VM with the force flag and the error message suggests retrying without the flag.
1 parent bdbe2bc commit 4605c9e

File tree

2 files changed

+15
-2
lines changed

2 files changed

+15
-2
lines changed

azure/errors.go

+6
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,12 @@ func ResourceNotFound(err error) bool {
3434
return errors.As(err, &rerr) && rerr.StatusCode == http.StatusNotFound
3535
}
3636

37+
// BadRequest parses an error to check if it its status code is Bad Request (400).
38+
func BadRequest(err error) bool {
39+
var rerr *azcore.ResponseError
40+
return errors.As(err, &rerr) && rerr.StatusCode == http.StatusBadRequest
41+
}
42+
3743
// VMDeletedError is returned when a virtual machine is deleted outside of capz.
3844
type VMDeletedError struct {
3945
ProviderID string

azure/services/virtualmachines/client.go

+9-2
Original file line numberDiff line numberDiff line change
@@ -109,14 +109,21 @@ func (ac *AzureClient) CreateOrUpdateAsync(ctx context.Context, spec azure.Resou
109109
// request to Azure and if accepted without error, the func will return a Poller which can be used to track the ongoing
110110
// progress of the operation.
111111
func (ac *AzureClient) DeleteAsync(ctx context.Context, spec azure.ResourceSpecGetter, resumeToken string) (poller *runtime.Poller[armcompute.VirtualMachinesClientDeleteResponse], err error) {
112-
ctx, _, done := tele.StartSpanWithLogger(ctx, "virtualmachines.AzureClient.Delete")
112+
ctx, log, done := tele.StartSpanWithLogger(ctx, "virtualmachines.AzureClient.Delete")
113113
defer done()
114114

115115
forceDelete := ptr.To(true)
116116
opts := &armcompute.VirtualMachinesClientBeginDeleteOptions{ResumeToken: resumeToken, ForceDeletion: forceDelete}
117117
poller, err = ac.virtualmachines.BeginDelete(ctx, spec.ResourceGroupName(), spec.ResourceName(), opts)
118118
if err != nil {
119-
return nil, err
119+
if azure.BadRequest(err) {
120+
log.Info("Failed to Begin VM Delete with Force Deletion, retrying without the force flag")
121+
opts.ForceDeletion = ptr.To(false)
122+
poller, err = ac.virtualmachines.BeginDelete(ctx, spec.ResourceGroupName(), spec.ResourceName(), opts)
123+
}
124+
if err != nil {
125+
return nil, err
126+
}
120127
}
121128

122129
ctx, cancel := context.WithTimeout(ctx, ac.apiCallTimeout)

0 commit comments

Comments
 (0)