Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (12.9k points)

Is there any way to force CloudFormation to delete a non-empty S3 Bucket?

1 Answer

0 votes
by (18.2k points)

You can try creating a lambda function that wipes up your bucket. You'll have to invoke your lambda function from CloudFormation.

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import json

import boto3

from botocore.vendored import requests

def our_lambda(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))

To invoke your lambda, you can try the following code block.

 ---

 AWSTemplateFormatVersion: '2010-09-09'

 Resources:

   myBucketResource:

     Type: AWS::S3::Bucket

     Properties:

       BucketName: my-test-bucket-cleaning-on-delete

   cleanupBucketOnDelete:

     Type: Custom::cleanupbucket

     Properties:

       ServiceToken: arn:aws:lambda:eu-west-1:123456789012:function:clean-bucket-lambda

       BucketName: !Ref myBucketResource

Related questions

0 votes
1 answer

Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

Browse Categories

...