2 Answers
- Newest
- Most votes
- Most comments
1
The site below has a Lambda sample that deletes objects in an S3 bucket.
https://stackoverflow.com/questions/40383470/can-i-force-cloudformation-to-delete-non-empty-s3-bucket
Only the "requests" module has changed.
Create a Lambda function with the code below.
Create a "requests" layer in your Lambda function.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import boto3
import requests
def lambda_handler(event, context):
try:
bucket = event['ResourceProperties']['BucketName']
if event['RequestType'] == 'Delete':
s3 = boto3.resource('s3')
bucket = s3.Bucket(bucket)
for obj in bucket.objects.filter():
s3.Object(bucket.name, obj.key).delete()
sendResponseCfn(event, context, "SUCCESS")
except Exception as e:
print(e)
sendResponseCfn(event, context, "FAILED")
def sendResponseCfn(event, context, responseStatus):
response_body = {'Status': responseStatus,
'Reason': 'Log stream name: ' + context.log_stream_name,
'PhysicalResourceId': context.log_stream_name,
'StackId': event['StackId'],
'RequestId': event['RequestId'],
'LogicalResourceId': event['LogicalResourceId'],
'Data': json.loads("{}")}
requests.put(event['ResponseURL'], data=json.dumps(response_body))
Specify the ARN of Lambda in the custom resource as follows.
AWSTemplateFormatVersion: '2010-09-09'
Resources:
myBucketResource:
Type: AWS::S3::Bucket
Properties:
BucketName: test-bucket
LambdaUsedToCleanUp:
Type: Custom::cleanupbucket
Properties:
ServiceToken: arn:aws:lambda:us-west-2:XXXXXXXXXXXX:function:lambda_function_name
BucketName: !Ref myBucketResource
0
Hi, this may be what you're looking for: https://adriandrummond.com/2019/04/02/how-to-delete-s3-bucket-contents-in-cloudformation/
Relevant content
- Accepted Answerasked 3 months ago
- AWS OFFICIALUpdated a year ago
- AWS OFFICIALUpdated 7 days ago
- AWS OFFICIALUpdated a month ago