Skip to content

Commit 8b2aaf3

Browse files
author
Yuriy Bezsonov
committed
Improve S3 cleanup
1 parent 26a8254 commit 8b2aaf3

7 files changed

Lines changed: 150 additions & 426 deletions

File tree

infra/cdk/src/main/java/sample/com/constructs/WorkshopBucket.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,12 +45,12 @@ public WorkshopBucket(final Construct scope, final String id, final WorkshopBuck
4545
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
4646

4747
// Create S3 bucket for workshop data (thread dumps, profiling data)
48+
// Note: autoDeleteObjects removed - CfnPreDeleteCleanup Lambda handles bucket emptying
4849
this.bucket = Bucket.Builder.create(this, "Bucket")
4950
.bucketName(String.format("%s-bucket-%s-%s-%s", prefix, Aws.ACCOUNT_ID, Aws.REGION, timestamp))
5051
.blockPublicAccess(BlockPublicAccess.BLOCK_ALL)
5152
.enforceSsl(true)
5253
.removalPolicy(RemovalPolicy.DESTROY)
53-
.autoDeleteObjects(true)
5454
.build();
5555

5656
// Create SSM parameter for bucket name discovery

infra/cdk/src/main/resources/lambda/cfn-pre-delete-cleanup.py

Lines changed: 6 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
ec2 = boto3.client('ec2')
66
logs = boto3.client('logs')
77
s3 = boto3.client('s3')
8+
s3_resource = boto3.resource('s3')
89

910
def lambda_handler(event, context):
1011
"""
@@ -139,58 +140,15 @@ def cleanup_s3_buckets():
139140
print("S3 bucket cleanup completed")
140141

141142
def empty_bucket(bucket_name):
142-
"""Delete all objects and versions from a bucket."""
143+
"""Delete all objects and versions from a bucket using boto3 resource API."""
143144
try:
144-
# Delete all object versions (for versioned buckets)
145-
paginator = s3.get_paginator('list_object_versions')
146-
try:
147-
for page in paginator.paginate(Bucket=bucket_name):
148-
objects_to_delete = []
149-
150-
# Collect versions
151-
for version in page.get('Versions', []):
152-
objects_to_delete.append({
153-
'Key': version['Key'],
154-
'VersionId': version['VersionId']
155-
})
156-
157-
# Collect delete markers
158-
for marker in page.get('DeleteMarkers', []):
159-
objects_to_delete.append({
160-
'Key': marker['Key'],
161-
'VersionId': marker['VersionId']
162-
})
163-
164-
if objects_to_delete:
165-
s3.delete_objects(
166-
Bucket=bucket_name,
167-
Delete={'Objects': objects_to_delete}
168-
)
169-
print(f"Deleted {len(objects_to_delete)} objects from {bucket_name}")
170-
except s3.exceptions.ClientError as e:
171-
# Bucket might not have versioning, try regular delete
172-
if 'NoSuchBucket' not in str(e):
173-
delete_objects_without_versions(bucket_name)
174-
145+
bucket = s3_resource.Bucket(bucket_name)
146+
# Delete all object versions (handles both versioned and non-versioned buckets)
147+
bucket.object_versions.delete()
148+
print(f"Emptied bucket: {bucket_name}")
175149
except Exception as e:
176150
print(f"Error emptying bucket {bucket_name}: {e}")
177151

178-
def delete_objects_without_versions(bucket_name):
179-
"""Delete objects from non-versioned bucket."""
180-
try:
181-
paginator = s3.get_paginator('list_objects_v2')
182-
for page in paginator.paginate(Bucket=bucket_name):
183-
objects = page.get('Contents', [])
184-
if objects:
185-
objects_to_delete = [{'Key': obj['Key']} for obj in objects]
186-
s3.delete_objects(
187-
Bucket=bucket_name,
188-
Delete={'Objects': objects_to_delete}
189-
)
190-
print(f"Deleted {len(objects_to_delete)} objects from {bucket_name}")
191-
except Exception as e:
192-
print(f"Error deleting objects from {bucket_name}: {e}")
193-
194152
def wait_for_deletion(endpoint_ids, max_wait=300):
195153
"""Poll until endpoints are deleted or timeout."""
196154
start_time = time.time()

infra/cfn/base-stack.yaml

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -676,6 +676,28 @@ Resources:
676676
Fn::GetAtt:
677677
- IdeInstanceLauncherFunction803C5A2A
678678
- Arn
679+
InstanceName: ide
680+
IamInstanceProfileArn:
681+
Fn::GetAtt:
682+
- IdeInstanceProfile61B92038
683+
- Arn
684+
VolumeSize: "50"
685+
SubnetIds:
686+
Fn::Join:
687+
- ""
688+
- - Ref: VpcPublicSubnet1Subnet8E8DEDC0
689+
- ","
690+
- Ref: VpcPublicSubnet2SubnetA811849C
691+
SecurityGroupIds:
692+
Fn::Join:
693+
- ""
694+
- - Fn::GetAtt:
695+
- IdeSecurityGroup73B02454
696+
- GroupId
697+
- ","
698+
- Fn::GetAtt:
699+
- IdeInternalSecurityGroupB0A5D76B
700+
- GroupId
679701
ImageId:
680702
Ref: SsmParameterValueawsserviceamiamazonlinuxlatestal2023amikernel61arm64C96584B6F00A464EAD1953AFF4B05118Parameter
681703
UserData:
@@ -815,28 +837,6 @@ Resources:
815837
exit 1
816838
fi
817839
InstanceTypes: m7g.xlarge,m6g.xlarge,c7g.xlarge,t4g.xlarge
818-
InstanceName: ide
819-
IamInstanceProfileArn:
820-
Fn::GetAtt:
821-
- IdeInstanceProfile61B92038
822-
- Arn
823-
VolumeSize: "50"
824-
SubnetIds:
825-
Fn::Join:
826-
- ""
827-
- - Ref: VpcPublicSubnet1Subnet8E8DEDC0
828-
- ","
829-
- Ref: VpcPublicSubnet2SubnetA811849C
830-
SecurityGroupIds:
831-
Fn::Join:
832-
- ""
833-
- - Fn::GetAtt:
834-
- IdeSecurityGroup73B02454
835-
- GroupId
836-
- ","
837-
- Fn::GetAtt:
838-
- IdeInternalSecurityGroupB0A5D76B
839-
- GroupId
840840
UpdateReplacePolicy: Delete
841841
DeletionPolicy: Delete
842842
IdeEipAssociationDFF81215:

infra/cfn/java-ai-agents-stack.yaml

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -757,12 +757,30 @@ Resources:
757757
Fn::GetAtt:
758758
- IdeInstanceLauncherFunction803C5A2A
759759
- Arn
760+
InstanceName: ide
760761
IamInstanceProfileArn:
761762
Fn::GetAtt:
762763
- IdeInstanceProfile61B92038
763764
- Arn
764-
InstanceName: ide
765-
InstanceTypes: m7g.xlarge,m6g.xlarge,c7g.xlarge,t4g.xlarge
765+
VolumeSize: "50"
766+
SubnetIds:
767+
Fn::Join:
768+
- ""
769+
- - Ref: VpcPublicSubnet1Subnet8E8DEDC0
770+
- ","
771+
- Ref: VpcPublicSubnet2SubnetA811849C
772+
SecurityGroupIds:
773+
Fn::Join:
774+
- ""
775+
- - Fn::GetAtt:
776+
- IdeSecurityGroup73B02454
777+
- GroupId
778+
- ","
779+
- Fn::GetAtt:
780+
- IdeInternalSecurityGroupB0A5D76B
781+
- GroupId
782+
ImageId:
783+
Ref: SsmParameterValueawsserviceamiamazonlinuxlatestal2023amikernel61arm64C96584B6F00A464EAD1953AFF4B05118Parameter
766784
UserData:
767785
Fn::Base64:
768786
Fn::Join:
@@ -899,25 +917,7 @@ Resources:
899917
"
900918
exit 1
901919
fi
902-
ImageId:
903-
Ref: SsmParameterValueawsserviceamiamazonlinuxlatestal2023amikernel61arm64C96584B6F00A464EAD1953AFF4B05118Parameter
904-
SecurityGroupIds:
905-
Fn::Join:
906-
- ""
907-
- - Fn::GetAtt:
908-
- IdeSecurityGroup73B02454
909-
- GroupId
910-
- ","
911-
- Fn::GetAtt:
912-
- IdeInternalSecurityGroupB0A5D76B
913-
- GroupId
914-
SubnetIds:
915-
Fn::Join:
916-
- ""
917-
- - Ref: VpcPublicSubnet1Subnet8E8DEDC0
918-
- ","
919-
- Ref: VpcPublicSubnet2SubnetA811849C
920-
VolumeSize: "50"
920+
InstanceTypes: m7g.xlarge,m6g.xlarge,c7g.xlarge,t4g.xlarge
921921
UpdateReplacePolicy: Delete
922922
DeletionPolicy: Delete
923923
IdeEipAssociationDFF81215:

0 commit comments

Comments
 (0)