Can I force CloudFormation to delete non-empty S3 Bucket?












19















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










share|improve this question





























    19















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










    share|improve this question



























      19












      19








      19


      6






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










      share|improve this question
















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







      amazon-web-services amazon-s3 aws-cli






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 12 '16 at 11:17









      Arafat Nalkhande

      4,42941943




      4,42941943










      asked Nov 2 '16 at 15:13









      Jamie CzuyJamie Czuy

      438415




      438415
























          4 Answers
          4






          active

          oldest

          votes


















          22














          You can create a lambda function to clean up your bucket and invoke your lambda from your CloudFormation stack using a CustomResource.



          Below a lambda example cleaning up your bucket:



          #!/usr/bin/env python
          # -*- coding: utf-8 -*-

          import json
          import boto3
          from botocore.vendored 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))


          After you create the lambda above, just put the CustomResource in your CloudFormation stack:



           ---
          AWSTemplateFormatVersion: '2010-09-09'

          Resources:

          myBucketResource:
          Type: AWS::S3::Bucket
          Properties:
          BucketName: my-test-bucket-cleaning-on-delete
          DependsOn: cleanupBucketOnDelete

          cleanupBucketOnDelete:
          Type: Custom::cleanupbucket
          Properties:
          ServiceToken: arn:aws:lambda:eu-west-1:123456789012:function:clean-bucket-lambda
          BucketName: my-test-bucket-cleaning-on-delete



          Remember to attach a role to your lambda that has permission to remove objects from your bucket.




          Furthermore keep in mind that you can create a lambda function that accepts CLI command line using the lambda function cli2cloudformation. You can download and install from here. Using that you just need to create a CustomResource like bellow:



          "removeBucket": {
          "Type": "Custom::cli2cloudformation",
          "Properties": {
          "ServiceToken": "arn:aws:lambda:eu-west-1:123456789000:function:custom-lambda-name",
          "CliCommandDelete": "aws s3 rb s3://bucket-name --force",
          }
          }





          share|improve this answer





















          • 3





            This is a great way to handle deleting the bucket from CloudFormation but I think the answer is just no - so I cannot mark this as the answer (but I did upvote it) - thanks

            – Jamie Czuy
            Jul 11 '17 at 15:40






          • 1





            This answer is awesome thanks for posting it

            – Hamed Minaee
            Oct 23 '17 at 16:19











          • More in-depth blog post on the topic: community.alfresco.com/community/platform/blog/2016/10/13/…

            – vincent
            Dec 11 '17 at 1:06











          • @JamieCzuy : This is a valid answer. You should mark it as resolver . Indeed, it is still in the context of cloudformation (CFN Custom resources)

            – Abdennour TOUMI
            Dec 19 '17 at 18:01



















          1














          I think your DependsOn is in wrong resource, at least it did not work for me properly because on stack deletion (via console), it would try to force bucket deletion first which will fail and then will attempt to delete custom resource, which triggers the lambda to empty the bucket. This will empty the bucket but the stack deletion will fail because it attempted to delete the bucket before it was empty. We want to initiate custom resource deletion first and then attempt to delete bucket after custom resource is deleted, so I did it like this and it works for me:



          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: my-test-bucket-cleaning-on-delete
          DependsOn: myBucketResource


          This way you ensure the bucket deletion does not come first because there is another resource that depends on it, hence the depending resource is deleted first (which triggeres the lambda to empty the bucket) and then bucket is deleted.
          Hope someone finds it helpful.






          share|improve this answer

































            0














            Well



            how about this:



            import boto3

            s3 = boto3.client('s3')
            res = boto3.resource('s3')

            buckets = s3.list_buckets()

            try:
            for bk in buckets['Buckets']:
            bucket = res.Bucket(bk['Name'])
            bucket.objects.all().delete()
            bucket.delete()

            except Exception as e:
            print e





            share|improve this answer































              0














              You should empty the bucket:



              $ aws s3 rm s3://bucket-name --recursive


              Then delete the Bucket



              $ aws cloudformation delete-stack --stack-name mys3stack





              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40383470%2fcan-i-force-cloudformation-to-delete-non-empty-s3-bucket%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                22














                You can create a lambda function to clean up your bucket and invoke your lambda from your CloudFormation stack using a CustomResource.



                Below a lambda example cleaning up your bucket:



                #!/usr/bin/env python
                # -*- coding: utf-8 -*-

                import json
                import boto3
                from botocore.vendored 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))


                After you create the lambda above, just put the CustomResource in your CloudFormation stack:



                 ---
                AWSTemplateFormatVersion: '2010-09-09'

                Resources:

                myBucketResource:
                Type: AWS::S3::Bucket
                Properties:
                BucketName: my-test-bucket-cleaning-on-delete
                DependsOn: cleanupBucketOnDelete

                cleanupBucketOnDelete:
                Type: Custom::cleanupbucket
                Properties:
                ServiceToken: arn:aws:lambda:eu-west-1:123456789012:function:clean-bucket-lambda
                BucketName: my-test-bucket-cleaning-on-delete



                Remember to attach a role to your lambda that has permission to remove objects from your bucket.




                Furthermore keep in mind that you can create a lambda function that accepts CLI command line using the lambda function cli2cloudformation. You can download and install from here. Using that you just need to create a CustomResource like bellow:



                "removeBucket": {
                "Type": "Custom::cli2cloudformation",
                "Properties": {
                "ServiceToken": "arn:aws:lambda:eu-west-1:123456789000:function:custom-lambda-name",
                "CliCommandDelete": "aws s3 rb s3://bucket-name --force",
                }
                }





                share|improve this answer





















                • 3





                  This is a great way to handle deleting the bucket from CloudFormation but I think the answer is just no - so I cannot mark this as the answer (but I did upvote it) - thanks

                  – Jamie Czuy
                  Jul 11 '17 at 15:40






                • 1





                  This answer is awesome thanks for posting it

                  – Hamed Minaee
                  Oct 23 '17 at 16:19











                • More in-depth blog post on the topic: community.alfresco.com/community/platform/blog/2016/10/13/…

                  – vincent
                  Dec 11 '17 at 1:06











                • @JamieCzuy : This is a valid answer. You should mark it as resolver . Indeed, it is still in the context of cloudformation (CFN Custom resources)

                  – Abdennour TOUMI
                  Dec 19 '17 at 18:01
















                22














                You can create a lambda function to clean up your bucket and invoke your lambda from your CloudFormation stack using a CustomResource.



                Below a lambda example cleaning up your bucket:



                #!/usr/bin/env python
                # -*- coding: utf-8 -*-

                import json
                import boto3
                from botocore.vendored 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))


                After you create the lambda above, just put the CustomResource in your CloudFormation stack:



                 ---
                AWSTemplateFormatVersion: '2010-09-09'

                Resources:

                myBucketResource:
                Type: AWS::S3::Bucket
                Properties:
                BucketName: my-test-bucket-cleaning-on-delete
                DependsOn: cleanupBucketOnDelete

                cleanupBucketOnDelete:
                Type: Custom::cleanupbucket
                Properties:
                ServiceToken: arn:aws:lambda:eu-west-1:123456789012:function:clean-bucket-lambda
                BucketName: my-test-bucket-cleaning-on-delete



                Remember to attach a role to your lambda that has permission to remove objects from your bucket.




                Furthermore keep in mind that you can create a lambda function that accepts CLI command line using the lambda function cli2cloudformation. You can download and install from here. Using that you just need to create a CustomResource like bellow:



                "removeBucket": {
                "Type": "Custom::cli2cloudformation",
                "Properties": {
                "ServiceToken": "arn:aws:lambda:eu-west-1:123456789000:function:custom-lambda-name",
                "CliCommandDelete": "aws s3 rb s3://bucket-name --force",
                }
                }





                share|improve this answer





















                • 3





                  This is a great way to handle deleting the bucket from CloudFormation but I think the answer is just no - so I cannot mark this as the answer (but I did upvote it) - thanks

                  – Jamie Czuy
                  Jul 11 '17 at 15:40






                • 1





                  This answer is awesome thanks for posting it

                  – Hamed Minaee
                  Oct 23 '17 at 16:19











                • More in-depth blog post on the topic: community.alfresco.com/community/platform/blog/2016/10/13/…

                  – vincent
                  Dec 11 '17 at 1:06











                • @JamieCzuy : This is a valid answer. You should mark it as resolver . Indeed, it is still in the context of cloudformation (CFN Custom resources)

                  – Abdennour TOUMI
                  Dec 19 '17 at 18:01














                22












                22








                22







                You can create a lambda function to clean up your bucket and invoke your lambda from your CloudFormation stack using a CustomResource.



                Below a lambda example cleaning up your bucket:



                #!/usr/bin/env python
                # -*- coding: utf-8 -*-

                import json
                import boto3
                from botocore.vendored 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))


                After you create the lambda above, just put the CustomResource in your CloudFormation stack:



                 ---
                AWSTemplateFormatVersion: '2010-09-09'

                Resources:

                myBucketResource:
                Type: AWS::S3::Bucket
                Properties:
                BucketName: my-test-bucket-cleaning-on-delete
                DependsOn: cleanupBucketOnDelete

                cleanupBucketOnDelete:
                Type: Custom::cleanupbucket
                Properties:
                ServiceToken: arn:aws:lambda:eu-west-1:123456789012:function:clean-bucket-lambda
                BucketName: my-test-bucket-cleaning-on-delete



                Remember to attach a role to your lambda that has permission to remove objects from your bucket.




                Furthermore keep in mind that you can create a lambda function that accepts CLI command line using the lambda function cli2cloudformation. You can download and install from here. Using that you just need to create a CustomResource like bellow:



                "removeBucket": {
                "Type": "Custom::cli2cloudformation",
                "Properties": {
                "ServiceToken": "arn:aws:lambda:eu-west-1:123456789000:function:custom-lambda-name",
                "CliCommandDelete": "aws s3 rb s3://bucket-name --force",
                }
                }





                share|improve this answer















                You can create a lambda function to clean up your bucket and invoke your lambda from your CloudFormation stack using a CustomResource.



                Below a lambda example cleaning up your bucket:



                #!/usr/bin/env python
                # -*- coding: utf-8 -*-

                import json
                import boto3
                from botocore.vendored 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))


                After you create the lambda above, just put the CustomResource in your CloudFormation stack:



                 ---
                AWSTemplateFormatVersion: '2010-09-09'

                Resources:

                myBucketResource:
                Type: AWS::S3::Bucket
                Properties:
                BucketName: my-test-bucket-cleaning-on-delete
                DependsOn: cleanupBucketOnDelete

                cleanupBucketOnDelete:
                Type: Custom::cleanupbucket
                Properties:
                ServiceToken: arn:aws:lambda:eu-west-1:123456789012:function:clean-bucket-lambda
                BucketName: my-test-bucket-cleaning-on-delete



                Remember to attach a role to your lambda that has permission to remove objects from your bucket.




                Furthermore keep in mind that you can create a lambda function that accepts CLI command line using the lambda function cli2cloudformation. You can download and install from here. Using that you just need to create a CustomResource like bellow:



                "removeBucket": {
                "Type": "Custom::cli2cloudformation",
                "Properties": {
                "ServiceToken": "arn:aws:lambda:eu-west-1:123456789000:function:custom-lambda-name",
                "CliCommandDelete": "aws s3 rb s3://bucket-name --force",
                }
                }






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jan 3 '18 at 14:08

























                answered Jul 10 '17 at 8:19









                Lucio Veloso GuimarãesLucio Veloso Guimarães

                36349




                36349








                • 3





                  This is a great way to handle deleting the bucket from CloudFormation but I think the answer is just no - so I cannot mark this as the answer (but I did upvote it) - thanks

                  – Jamie Czuy
                  Jul 11 '17 at 15:40






                • 1





                  This answer is awesome thanks for posting it

                  – Hamed Minaee
                  Oct 23 '17 at 16:19











                • More in-depth blog post on the topic: community.alfresco.com/community/platform/blog/2016/10/13/…

                  – vincent
                  Dec 11 '17 at 1:06











                • @JamieCzuy : This is a valid answer. You should mark it as resolver . Indeed, it is still in the context of cloudformation (CFN Custom resources)

                  – Abdennour TOUMI
                  Dec 19 '17 at 18:01














                • 3





                  This is a great way to handle deleting the bucket from CloudFormation but I think the answer is just no - so I cannot mark this as the answer (but I did upvote it) - thanks

                  – Jamie Czuy
                  Jul 11 '17 at 15:40






                • 1





                  This answer is awesome thanks for posting it

                  – Hamed Minaee
                  Oct 23 '17 at 16:19











                • More in-depth blog post on the topic: community.alfresco.com/community/platform/blog/2016/10/13/…

                  – vincent
                  Dec 11 '17 at 1:06











                • @JamieCzuy : This is a valid answer. You should mark it as resolver . Indeed, it is still in the context of cloudformation (CFN Custom resources)

                  – Abdennour TOUMI
                  Dec 19 '17 at 18:01








                3




                3





                This is a great way to handle deleting the bucket from CloudFormation but I think the answer is just no - so I cannot mark this as the answer (but I did upvote it) - thanks

                – Jamie Czuy
                Jul 11 '17 at 15:40





                This is a great way to handle deleting the bucket from CloudFormation but I think the answer is just no - so I cannot mark this as the answer (but I did upvote it) - thanks

                – Jamie Czuy
                Jul 11 '17 at 15:40




                1




                1





                This answer is awesome thanks for posting it

                – Hamed Minaee
                Oct 23 '17 at 16:19





                This answer is awesome thanks for posting it

                – Hamed Minaee
                Oct 23 '17 at 16:19













                More in-depth blog post on the topic: community.alfresco.com/community/platform/blog/2016/10/13/…

                – vincent
                Dec 11 '17 at 1:06





                More in-depth blog post on the topic: community.alfresco.com/community/platform/blog/2016/10/13/…

                – vincent
                Dec 11 '17 at 1:06













                @JamieCzuy : This is a valid answer. You should mark it as resolver . Indeed, it is still in the context of cloudformation (CFN Custom resources)

                – Abdennour TOUMI
                Dec 19 '17 at 18:01





                @JamieCzuy : This is a valid answer. You should mark it as resolver . Indeed, it is still in the context of cloudformation (CFN Custom resources)

                – Abdennour TOUMI
                Dec 19 '17 at 18:01













                1














                I think your DependsOn is in wrong resource, at least it did not work for me properly because on stack deletion (via console), it would try to force bucket deletion first which will fail and then will attempt to delete custom resource, which triggers the lambda to empty the bucket. This will empty the bucket but the stack deletion will fail because it attempted to delete the bucket before it was empty. We want to initiate custom resource deletion first and then attempt to delete bucket after custom resource is deleted, so I did it like this and it works for me:



                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: my-test-bucket-cleaning-on-delete
                DependsOn: myBucketResource


                This way you ensure the bucket deletion does not come first because there is another resource that depends on it, hence the depending resource is deleted first (which triggeres the lambda to empty the bucket) and then bucket is deleted.
                Hope someone finds it helpful.






                share|improve this answer






























                  1














                  I think your DependsOn is in wrong resource, at least it did not work for me properly because on stack deletion (via console), it would try to force bucket deletion first which will fail and then will attempt to delete custom resource, which triggers the lambda to empty the bucket. This will empty the bucket but the stack deletion will fail because it attempted to delete the bucket before it was empty. We want to initiate custom resource deletion first and then attempt to delete bucket after custom resource is deleted, so I did it like this and it works for me:



                  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: my-test-bucket-cleaning-on-delete
                  DependsOn: myBucketResource


                  This way you ensure the bucket deletion does not come first because there is another resource that depends on it, hence the depending resource is deleted first (which triggeres the lambda to empty the bucket) and then bucket is deleted.
                  Hope someone finds it helpful.






                  share|improve this answer




























                    1












                    1








                    1







                    I think your DependsOn is in wrong resource, at least it did not work for me properly because on stack deletion (via console), it would try to force bucket deletion first which will fail and then will attempt to delete custom resource, which triggers the lambda to empty the bucket. This will empty the bucket but the stack deletion will fail because it attempted to delete the bucket before it was empty. We want to initiate custom resource deletion first and then attempt to delete bucket after custom resource is deleted, so I did it like this and it works for me:



                    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: my-test-bucket-cleaning-on-delete
                    DependsOn: myBucketResource


                    This way you ensure the bucket deletion does not come first because there is another resource that depends on it, hence the depending resource is deleted first (which triggeres the lambda to empty the bucket) and then bucket is deleted.
                    Hope someone finds it helpful.






                    share|improve this answer















                    I think your DependsOn is in wrong resource, at least it did not work for me properly because on stack deletion (via console), it would try to force bucket deletion first which will fail and then will attempt to delete custom resource, which triggers the lambda to empty the bucket. This will empty the bucket but the stack deletion will fail because it attempted to delete the bucket before it was empty. We want to initiate custom resource deletion first and then attempt to delete bucket after custom resource is deleted, so I did it like this and it works for me:



                    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: my-test-bucket-cleaning-on-delete
                    DependsOn: myBucketResource


                    This way you ensure the bucket deletion does not come first because there is another resource that depends on it, hence the depending resource is deleted first (which triggeres the lambda to empty the bucket) and then bucket is deleted.
                    Hope someone finds it helpful.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Jan 2 at 12:21

























                    answered Jan 2 at 10:57









                    OkayWhateverOkayWhatever

                    163




                    163























                        0














                        Well



                        how about this:



                        import boto3

                        s3 = boto3.client('s3')
                        res = boto3.resource('s3')

                        buckets = s3.list_buckets()

                        try:
                        for bk in buckets['Buckets']:
                        bucket = res.Bucket(bk['Name'])
                        bucket.objects.all().delete()
                        bucket.delete()

                        except Exception as e:
                        print e





                        share|improve this answer




























                          0














                          Well



                          how about this:



                          import boto3

                          s3 = boto3.client('s3')
                          res = boto3.resource('s3')

                          buckets = s3.list_buckets()

                          try:
                          for bk in buckets['Buckets']:
                          bucket = res.Bucket(bk['Name'])
                          bucket.objects.all().delete()
                          bucket.delete()

                          except Exception as e:
                          print e





                          share|improve this answer


























                            0












                            0








                            0







                            Well



                            how about this:



                            import boto3

                            s3 = boto3.client('s3')
                            res = boto3.resource('s3')

                            buckets = s3.list_buckets()

                            try:
                            for bk in buckets['Buckets']:
                            bucket = res.Bucket(bk['Name'])
                            bucket.objects.all().delete()
                            bucket.delete()

                            except Exception as e:
                            print e





                            share|improve this answer













                            Well



                            how about this:



                            import boto3

                            s3 = boto3.client('s3')
                            res = boto3.resource('s3')

                            buckets = s3.list_buckets()

                            try:
                            for bk in buckets['Buckets']:
                            bucket = res.Bucket(bk['Name'])
                            bucket.objects.all().delete()
                            bucket.delete()

                            except Exception as e:
                            print e






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered May 11 '18 at 20:09









                            VFagundesVFagundes

                            1




                            1























                                0














                                You should empty the bucket:



                                $ aws s3 rm s3://bucket-name --recursive


                                Then delete the Bucket



                                $ aws cloudformation delete-stack --stack-name mys3stack





                                share|improve this answer




























                                  0














                                  You should empty the bucket:



                                  $ aws s3 rm s3://bucket-name --recursive


                                  Then delete the Bucket



                                  $ aws cloudformation delete-stack --stack-name mys3stack





                                  share|improve this answer


























                                    0












                                    0








                                    0







                                    You should empty the bucket:



                                    $ aws s3 rm s3://bucket-name --recursive


                                    Then delete the Bucket



                                    $ aws cloudformation delete-stack --stack-name mys3stack





                                    share|improve this answer













                                    You should empty the bucket:



                                    $ aws s3 rm s3://bucket-name --recursive


                                    Then delete the Bucket



                                    $ aws cloudformation delete-stack --stack-name mys3stack






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Feb 14 at 16:38









                                    KlykooKlykoo

                                    11




                                    11






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40383470%2fcan-i-force-cloudformation-to-delete-non-empty-s3-bucket%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        MongoDB - Not Authorized To Execute Command

                                        How to fix TextFormField cause rebuild widget in Flutter

                                        in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith