From 1aa4794834b9052bf427519f8db5649b4754cf63 Mon Sep 17 00:00:00 2001 From: Otavio Macedo Date: Fri, 8 Oct 2021 13:02:31 +0100 Subject: [PATCH] fix(s3): auto-delete fails when bucket has been deleted manually (#16645) Even though buckets are not supposed to be deleted manually, this change makes the delete operation idempotent and thus more reliable. Fixes #16619. ---- *By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license* --- .../lib/auto-delete-objects-handler/index.ts | 9 ++++++++- .../test/auto-delete-objects-handler.test.ts | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/packages/@aws-cdk/aws-s3/lib/auto-delete-objects-handler/index.ts b/packages/@aws-cdk/aws-s3/lib/auto-delete-objects-handler/index.ts index fed602825c6a0..2459d44ab1d18 100644 --- a/packages/@aws-cdk/aws-s3/lib/auto-delete-objects-handler/index.ts +++ b/packages/@aws-cdk/aws-s3/lib/auto-delete-objects-handler/index.ts @@ -58,7 +58,14 @@ async function onDelete(bucketName?: string) { process.stdout.write(`Bucket does not have '${AUTO_DELETE_OBJECTS_TAG}' tag, skipping cleaning.\n`); return; } - await emptyBucket(bucketName); + try { + await emptyBucket(bucketName); + } catch (e) { + if (e.code !== 'NoSuchBucket') { + throw e; + } + // Bucket doesn't exist. Ignoring + } } /** diff --git a/packages/@aws-cdk/aws-s3/test/auto-delete-objects-handler.test.ts b/packages/@aws-cdk/aws-s3/test/auto-delete-objects-handler.test.ts index 51cc65b3d5466..b4b7f523faef2 100644 --- a/packages/@aws-cdk/aws-s3/test/auto-delete-objects-handler.test.ts +++ b/packages/@aws-cdk/aws-s3/test/auto-delete-objects-handler.test.ts @@ -287,6 +287,23 @@ test('delete event where bucket has many objects does recurse appropriately', as }); }); +test('does nothing when the bucket does not exist', async () => { + // GIVEN + mockS3Client.promise.mockRejectedValue({ code: 'NoSuchBucket' }); + + // WHEN + const event: Partial = { + RequestType: 'Delete', + ResourceProperties: { + ServiceToken: 'Foo', + BucketName: 'MyBucket', + }, + }; + await invokeHandler(event); + + expect(mockS3Client.deleteObjects).not.toHaveBeenCalled(); +}); + // helper function to get around TypeScript expecting a complete event object, // even though our tests only need some of the fields async function invokeHandler(event: Partial) {