--- AWSTemplateFormatVersion: 2010-09-09 Description: > This template deploys a Lambda function that can be used to clean/empty an S3 bucket before it is deleted Resources: CleanupBucketLambdaFunction: Type: 'AWS::Lambda::Function' Properties: Description: 'Retail Demo Store deployment utility function that deletes all objects in an S3 bucket when the CloudFormation stack is deleted' Code: ZipFile: | import boto3 import cfnresponse def handler(event, context): print(event) responseData = {} responseStatus = cfnresponse.SUCCESS try: bucketName = event['ResourceProperties']['BucketName'] if event['RequestType'] == 'Create': responseData['Message'] = "Resource creation succeeded" elif event['RequestType'] == 'Update': responseData['Message'] = "Resource update succeeded" elif event['RequestType'] == 'Delete': # Empty the S3 bucket s3 = boto3.resource('s3') bucket = s3.Bucket(bucketName) bucket.object_versions.delete() #delete all versions of objects responseData['Message'] = "Resource deletion succeeded" except Exception as e: print("Error: " + str(e)) responseStatus = cfnresponse.FAILED responseData['Message'] = "Resource {} failed: {}".format(event['RequestType'], e) cfnresponse.send(event, context, responseStatus, responseData) Handler: index.handler Runtime: python3.7 Timeout: 300 Role: !GetAtt CleanupBucketLambdaExecutionRole.Arn CleanupBucketLambdaExecutionRole: Type: 'AWS::IAM::Role' Properties: AssumeRolePolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Principal: Service: lambda.amazonaws.com Action: - 'sts:AssumeRole' Policies: - PolicyName: LoggingPolicy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - logs:CreateLogGroup - logs:CreateLogStream - logs:PutLogEvents Resource: '*' - PolicyName: S3Policy PolicyDocument: Version: 2012-10-17 Statement: - Effect: Allow Action: - s3:List* - s3:DeleteObject - s3:DeleteObjectVersion Resource: '*' Outputs: LambdaFunctionArn: Description: Lambda function ARN for S3 bucket cleanup utility Value: !GetAtt CleanupBucketLambdaFunction.Arn