Repository: aws-cloudformation/community-registry-extensions (language: python)

Issue:
S3 DeleteBucketContents Resource
## AwsCommunity::S3::DeleteBucketContents

### Tracking Issue

This resource type will delete the contents of the referenced bucket, so that bucket deletion can be automated without writing a custom resource.


Discussion / hints:

Fix patch:
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 00000000..e43b0f98
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,1 @@
+.DS_Store
diff --git a/resources/BucketNotification/README.md b/resources/BucketNotification/README.md
index 16f77610..db039938 100644
--- a/resources/BucketNotification/README.md
+++ b/resources/BucketNotification/README.md
@@ -8,17 +8,76 @@ Note that this resource intentionally introduces drift into your template,
 since the official way to configure bucket notifications is to specify them as
 part of the `AWS::S3::Bucket` resource.
 
+## Sample template
+
+```yml
+Resources:
+  Queue:
+    Type: AWS::SQS::Queue
+  Bucket:
+    Type: AWS::S3::Bucket
+  Notification:
+    Type: AwsCommunity::S3::BucketNotification
+    Properties:
+      Id: MyNotification
+      Events: 
+        - s3:ObjectCreated:*
+      Filters:
+        - Name: suffix
+          Value: gif
+      BucketArn: !GetAtt Bucket.Arn
+      TargetType: Queue
+      TargetArn: !GetAtt Queue.Arn
+    DependsOn:
+      - Bucket
+      - Queue
+```
+
 ## Development
 
+Open two tabs in your terminal.
+
+Create a virtual environment.
+
 ```sh
 cd resources/BucketNotification
 python3 -m venv .env
 source .env/bin/activate
 cd src
 pip install -r requirements.txt
-pip install -e .
-cd awscommunity_s3_bucketnotification
-pylint *.py
-python3 config_integ.py --profile YOUR_PROFILE_NAME
+cd ..
+```
+
+In the other tab, run SAM local:
+
+```sh
+cd resources/BucketNotification
+source .env/bin/activaate
+sam local start-lambda
+```
+
+Keep in mind that SAM local testing only simulates lambda locally, it will make SDK 
+calls into your account and create resources!
+
+In the first tab:
+
+```sh
+./run-test.sh
+```
+
+If you don't have a default profile set up on your machine, you can do this:
+
+```sh
+AWS_PROFILE=my-profile ./run-test.sh
+```
+
+The `run-test.sh` script runs pylint and does a `cfn submit --dry-run`, which is necessary to create the build folder that SAM relies on.
+
+There is also an integ test you can run to test the SDK calls without using SAM.
+It also creates resources in your account.
+
+```sh
+cd src
+python3 run_integ_test.py --profile your-aws-profile-name
 ```
 
diff --git a/resources/BucketNotification/awscommunity-s3-bucketnotification.json b/resources/BucketNotification/awscommunity-s3-bucketnotification.json
index e02ec9b7..6c418f59 100644
--- a/resources/BucketNotification/awscommunity-s3-bucketnotification.json
+++ b/resources/BucketNotification/awscommunity-s3-bucketnotification.json
@@ -75,6 +75,7 @@
         "create": {
             "permissions": [
                 "iam:CreateRole",
+                "iam:GetRole",
                 "iam:DeleteRole",
                 "s3:PutBucketNotification",
                 "s3:GetBucketNotification",
@@ -94,6 +95,7 @@
         "read": {
             "permissions": [
                 "s3:GetBucketNotification",
+                "iam:GetRole",
                 "sns:ConfirmSubscription",
                 "sns:GetTopicAttributes",
                 "sqs:AddPermission",
@@ -104,6 +106,7 @@
         "update": {
             "permissions": [
                 "iam:CreateRole",
+                "iam:GetRole",
                 "iam:DeleteRole",
                 "s3:PutBucketNotification",
                 "s3:GetBucketNotification",
diff --git a/resources/BucketNotification/example_inputs/inputs_1_create.json b/resources/BucketNotification/example_inputs/inputs_1_create.json
index 296315d4..93f28eb6 100644
--- a/resources/BucketNotification/example_inputs/inputs_1_create.json
+++ b/resources/BucketNotification/example_inputs/inputs_1_create.json
@@ -1,8 +1,8 @@
 {
     "Id": "Test1",
     "Events": ["s3:ObjectCreated:*"],
-    "BucketArn": "arn:aws:s3:::ezbeard-at-amazon-docs",
-    "TargetArn": "arn:aws:sqs:us-east-1:916662284357:Dop201BStack-Dop201BQueue3245FBAB-1EAHQVNYX79M7",
+    "BucketArn": "arn:aws:s3:::[NEEDS TO BE A REAL BUCKET IN YOUR ACCOUNT]",
+    "TargetArn": "arn:aws:sqs:us-east-1:[YOUR ACCOUNT ID]:[NEEDS TO BE A REAL QUEUE]",
     "TargetType": "Queue",
     "Filters": [
         {
diff --git a/resources/BucketNotification/example_inputs/inputs_1_update.json b/resources/BucketNotification/example_inputs/inputs_1_update.json
index 2ad34fdc..93f28eb6 100644
--- a/resources/BucketNotification/example_inputs/inputs_1_update.json
+++ b/resources/BucketNotification/example_inputs/inputs_1_update.json
@@ -1,8 +1,8 @@
 {
     "Id": "Test1",
     "Events": ["s3:ObjectCreated:*"],
-    "BucketArn": "arn:aws:s3:::ezbeard-at-amazon-docs",
-    "TargetArn": "arn:aws:sqs:us-east-1:916662284357:Dop201BStack-Dop201BQueue3245FBAB-1EAHQVNYX79M7",
+    "BucketArn": "arn:aws:s3:::[NEEDS TO BE A REAL BUCKET IN YOUR ACCOUNT]",
+    "TargetArn": "arn:aws:sqs:us-east-1:[YOUR ACCOUNT ID]:[NEEDS TO BE A REAL QUEUE]",
     "TargetType": "Queue",
     "Filters": [
         {
@@ -11,3 +11,4 @@
         }
     ]
 }
+
diff --git a/resources/BucketNotification/resource-role.yaml b/resources/BucketNotification/resource-role.yaml
index 591ad3cb..68ea8a5e 100644
--- a/resources/BucketNotification/resource-role.yaml
+++ b/resources/BucketNotification/resource-role.yaml
@@ -32,6 +32,7 @@ Resources:
                 Action:
                 - "iam:CreateRole"
                 - "iam:DeleteRole"
+                - "iam:GetRole"
                 - "lambda:AddPermission"
                 - "lambda:RemovePermission"
                 - "s3:GetBucketNotification"
diff --git a/resources/BucketNotification/src/awscommunity_s3_bucketnotification/config.py b/resources/BucketNotification/src/awscommunity_s3_bucketnotification/config.py
index 40087bad..3a3927a3 100644
--- a/resources/BucketNotification/src/awscommunity_s3_bucketnotification/config.py
+++ b/resources/BucketNotification/src/awscommunity_s3_bucketnotification/config.py
@@ -12,6 +12,7 @@
 from .models import ResourceModel, KeyVal
 
 LOG = logging.getLogger(__name__)
+LOG.setLevel(logging.DEBUG)
 
 def find(cfg, model_id):
     """
@@ -108,32 +109,50 @@ def delete(session, bucket_arn, model_id):
         print(f"Id {model_id} not found in notification config for {bucket_arn}")
         return False
 
+    target_arn = None
+    notification_id = notification["Id"]
+    has_policy = False
+
     if "TopicArn" in notification:
+        target_arn = notification["TopicArn"]
         del cfg["TopicConfigurations"][idx] 
     elif "QueueArn" in notification:
+        target_arn = notification["QueueArn"]
         del cfg["QueueConfigurations"][idx]
     elif "LambdaFunctionArn" in notification:
+        target_arn = notification["LambdaFunctionArn"]
+        has_policy = True
         del cfg["LambdaFunctionConfigurations"][idx]
     else:
         raise Exception("Unexpected notification missing Arn")
 
     save_config(session, bucket_arn, cfg)
 
+    # Delete the role we created to allow S3 to send the notifications
+    target_name = target_arn.split(":")[-1]
+    role_name = get_role_name(target_name, notification_id)
+    policy_name = None
+    if has_policy:
+        policy_name = get_policy_name(role_name)
+    delete_role(session, role_name, policy_name)
+
     return True
 
 def get_role_name(target_name, notification_id):
     "Get the name of the role we create for S3 to notify the target"
-    return target_name + "-bktntf-" + notification_id
+    return target_name + "-bn-" + notification_id
 
 def get_policy_name(role_name):
     "Get the policy name for the role we create"
-    return role_name + "_policy"
+    return role_name + "_p"
 
 def delete_role(session, role_name, policy_arn):
     "Delete the role we created for S3 to notifiy the target"
 
     iam = session.client("iam")
 
+    #TODO - Delete the Queue/Topic policy
+
     try:
         if policy_arn:
             iam.delete_policy(PolicyArn=policy_arn)
@@ -222,6 +241,7 @@ def create_role(session, notification_id, target_type, target_arn, bucket_arn):
         if target_type == "Queue":
             sqs = session.client("sqs")
             queue_url = sqs.get_queue_url(QueueName=target_name)["QueueUrl"]
+            # TODO - What if the queue already had a Policy?
             sqs.set_queue_attributes(
                 QueueUrl=queue_url,
                 Attributes = {
@@ -230,6 +250,7 @@ def create_role(session, notification_id, target_type, target_arn, bucket_arn):
             )
         else:
             sns = session.client("sns")
+            # TODO - What if the topic already had a Policy?
             sns.set_topic_attributes(
                 TopicArn=target_arn,
                 AttributeName="Policy",
diff --git a/resources/BucketNotification/src/awscommunity_s3_bucketnotification/config_integ.py b/resources/BucketNotification/src/awscommunity_s3_bucketnotification/config_integ.py
index ff215260..f2913938 100644
--- a/resources/BucketNotification/src/awscommunity_s3_bucketnotification/config_integ.py
+++ b/resources/BucketNotification/src/awscommunity_s3_bucketnotification/config_integ.py
@@ -120,7 +120,14 @@ def main(profile_name): #pylint: disable=too-many-branches
         function_role_arn = r["Role"]["Arn"]
         print("Created function role:", function_role_arn)
 
-        with open('awscommunity_s3_bucketnotification/test_lambda.zip', 'rb') as f:
+        # When we had the zip in this folder, it caused `cfn submit` to fail,
+        # since it apparently assumes that any zip file in the build folder is the 
+        # entry point for the handler functions. We got errors like this:
+        # Lambda function handler threw an uncaught exception: Unable to import
+        # module 'awscommunity_s3_bucketnotification.handlers': No module named
+        # 'awscommunity_s3_bucketnotification'
+        zip_path = "../test/test_lambda.zip"
+        with open(zip_path, 'rb') as f:
             zipped_code = f.read()
 
         r = lam.create_function(FunctionName=function_name,
diff --git a/resources/BucketNotification/src/awscommunity_s3_bucketnotification/handlers.py b/resources/BucketNotification/src/awscommunity_s3_bucketnotification/handlers.py
index 5b2e8008..9b4193de 100644
--- a/resources/BucketNotification/src/awscommunity_s3_bucketnotification/handlers.py
+++ b/resources/BucketNotification/src/awscommunity_s3_bucketnotification/handlers.py
@@ -2,6 +2,7 @@
 Resource handler implementation for AwsCommunity::S3::BucketNotification
 """
 
+import json
 import logging
 
 from cloudformation_cli_python_lib import (
@@ -20,25 +21,25 @@
 
 # Use this logger to forward log messages to CloudWatch Logs.
 LOG = logging.getLogger(__name__)
+LOG.setLevel(logging.DEBUG)
 
 TYPE_NAME = "AwsCommunity::S3::BucketNotification"
 
 resource = Resource(TYPE_NAME, ResourceModel)
 test_entrypoint = resource.test_entrypoint
 
+def dumps(msg):
+    "JSON serialize with a default to catch errors"
+    return json.dumps(msg, default=str)
+
 @resource.handler(Action.CREATE)
 def create_handler(session, request, callback_context): #pylint:disable=unused-argument
     "Create the bucket notification"
 
     model = request.desiredResourceState
 
-    print("create_handler")
-    print(model.Id)
-    print(model.BucketArn)
-    print(model.TargetType)
-    print(model.TargetArn)
-    print(model.Events)
-    print(model.Filters)
+    LOG.debug("create_handler")
+    LOG.debug("model: %s", dumps(model))
 
     progress = ProgressEvent(
         status=OperationStatus.IN_PROGRESS,
@@ -69,13 +70,8 @@ def update_handler(session, request, callback_context): #pylint:disable=unused-a
 
     model = request.desiredResourceState
 
-    print("update_handler")
-    print(model.Id)
-    print(model.BucketArn)
-    print(model.TargetType)
-    print(model.TargetArn)
-    print(model.Events)
-    print(model.Filters)
+    LOG.debug("update_handler")
+    LOG.debug("model: %s", dumps(model))
 
     progress = ProgressEvent(
         status=OperationStatus.IN_PROGRESS,
@@ -103,10 +99,12 @@ def update_handler(session, request, callback_context): #pylint:disable=unused-a
 @resource.handler(Action.DELETE)
 def delete_handler(session, request, callback_context): #pylint:disable=unused-argument
     "Delete the bucket notification"
-
     
     model = request.desiredResourceState
 
+    LOG.debug("delete_handler")
+    LOG.debug("model: %s", dumps(model))
+
     progress: ProgressEvent = ProgressEvent(
         status=OperationStatus.IN_PROGRESS,
         resourceModel=None,
@@ -129,7 +127,7 @@ def read_handler(session, request, callback_context): #pylint:disable=unused-arg
     "Read the bucket notification"
 
     model = request.desiredResourceState
-    print("read_handler")
+    LOG.debug("read_handler")
 
     try:
         model = get(session, model.BucketArn, model.Id)
@@ -149,22 +147,5 @@ def read_handler(session, request, callback_context): #pylint:disable=unused-arg
 
 # It doesn't really make sense for us to implement a list handler here, 
 # since we can't tell if we created the bucket notifications on all 
-# buckets in an account.
-
-#@resource.handler(Action.LIST)
-#def list_handler(session, request, callback_context):
-#    "List bucket notifications"
-#
-#    
-#    progress: ProgressEvent = ProgressEvent(
-#        status=OperationStatus.IN_PROGRESS,
-#        resourceModels=None,
-#    )
-#    try:
-#
-#        progress.status = OperationStatus.SUCCESS
-#    except Exception as e:
-#        raise exceptions.InternalFailure(e)
-#
-#    return progress
-#
+# buckets in an account. Maybe we could do something with tags?
+
diff --git a/resources/BucketNotification/src/requirements.txt b/resources/BucketNotification/src/requirements.txt
new file mode 100644
index 00000000..19f8f8a5
--- /dev/null
+++ b/resources/BucketNotification/src/requirements.txt
@@ -0,0 +1,70 @@
+aiosmtpd==1.4.2
+astroid==2.12.4
+atpublic==3.0.1
+attrs==22.1.0
+aws-encryption-sdk==3.1.0
+aws-sam-translator==1.50.0
+boto3==1.24.60
+botocore==1.27.60
+certifi==2022.6.15
+cffi==1.15.1
+cfn-flip==1.3.0
+cfn-lint==0.63.0
+charset-normalizer==2.1.1
+click==8.1.3
+cloudformation-cli==0.2.25
+cloudformation-cli-python-lib==2.1.12
+cloudformation-cli-python-plugin==2.1.5
+colorama==0.4.5
+cryptography==37.0.4
+dill==0.3.5.1
+docker==6.0.0
+exceptiongroup==1.0.0rc8
+hypothesis==6.54.4
+idna==3.3
+importlib-metadata==4.12.0
+iniconfig==1.1.1
+isort==5.10.1
+Jinja2==2.11.3
+jmespath==1.0.1
+jschema-to-python==1.2.3
+jsonpatch==1.32
+jsonpickle==2.2.0
+jsonpointer==2.3
+jsonschema==3.2.0
+junit-xml==1.9
+lazy-object-proxy==1.7.1
+MarkupSafe==2.0.1
+mccabe==0.7.0
+nested-lookup==0.2.25
+networkx==2.6.3
+ordered-set==4.1.0
+packaging==21.3
+pbr==5.10.0
+platformdirs==2.5.2
+pluggy==1.0.0
+py==1.11.0
+pycparser==2.21
+pylint==2.15.0
+pyparsing==3.0.9
+pyrsistent==0.18.1
+pytest==7.1.2
+pytest-localserver==0.6.0
+pytest-random-order==1.0.4
+python-dateutil==2.8.2
+PyYAML==5.4.1
+requests==2.28.1
+s3transfer==0.6.0
+sarif-om==1.0.4
+six==1.16.0
+sortedcontainers==2.4.0
+tomli==2.0.1
+tomlkit==0.11.4
+typed-ast==1.5.4
+types-dataclasses==0.6.6
+typing_extensions==4.3.0
+urllib3==1.26.12
+websocket-client==1.4.0
+Werkzeug==2.1.2
+wrapt==1.14.1
+zipp==3.8.1
diff --git a/resources/DeleteBucketContents/.gitignore b/resources/DeleteBucketContents/.gitignore
new file mode 100644
index 00000000..0bc06217
--- /dev/null
+++ b/resources/DeleteBucketContents/.gitignore
@@ -0,0 +1,132 @@
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+pip-wheel-metadata/
+share/python-wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+#  Usually these files are written by a python script from a template
+#  before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.nox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+.hypothesis/
+.pytest_cache/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+db.sqlite3-journal
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/_build/
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# IPython
+profile_default/
+ipython_config.py
+
+# pyenv
+.python-version
+
+# pipenv
+#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
+#   However, in case of collaboration, if having platform-specific dependencies or dependencies
+#   having no cross-platform support, pipenv may install dependencies that don't work, or not
+#   install all needed dependencies.
+#Pipfile.lock
+
+# celery beat schedule file
+celerybeat-schedule
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+.dmypy.json
+dmypy.json
+
+# Pyre type checker
+.pyre/
+
+# contains credentials
+sam-tests/
+
+rpdk.log*
+awscommunity-s3-deletebucketcontents.zip
+inputs/
+.DS_Store
diff --git a/resources/DeleteBucketContents/.rpdk-config b/resources/DeleteBucketContents/.rpdk-config
new file mode 100644
index 00000000..4f1597fc
--- /dev/null
+++ b/resources/DeleteBucketContents/.rpdk-config
@@ -0,0 +1,21 @@
+{
+    "artifact_type": "RESOURCE",
+    "typeName": "AwsCommunity::S3::DeleteBucketContents",
+    "language": "python37",
+    "runtime": "python3.7",
+    "entrypoint": "awscommunity_s3_deletebucketcontents.handlers.resource",
+    "testEntrypoint": "awscommunity_s3_deletebucketcontents.handlers.test_entrypoint",
+    "settings": {
+        "version": false,
+        "subparser_name": null,
+        "verbose": 0,
+        "force": false,
+        "type_name": null,
+        "artifact_type": null,
+        "endpoint_url": null,
+        "region": null,
+        "target_schemas": [],
+        "use_docker": true,
+        "protocolVersion": "2.0.0"
+    }
+}
diff --git a/resources/DeleteBucketContents/README.md b/resources/DeleteBucketContents/README.md
new file mode 100644
index 00000000..7e167cf6
--- /dev/null
+++ b/resources/DeleteBucketContents/README.md
@@ -0,0 +1,36 @@
+# AwsCommunity::S3::DeleteBucketContents
+
+This registry extension resource type deletes all contents of a bucket when the resource is deleted. 
+
+Use this resource with caution! In the sample below we show how to incorporate a condition to avoid deleting contents from a production environment.
+
+## Sample template
+
+```yml
+Parameters:
+  EnvType:
+    Description: Environment type.
+    Default: alpha
+    Type: String
+    AllowedValues:
+      - alpha
+      - beta
+      - gamma
+      - prod
+    ConstraintDescription: Specify alpha, beta, gamma, or prod
+Conditions:
+  IsNotProd: !Not 
+    - !Equals
+      - !Ref EnvType
+      - prod
+Resources:
+  Bucket:
+    Type: AWS::S3::Bucket
+  Deleter:
+    DependsOn: Bucket
+    Condition: IsNotProd
+    Type: AwsCommunity::S3::DeleteBucketContents
+    Properties:
+      BucketName: !Ref Bucket
+```
+
diff --git a/resources/DeleteBucketContents/awscommunity-s3-deletebucketcontents.json b/resources/DeleteBucketContents/awscommunity-s3-deletebucketcontents.json
new file mode 100644
index 00000000..e0c82c42
--- /dev/null
+++ b/resources/DeleteBucketContents/awscommunity-s3-deletebucketcontents.json
@@ -0,0 +1,49 @@
+{
+    "typeName": "AwsCommunity::S3::DeleteBucketContents",
+    "description": "Deletes all contents of the referenced bucket.",
+    "sourceUrl": "https://github.com/aws-cloudformation/community-registry-extensions.git",
+    "definitions": { },
+    "properties": {
+        "BucketName": {
+            "description": "The name of the bucket",
+            "type": "string"
+        }
+    },
+    "additionalProperties": false,
+    "tagging": {
+        "taggable": false
+    },
+    "required": [
+        "BucketName"
+    ],
+    "createOnlyProperties": [
+        "/properties/BucketName"
+    ],
+    "primaryIdentifier": [
+        "/properties/BucketName"
+    ],
+    "handlers": {
+        "create": {
+            "permissions": [
+                "s3:ListBucket",
+                "s3:GetBucketTagging",
+                "s3:PutBucketTagging"
+            ]
+        },
+        "read": {
+            "permissions": [
+                "s3:ListBucket",
+                "s3:GetBucketTagging"
+            ]
+        },
+        "delete": {
+            "permissions": [
+                "s3:DeleteObject",
+                "s3:ListBucket",
+                "s3:ListBucketVersions",
+                "s3:GetBucketTagging",
+                "s3:PutBucketTagging"
+            ]
+        }
+    }
+}
diff --git a/resources/DeleteBucketContents/docs/README.md b/resources/DeleteBucketContents/docs/README.md
new file mode 100644
index 00000000..6a4b185d
--- /dev/null
+++ b/resources/DeleteBucketContents/docs/README.md
@@ -0,0 +1,44 @@
+# AwsCommunity::S3::DeleteBucketContents
+
+Deletes all contents of the referenced bucket.
+
+## Syntax
+
+To declare this entity in your AWS CloudFormation template, use the following syntax:
+
+### JSON
+
+<pre>
+{
+    "Type" : "AwsCommunity::S3::DeleteBucketContents",
+    "Properties" : {
+        "<a href="#bucketname" title="BucketName">BucketName</a>" : <i>String</i>
+    }
+}
+</pre>
+
+### YAML
+
+<pre>
+Type: AwsCommunity::S3::DeleteBucketContents
+Properties:
+    <a href="#bucketname" title="BucketName">BucketName</a>: <i>String</i>
+</pre>
+
+## Properties
+
+#### BucketName
+
+The name of the bucket
+
+_Required_: Yes
+
+_Type_: String
+
+_Update requires_: [Replacement](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html#update-replacement)
+
+## Return Values
+
+### Ref
+
+When you pass the logical ID of this resource to the intrinsic `Ref` function, Ref returns the BucketName.
diff --git a/resources/DeleteBucketContents/example_inputs/inputs_1_create.json b/resources/DeleteBucketContents/example_inputs/inputs_1_create.json
new file mode 100644
index 00000000..b71c3f5b
--- /dev/null
+++ b/resources/DeleteBucketContents/example_inputs/inputs_1_create.json
@@ -0,0 +1,3 @@
+{
+    "BucketName": "test-delete-bucket-contents-1234567890"
+}
diff --git a/resources/DeleteBucketContents/example_inputs/inputs_1_invalid.json b/resources/DeleteBucketContents/example_inputs/inputs_1_invalid.json
new file mode 100644
index 00000000..0a34b64b
--- /dev/null
+++ b/resources/DeleteBucketContents/example_inputs/inputs_1_invalid.json
@@ -0,0 +1,3 @@
+{
+    "BucketName": ""
+}
diff --git a/resources/DeleteBucketContents/example_inputs/inputs_1_update.json b/resources/DeleteBucketContents/example_inputs/inputs_1_update.json
new file mode 100644
index 00000000..b71c3f5b
--- /dev/null
+++ b/resources/DeleteBucketContents/example_inputs/inputs_1_update.json
@@ -0,0 +1,3 @@
+{
+    "BucketName": "test-delete-bucket-contents-1234567890"
+}
diff --git a/resources/DeleteBucketContents/requirements.txt b/resources/DeleteBucketContents/requirements.txt
new file mode 100644
index 00000000..ae233772
--- /dev/null
+++ b/resources/DeleteBucketContents/requirements.txt
@@ -0,0 +1,1 @@
+cloudformation-cli-python-lib>=2.1.9
diff --git a/resources/DeleteBucketContents/resource-role.yaml b/resources/DeleteBucketContents/resource-role.yaml
new file mode 100644
index 00000000..cb631203
--- /dev/null
+++ b/resources/DeleteBucketContents/resource-role.yaml
@@ -0,0 +1,42 @@
+AWSTemplateFormatVersion: "2010-09-09"
+Description: >
+  This CloudFormation template creates a role assumed by CloudFormation
+  during CRUDL operations to mutate resources on behalf of the customer.
+
+Resources:
+  ExecutionRole:
+    Type: AWS::IAM::Role
+    Properties:
+      MaxSessionDuration: 8400
+      AssumeRolePolicyDocument:
+        Version: '2012-10-17'
+        Statement:
+          - Effect: Allow
+            Principal:
+              Service: resources.cloudformation.amazonaws.com
+            Action: sts:AssumeRole
+            Condition:
+              StringEquals:
+                aws:SourceAccount:
+                  Ref: AWS::AccountId
+              StringLike:
+                aws:SourceArn:
+                  Fn::Sub: arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:type/resource/AwsCommunity-S3-DeleteBucketContents/*
+      Path: "/"
+      Policies:
+        - PolicyName: ResourceTypePolicy
+          PolicyDocument:
+            Version: '2012-10-17'
+            Statement:
+              - Effect: Allow
+                Action:
+                - "s3:DeleteObject"
+                - "s3:GetBucketTagging"
+                - "s3:ListBucket"
+                - "s3:ListBucketVersions"
+                - "s3:PutBucketTagging"
+                Resource: "*"
+Outputs:
+  ExecutionRoleArn:
+    Value:
+      Fn::GetAtt: ExecutionRole.Arn
diff --git a/resources/DeleteBucketContents/sample-template.yml b/resources/DeleteBucketContents/sample-template.yml
new file mode 100644
index 00000000..09adf148
--- /dev/null
+++ b/resources/DeleteBucketContents/sample-template.yml
@@ -0,0 +1,25 @@
+Parameters:
+  EnvType:
+    Description: Environment type.
+    Default: alpha
+    Type: String
+    AllowedValues:
+      - alpha
+      - beta
+      - gamma
+      - prod
+    ConstraintDescription: Specify alpha, beta, gamma, or prod
+Conditions:
+  IsNotProd: !Not 
+    - !Equals
+      - !Ref EnvType
+      - prod
+Resources:
+  Bucket:
+    Type: AWS::S3::Bucket
+  Deleter:
+    DependsOn: Bucket
+    Condition: IsNotProd
+    Type: AwsCommunity::S3::DeleteBucketContents
+    Properties:
+      BucketName: !Ref Bucket
diff --git a/resources/DeleteBucketContents/src/.pylintrc b/resources/DeleteBucketContents/src/.pylintrc
new file mode 100644
index 00000000..8ee28d58
--- /dev/null
+++ b/resources/DeleteBucketContents/src/.pylintrc
@@ -0,0 +1,618 @@
+[MAIN]
+
+# Analyse import fallback blocks. This can be used to support both Python 2 and
+# 3 compatible code, which means that the block might have code that exists
+# only in one or another interpreter, leading to false positives when analysed.
+analyse-fallback-blocks=no
+
+# Load and enable all available extensions. Use --list-extensions to see a list
+# all available extensions.
+#enable-all-extensions=
+
+# In error mode, messages with a category besides ERROR or FATAL are
+# suppressed, and no reports are done by default. Error mode is compatible with
+# disabling specific errors.
+#errors-only=
+
+# Always return a 0 (non-error) status code, even if lint errors are found.
+# This is primarily useful in continuous integration scripts.
+#exit-zero=
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code.
+extension-pkg-allow-list=
+
+# A comma-separated list of package or module names from where C extensions may
+# be loaded. Extensions are loading into the active Python interpreter and may
+# run arbitrary code. (This is an alternative name to extension-pkg-allow-list
+# for backward compatibility.)
+extension-pkg-whitelist=
+
+# Return non-zero exit code if any of these messages/categories are detected,
+# even if score is above --fail-under value. Syntax same as enable. Messages
+# specified are enabled, while categories only check already-enabled messages.
+fail-on=
+
+# Specify a score threshold to be exceeded before program exits with error.
+fail-under=10
+
+# Interpret the stdin as a python script, whose filename needs to be passed as
+# the module_or_package argument.
+#from-stdin=
+
+# Files or directories to be skipped. They should be base names, not paths.
+ignore=CVS,
+       models.py
+
+# Add files or directories matching the regex patterns to the ignore-list. The
+# regex matches against paths and can be in Posix or Windows format.
+ignore-paths=
+
+# Files or directories matching the regex patterns are skipped. The regex
+# matches against base names, not paths. The default value ignores Emacs file
+# locks
+ignore-patterns=^\.#
+
+# List of module names for which member attributes should not be checked
+# (useful for modules/projects where namespaces are manipulated during runtime
+# and thus existing member attributes cannot be deduced by static analysis). It
+# supports qualified module names, as well as Unix pattern matching.
+ignored-modules=
+
+# Python code to execute, usually for sys.path manipulation such as
+# pygtk.require().
+#init-hook=
+
+# Use multiple processes to speed up Pylint. Specifying 0 will auto-detect the
+# number of processors available to use, and will cap the count on Windows to
+# avoid hangs.
+jobs=1
+
+# Control the amount of potential inferred values when inferring a single
+# object. This can help the performance when dealing with large functions or
+# complex, nested conditions.
+limit-inference-results=100
+
+# List of plugins (as comma separated values of python module names) to load,
+# usually to register additional checkers.
+load-plugins=
+
+# Pickle collected data for later comparisons.
+persistent=yes
+
+# Minimum Python version to use for version dependent checks. Will default to
+# the version used to run pylint.
+py-version=3.9
+
+# Discover python modules and packages in the file system subtree.
+recursive=no
+
+# When enabled, pylint would attempt to guess common misconfiguration and emit
+# user-friendly hints instead of false-positive error messages.
+suggestion-mode=yes
+
+# Allow loading of arbitrary C extensions. Extensions are imported into the
+# active Python interpreter and may run arbitrary code.
+unsafe-load-any-extension=no
+
+# In verbose mode, extra non-checker-related info will be displayed.
+#verbose=
+
+
+[REPORTS]
+
+# Python expression which should return a score less than or equal to 10. You
+# have access to the variables 'fatal', 'error', 'warning', 'refactor',
+# 'convention', and 'info' which contain the number of messages in each
+# category, as well as 'statement' which is the total number of statements
+# analyzed. This score is used by the global evaluation report (RP0004).
+evaluation=max(0, 0 if fatal else 10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10))
+
+# Template used to display messages. This is a python new-style format string
+# used to format the message information. See doc for all details.
+msg-template=
+
+# Set the output format. Available formats are text, parseable, colorized, json
+# and msvs (visual studio). You can also give a reporter class, e.g.
+# mypackage.mymodule.MyReporterClass.
+#output-format=
+
+# Tells whether to display a full report or only the messages.
+reports=no
+
+# Activate the evaluation score.
+score=yes
+
+
+[MESSAGES CONTROL]
+
+# Only show warnings with the listed confidence levels. Leave empty to show
+# all. Valid levels: HIGH, CONTROL_FLOW, INFERENCE, INFERENCE_FAILURE,
+# UNDEFINED.
+confidence=HIGH,
+           CONTROL_FLOW,
+           INFERENCE,
+           INFERENCE_FAILURE,
+           UNDEFINED
+
+# Disable the message, report, category or checker with the given id(s). You
+# can either give multiple identifiers separated by comma (,) or put this
+# option multiple times (only on the command line, not in the configuration
+# file where it should appear only once). You can also use "--disable=all" to
+# disable everything first and then re-enable specific checks. For example, if
+# you want to run only the similarities checker, you can use "--disable=all
+# --enable=similarities". If you want to run only the classes checker, but have
+# no Warning level messages displayed, use "--disable=all --enable=classes
+# --disable=W".
+disable=raw-checker-failed,
+        bad-inline-option,
+        locally-disabled,
+        file-ignored,
+        suppressed-message,
+        useless-suppression,
+        deprecated-pragma,
+        use-symbolic-message-instead,
+        fixme,
+        trailing-whitespace,
+        trailing-newlines,
+        invalid-name,
+        too-many-locals,
+        broad-except,
+        too-many-statements
+
+# Enable the message, report, category or checker with the given id(s). You can
+# either give multiple identifier separated by comma (,) or put this option
+# multiple time (only on the command line, not in the configuration file where
+# it should appear only once). See also the "--disable" option for examples.
+enable=c-extension-no-member
+
+
+[LOGGING]
+
+# The type of string formatting that logging methods do. `old` means using %
+# formatting, `new` is for `{}` formatting.
+logging-format-style=old
+
+# Logging modules to check that the string format arguments are in logging
+# function parameter format.
+logging-modules=logging
+
+
+[SPELLING]
+
+# Limits count of emitted suggestions for spelling mistakes.
+max-spelling-suggestions=4
+
+# Spelling dictionary name. Available dictionaries: none. To make it work,
+# install the 'python-enchant' package.
+spelling-dict=
+
+# List of comma separated words that should be considered directives if they
+# appear at the beginning of a comment and should not be checked.
+spelling-ignore-comment-directives=fmt: on,fmt: off,noqa:,noqa,nosec,isort:skip,mypy:
+
+# List of comma separated words that should not be checked.
+spelling-ignore-words=
+
+# A path to a file that contains the private dictionary; one word per line.
+spelling-private-dict-file=
+
+# Tells whether to store unknown words to the private dictionary (see the
+# --spelling-private-dict-file option) instead of raising a message.
+spelling-store-unknown-words=no
+
+
+[MISCELLANEOUS]
+
+# List of note tags to take in consideration, separated by a comma.
+notes=FIXME,
+      XXX,
+      TODO
+
+# Regular expression of note tags to take in consideration.
+notes-rgx=
+
+
+[TYPECHECK]
+
+# List of decorators that produce context managers, such as
+# contextlib.contextmanager. Add to this list to register other decorators that
+# produce valid context managers.
+contextmanager-decorators=contextlib.contextmanager
+
+# List of members which are set dynamically and missed by pylint inference
+# system, and so shouldn't trigger E1101 when accessed. Python regular
+# expressions are accepted.
+generated-members=
+
+# Tells whether to warn about missing members when the owner of the attribute
+# is inferred to be None.
+ignore-none=yes
+
+# This flag controls whether pylint should warn about no-member and similar
+# checks whenever an opaque object is returned when inferring. The inference
+# can return multiple potential results while evaluating a Python object, but
+# some branches might not be evaluated, which results in partial inference. In
+# that case, it might be useful to still emit no-member and other checks for
+# the rest of the inferred objects.
+ignore-on-opaque-inference=yes
+
+# List of symbolic message names to ignore for Mixin members.
+ignored-checks-for-mixins=no-member,
+                          not-async-context-manager,
+                          not-context-manager,
+                          attribute-defined-outside-init
+
+# List of class names for which member attributes should not be checked (useful
+# for classes with dynamically set attributes). This supports the use of
+# qualified names.
+ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace
+
+# Show a hint with possible names when a member name was not found. The aspect
+# of finding the hint is based on edit distance.
+missing-member-hint=yes
+
+# The minimum edit distance a name should have in order to be considered a
+# similar match for a missing member name.
+missing-member-hint-distance=1
+
+# The total number of similar names that should be taken in consideration when
+# showing a hint for a missing member.
+missing-member-max-choices=1
+
+# Regex pattern to define which classes are considered mixins.
+mixin-class-rgx=.*[Mm]ixin
+
+# List of decorators that change the signature of a decorated function.
+signature-mutators=
+
+
+[CLASSES]
+
+# Warn about protected attribute access inside special methods
+check-protected-access-in-special-methods=no
+
+# List of method names used to declare (i.e. assign) instance attributes.
+defining-attr-methods=__init__,
+                      __new__,
+                      setUp,
+                      __post_init__
+
+# List of member names, which should be excluded from the protected access
+# warning.
+exclude-protected=_asdict,
+                  _fields,
+                  _replace,
+                  _source,
+                  _make
+
+# List of valid names for the first argument in a class method.
+valid-classmethod-first-arg=cls
+
+# List of valid names for the first argument in a metaclass class method.
+valid-metaclass-classmethod-first-arg=cls
+
+
+[VARIABLES]
+
+# List of additional names supposed to be defined in builtins. Remember that
+# you should avoid defining new builtins when possible.
+additional-builtins=
+
+# Tells whether unused global variables should be treated as a violation.
+allow-global-unused-variables=yes
+
+# List of names allowed to shadow builtins
+allowed-redefined-builtins=
+
+# List of strings which can identify a callback function by name. A callback
+# name must start or end with one of those strings.
+callbacks=cb_,
+          _cb
+
+# A regular expression matching the name of dummy variables (i.e. expected to
+# not be used).
+dummy-variables-rgx=_+$|(_[a-zA-Z0-9_]*[a-zA-Z0-9]+?$)|dummy|^ignored_|^unused_
+
+# Argument names that match this expression will be ignored. Default to name
+# with leading underscore.
+ignored-argument-names=_.*|^ignored_|^unused_
+
+# Tells whether we should check for unused import in __init__ files.
+init-import=no
+
+# List of qualified module names which can have objects that can redefine
+# builtins.
+redefining-builtins-modules=six.moves,past.builtins,future.builtins,builtins,io
+
+
+[FORMAT]
+
+# Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
+expected-line-ending-format=
+
+# Regexp for a line that is allowed to be longer than the limit.
+ignore-long-lines=^\s*(# )?<?https?://\S+>?$
+
+# Number of spaces of indent required inside a hanging or continued line.
+indent-after-paren=4
+
+# String used as indentation unit. This is usually "    " (4 spaces) or "\t" (1
+# tab).
+indent-string='    '
+
+# Maximum number of characters on a single line.
+max-line-length=100
+
+# Maximum number of lines in a module.
+max-module-lines=1000
+
+# Allow the body of a class to be on the same line as the declaration if body
+# contains single statement.
+single-line-class-stmt=no
+
+# Allow the body of an if to be on the same line as the test if there is no
+# else.
+single-line-if-stmt=no
+
+
+[IMPORTS]
+
+# List of modules that can be imported at any level, not just the top level
+# one.
+allow-any-import-level=
+
+# Allow wildcard imports from modules that define __all__.
+allow-wildcard-with-all=no
+
+# Deprecated modules which should not be used, separated by a comma.
+deprecated-modules=
+
+# Output a graph (.gv or any supported image format) of external dependencies
+# to the given file (report RP0402 must not be disabled).
+ext-import-graph=
+
+# Output a graph (.gv or any supported image format) of all (i.e. internal and
+# external) dependencies to the given file (report RP0402 must not be
+# disabled).
+import-graph=
+
+# Output a graph (.gv or any supported image format) of internal dependencies
+# to the given file (report RP0402 must not be disabled).
+int-import-graph=
+
+# Force import order to recognize a module as part of the standard
+# compatibility libraries.
+known-standard-library=
+
+# Force import order to recognize a module as part of a third party library.
+known-third-party=enchant
+
+# Couples of modules and preferred modules, separated by a comma.
+preferred-modules=
+
+
+[EXCEPTIONS]
+
+# Exceptions that will emit a warning when caught.
+overgeneral-exceptions=BaseException,
+                       Exception
+
+
+[REFACTORING]
+
+# Maximum number of nested blocks for function / method body
+max-nested-blocks=5
+
+# Complete name of functions that never returns. When checking for
+# inconsistent-return-statements if a never returning function is called then
+# it will be considered as an explicit return statement and no message will be
+# printed.
+never-returning-functions=sys.exit,argparse.parse_error
+
+
+[SIMILARITIES]
+
+# Comments are removed from the similarity computation
+ignore-comments=yes
+
+# Docstrings are removed from the similarity computation
+ignore-docstrings=yes
+
+# Imports are removed from the similarity computation
+ignore-imports=yes
+
+# Signatures are removed from the similarity computation
+ignore-signatures=yes
+
+# Minimum lines number of a similarity.
+min-similarity-lines=4
+
+
+[DESIGN]
+
+# List of regular expressions of class ancestor names to ignore when counting
+# public methods (see R0903)
+exclude-too-few-public-methods=
+
+# List of qualified class names to ignore when counting class parents (see
+# R0901)
+ignored-parents=
+
+# Maximum number of arguments for function / method.
+max-args=5
+
+# Maximum number of attributes for a class (see R0902).
+max-attributes=7
+
+# Maximum number of boolean expressions in an if statement (see R0916).
+max-bool-expr=5
+
+# Maximum number of branch for function / method body.
+max-branches=12
+
+# Maximum number of locals for function / method body.
+max-locals=15
+
+# Maximum number of parents for a class (see R0901).
+max-parents=7
+
+# Maximum number of public methods for a class (see R0904).
+max-public-methods=20
+
+# Maximum number of return / yield for function / method body.
+max-returns=6
+
+# Maximum number of statements in function / method body.
+max-statements=50
+
+# Minimum number of public methods for a class (see R0903).
+min-public-methods=2
+
+
+[STRING]
+
+# This flag controls whether inconsistent-quotes generates a warning when the
+# character used as a quote delimiter is used inconsistently within a module.
+check-quote-consistency=no
+
+# This flag controls whether the implicit-str-concat should generate a warning
+# on implicit string concatenation in sequences defined over several lines.
+check-str-concat-over-line-jumps=no
+
+
+[BASIC]
+
+# Naming style matching correct argument names.
+argument-naming-style=snake_case
+
+# Regular expression matching correct argument names. Overrides argument-
+# naming-style. If left empty, argument names will be checked with the set
+# naming style.
+#argument-rgx=
+
+# Naming style matching correct attribute names.
+attr-naming-style=snake_case
+
+# Regular expression matching correct attribute names. Overrides attr-naming-
+# style. If left empty, attribute names will be checked with the set naming
+# style.
+#attr-rgx=
+
+# Bad variable names which should always be refused, separated by a comma.
+bad-names=foo,
+          bar,
+          baz,
+          toto,
+          tutu,
+          tata
+
+# Bad variable names regexes, separated by a comma. If names match any regex,
+# they will always be refused
+bad-names-rgxs=
+
+# Naming style matching correct class attribute names.
+class-attribute-naming-style=any
+
+# Regular expression matching correct class attribute names. Overrides class-
+# attribute-naming-style. If left empty, class attribute names will be checked
+# with the set naming style.
+#class-attribute-rgx=
+
+# Naming style matching correct class constant names.
+class-const-naming-style=UPPER_CASE
+
+# Regular expression matching correct class constant names. Overrides class-
+# const-naming-style. If left empty, class constant names will be checked with
+# the set naming style.
+#class-const-rgx=
+
+# Naming style matching correct class names.
+class-naming-style=PascalCase
+
+# Regular expression matching correct class names. Overrides class-naming-
+# style. If left empty, class names will be checked with the set naming style.
+#class-rgx=
+
+# Naming style matching correct constant names.
+const-naming-style=UPPER_CASE
+
+# Regular expression matching correct constant names. Overrides const-naming-
+# style. If left empty, constant names will be checked with the set naming
+# style.
+#const-rgx=
+
+# Minimum line length for functions/classes that require docstrings, shorter
+# ones are exempt.
+docstring-min-length=-1
+
+# Naming style matching correct function names.
+function-naming-style=snake_case
+
+# Regular expression matching correct function names. Overrides function-
+# naming-style. If left empty, function names will be checked with the set
+# naming style.
+#function-rgx=
+
+# Good variable names which should always be accepted, separated by a comma.
+good-names=i,
+           j,
+           k,
+           ex,
+           Run,
+           _
+
+# Good variable names regexes, separated by a comma. If names match any regex,
+# they will always be accepted
+good-names-rgxs=
+
+# Include a hint for the correct naming format with invalid-name.
+include-naming-hint=no
+
+# Naming style matching correct inline iteration names.
+inlinevar-naming-style=any
+
+# Regular expression matching correct inline iteration names. Overrides
+# inlinevar-naming-style. If left empty, inline iteration names will be checked
+# with the set naming style.
+#inlinevar-rgx=
+
+# Naming style matching correct method names.
+method-naming-style=snake_case
+
+# Regular expression matching correct method names. Overrides method-naming-
+# style. If left empty, method names will be checked with the set naming style.
+#method-rgx=
+
+# Naming style matching correct module names.
+module-naming-style=snake_case
+
+# Regular expression matching correct module names. Overrides module-naming-
+# style. If left empty, module names will be checked with the set naming style.
+#module-rgx=
+
+# Colon-delimited sets of names that determine each other's naming style when
+# the name regexes allow several styles.
+name-group=
+
+# Regular expression which should only match function or class names that do
+# not require a docstring.
+no-docstring-rgx=^_
+
+# List of decorators that produce properties, such as abc.abstractproperty. Add
+# to this list to register other decorators that produce valid properties.
+# These decorators are taken in consideration only for invalid-name.
+property-classes=abc.abstractproperty
+
+# Regular expression matching correct type variable names. If left empty, type
+# variable names will be checked with the set naming style.
+#typevar-rgx=
+
+# Naming style matching correct variable names.
+variable-naming-style=snake_case
+
+# Regular expression matching correct variable names. Overrides variable-
+# naming-style. If left empty, variable names will be checked with the set
+# naming style.
+#variable-rgx=
diff --git a/resources/DeleteBucketContents/src/awscommunity_s3_deletebucketcontents/__init__.py b/resources/DeleteBucketContents/src/awscommunity_s3_deletebucketcontents/__init__.py
new file mode 100644
index 00000000..e69de29b
diff --git a/resources/DeleteBucketContents/src/awscommunity_s3_deletebucketcontents/handlers.py b/resources/DeleteBucketContents/src/awscommunity_s3_deletebucketcontents/handlers.py
new file mode 100644
index 00000000..6c3a2e25
--- /dev/null
+++ b/resources/DeleteBucketContents/src/awscommunity_s3_deletebucketcontents/handlers.py
@@ -0,0 +1,276 @@
+"""
+Handler functions for the public registry resource type
+AwsCommunity::S3::DeleteBucketContents 
+"""
+#pylint:disable=too-many-branches
+
+import json
+import logging
+
+import botocore
+
+from cloudformation_cli_python_lib import (
+    Action,
+    HandlerErrorCode,
+    OperationStatus,
+    ProgressEvent,
+    Resource,
+    exceptions,
+)
+
+from .models import ResourceModel
+
+# Use this logger to forward log messages to CloudWatch Logs.
+LOG = logging.getLogger(__name__)
+LOG.setLevel(logging.DEBUG)
+TYPE_NAME = "AwsCommunity::S3::DeleteBucketContents"
+DELETE_BUCKET_CONTENTS_TAG = "aws-community-delete-bucket-contents"
+
+resource = Resource(TYPE_NAME, ResourceModel)
+test_entrypoint = resource.test_entrypoint
+
+def check_bucket_exists(session, bucket_name):
+    "Check to see if the bucket exists"
+    s3 = session.client("s3")
+    try:
+        s3.head_bucket(Bucket=bucket_name)
+        return True
+    except s3.exceptions.NoSuchBucket:
+        LOG.error("Bucket does not exist: %s", bucket_name)
+        return False
+
+def check_tag(session, bucket_name):
+    "Check to see if the deletion tag is on the bucket"
+    s3 = session.client("s3")
+    try:
+        tags = s3.get_bucket_tagging(Bucket=bucket_name)
+        if "TagSet" in tags:
+            for tag in tags["TagSet"]:
+                if tag["Key"] == DELETE_BUCKET_CONTENTS_TAG and tag["Value"] == "true":
+                    return True
+    except botocore.exceptions.ClientError as ce:
+        # It looks like we can't actually catch s3.exceptions.NoSuchTagSet like we need to
+        if "NoSuchTagSet" not in str(ce):
+            raise ce
+    return False
+
+def create_tag(session, bucket_name):
+    "Create the deletion tag on the bucket"
+    s3 = session.client("s3")
+    tags = None
+    try:
+        tags = s3.get_bucket_tagging(Bucket=bucket_name)
+    except botocore.exceptions.ClientError as ce:
+        # It looks like we can't actually catch s3.exceptions.NoSuchTagSet like we need to
+        if "NoSuchTagSet" not in str(ce):
+            raise ce
+
+    if not tags:
+        tags = {}
+        tags["TagSet"] = []
+
+    tags["TagSet"].append({"Key": DELETE_BUCKET_CONTENTS_TAG, "Value": "true"})
+    s3.put_bucket_tagging(Bucket=bucket_name, Tagging={"TagSet": tags["TagSet"]})
+
+def remove_tag(session, bucket_name):
+    "Remove the deletion tag from the bucket"
+
+    s3 = session.client("s3")
+    tags = None
+    try:
+        tags = s3.get_bucket_tagging(Bucket=bucket_name)
+    except botocore.exceptions.ClientError as ce:
+        # It looks like we can't actually catch s3.exceptions.NoSuchTagSet like we need to
+        if "NoSuchTagSet" not in str(ce):
+            raise ce
+
+    if not tags:
+        return 
+
+    new_tags = []
+    for tag in tags["TagSet"]:
+        # Append everything except our tag, leave everything else alone
+        if tag["Key"] != DELETE_BUCKET_CONTENTS_TAG:
+            new_tags.append(tag)
+    s3.put_bucket_tagging(Bucket=bucket_name, Tagging={"TagSet": new_tags})
+
+def progress_not_found(bucket_name):
+    "Returns a not found progress event"
+    return ProgressEvent(
+        status = OperationStatus.FAILED,
+        message = f"Bucket does not exist: {bucket_name}",
+        errorCode = HandlerErrorCode.NotFound
+    )
+
+@resource.handler(Action.CREATE)
+def create_handler(session, request, callback_context): #pylint:disable=unused-argument
+    "Handle CloudFormation CREATE events"
+    
+    model = request.desiredResourceState
+    
+    LOG.debug("create_handler")
+    LOG.debug("model: %s", json.dumps(model, default=str))
+
+    progress = ProgressEvent(
+        status=OperationStatus.SUCCESS,
+        resourceModel=model,
+    )
+
+    try:
+        # Make sure the bucket exists
+        exists = check_bucket_exists(session, model.BucketName)
+        if not exists:
+            return progress_not_found(model.BucketName)
+
+        # Check to see if this resource was already created
+        has_tag = check_tag(session, model.BucketName)
+        if has_tag:
+            msg = f"Bucket is already tagged for content deletion: {model.BucketName}"
+            return ProgressEvent(
+                status = OperationStatus.FAILED,
+                message = msg, 
+                errorCode = HandlerErrorCode.AlreadyExists
+            )
+
+        # Create the tag so we know we already did this
+        create_tag(session, model.BucketName)
+            
+    except Exception as e:
+        LOG.exception(e)
+        raise exceptions.InternalFailure(f"Unxpected exception: {e}")
+
+    return progress
+
+@resource.handler(Action.DELETE)
+def delete_handler(session, request, callback_context): #pylint:disable=unused-argument
+    "Handle CloudFormation DELETE events"
+    model = request.desiredResourceState
+
+    LOG.debug("delete_handler")
+    LOG.debug("model: %s", json.dumps(model, default=str))
+
+    try:
+        # Make sure the bucket exists
+        s3 = session.client("s3")
+        exists = check_bucket_exists(session, model.BucketName)
+        if not exists:
+            return progress_not_found(model.BucketName)
+
+        # Verify the tag
+        if not check_tag(session, model.BucketName):
+            return ProgressEvent(
+                status = OperationStatus.FAILED,
+                message = f"Bucket is not tagged for content deletion: {model.BucketName}",
+                errorCode = HandlerErrorCode.NotFound)
+
+        # Get the contents of the bucket
+
+        objects_to_delete = []
+
+        has_more_results = True
+        next_key_marker = None
+        next_version_id_marker = None
+
+        while has_more_results:
+            args = {
+                "Bucket": model.BucketName
+            }
+            if next_key_marker:
+                args["KeyMarker"] = next_key_marker
+                args["VersionIdMarker"] = next_version_id_marker
+            contents = s3.list_object_versions(**args)
+
+            # This causes a failure if there are too many objects!
+            #LOG.debug("contents: %s", json.dumps(contents, default=str))
+
+            if "Versions" not in contents and "DeleteMarkers" not in contents:
+                LOG.debug("Versions or DeleteMarkers not found in contents")
+                break
+
+            if "Versions" in contents:
+                for v in contents["Versions"]:
+                    d = {"Key": v["Key"]}
+                    if "VersionId" in v and v["VersionId"] != "null":
+                        d["VersionId"] = v["VersionId"]
+                    objects_to_delete.append(d)
+
+            if "DeleteMarkers" in contents:
+                for v in contents["DeleteMarkers"]:
+                    d = {"Key": v["Key"]}
+                    if "VersionId" in v and v["VersionId"] != "null":
+                        d["VersionId"] = v["VersionId"]
+                    objects_to_delete.append(d)
+
+            if len(objects_to_delete) == 0:
+                LOG.debug("objects_to_delete is empty")
+                break
+
+            if contents["IsTruncated"] is True:
+                has_more_results = True
+                next_key_marker = contents["NextKeyMarker"] 
+                next_version_id_marker = contents["NextVersionIdMarker"]
+                if next_key_marker is None or next_version_id_marker is None:
+                    LOG.warning("NextKeyMarker and NextVersionIdMarker not set")
+                    break
+            else:
+                has_more_results = False
+
+        # Delete the contents
+        LOG.debug("Bucket has %s objects to delete", len(objects_to_delete))
+
+        # Break into chunks of 1000 or less
+        def chunks(lst, n):
+            "Break an array into chunks of n size"
+            for i in range(0, len(lst), n):
+                yield lst[i:i + n]
+
+        # What if this takes a long time? Should we use callbacks? TODO
+        for chunk in chunks(objects_to_delete, 1000):
+            LOG.debug("About to delete chunk: %s", json.dumps(chunk, default=str))
+            r = s3.delete_objects(Bucket=model.BucketName, Delete={"Objects": chunk})
+            LOG.debug("delete_objects response: %s", json.dumps(r, default=str))
+
+        LOG.debug("All chunks deleted, about to remove the tag")
+        # TODO - Confirm that the bucket is empty
+
+        # Remove our tag from the bucket
+        remove_tag(session, model.BucketName)
+
+        progress = ProgressEvent(
+            status=OperationStatus.SUCCESS,
+            resourceModel=None,
+        )
+
+    except Exception as e:
+        LOG.exception(e)
+        raise exceptions.InternalFailure(f"Unxpected exception: {e}")
+
+    return progress
+
+
+@resource.handler(Action.READ)
+def read_handler(session, request, callback_context): #pylint:disable=unused-argument
+    "Handle CloudFormation READ events"
+
+    model = request.desiredResourceState
+
+    LOG.debug("read_handler")
+    LOG.debug("model: %s", json.dumps(model, default=str))
+
+    exists = check_bucket_exists(session, model.BucketName)
+    if not exists:
+        return progress_not_found(model.BucketName)
+
+    # Verify the tag
+    if not check_tag(session, model.BucketName):
+        return ProgressEvent(
+            status = OperationStatus.FAILED,
+            message = f"Bucket is not tagged for content deletion: {model.BucketName}",
+            errorCode = HandlerErrorCode.NotFound)
+
+    return ProgressEvent(
+        status=OperationStatus.SUCCESS,
+        resourceModel=model,
+    )
+
+
diff --git a/resources/DeleteBucketContents/src/awscommunity_s3_deletebucketcontents/models.py b/resources/DeleteBucketContents/src/awscommunity_s3_deletebucketcontents/models.py
new file mode 100644
index 00000000..74f0c489
--- /dev/null
+++ b/resources/DeleteBucketContents/src/awscommunity_s3_deletebucketcontents/models.py
@@ -0,0 +1,80 @@
+# DO NOT modify this file by hand, changes will be overwritten
+import sys
+from dataclasses import dataclass
+from inspect import getmembers, isclass
+from typing import (
+    AbstractSet,
+    Any,
+    Generic,
+    Mapping,
+    MutableMapping,
+    Optional,
+    Sequence,
+    Type,
+    TypeVar,
+)
+
+from cloudformation_cli_python_lib.interface import (
+    BaseModel,
+    BaseResourceHandlerRequest,
+)
+from cloudformation_cli_python_lib.recast import recast_object
+from cloudformation_cli_python_lib.utils import deserialize_list
+
+T = TypeVar("T")
+
+
+def set_or_none(value: Optional[Sequence[T]]) -> Optional[AbstractSet[T]]:
+    if value:
+        return set(value)
+    return None
+
+
+@dataclass
+class ResourceHandlerRequest(BaseResourceHandlerRequest):
+    # pylint: disable=invalid-name
+    desiredResourceState: Optional["ResourceModel"]
+    previousResourceState: Optional["ResourceModel"]
+    typeConfiguration: Optional["TypeConfigurationModel"]
+
+
+@dataclass
+class ResourceModel(BaseModel):
+    BucketName: Optional[str]
+
+    @classmethod
+    def _deserialize(
+        cls: Type["_ResourceModel"],
+        json_data: Optional[Mapping[str, Any]],
+    ) -> Optional["_ResourceModel"]:
+        if not json_data:
+            return None
+        dataclasses = {n: o for n, o in getmembers(sys.modules[__name__]) if isclass(o)}
+        recast_object(cls, json_data, dataclasses)
+        return cls(
+            BucketName=json_data.get("BucketName"),
+        )
+
+
+# work around possible type aliasing issues when variable has same name as a model
+_ResourceModel = ResourceModel
+
+
+@dataclass
+class TypeConfigurationModel(BaseModel):
+
+    @classmethod
+    def _deserialize(
+        cls: Type["_TypeConfigurationModel"],
+        json_data: Optional[Mapping[str, Any]],
+    ) -> Optional["_TypeConfigurationModel"]:
+        if not json_data:
+            return None
+        return cls(
+        )
+
+
+# work around possible type aliasing issues when variable has same name as a model
+_TypeConfigurationModel = TypeConfigurationModel
+
+
diff --git a/resources/DeleteBucketContents/src/requirements.txt b/resources/DeleteBucketContents/src/requirements.txt
new file mode 100644
index 00000000..03b41d7a
--- /dev/null
+++ b/resources/DeleteBucketContents/src/requirements.txt
@@ -0,0 +1,71 @@
+aiosmtpd==1.4.2
+astroid==2.12.5
+atpublic==3.1
+attrs==22.1.0
+aws-sam-translator==1.50.0
+black==22.6.0
+boto3==1.24.61
+botocore==1.27.61
+certifi==2022.6.15
+cfn-flip==1.3.0
+cfn-lint==0.63.0
+charset-normalizer==2.1.1
+click==8.1.3
+cloudformation-cli==0.2.25
+cloudformation-cli-python-plugin==2.1.5
+colorama==0.4.5
+dill==0.3.5.1
+docker==6.0.0
+exceptiongroup==1.0.0rc9
+hypothesis==6.54.4
+idna==3.3
+importlib-metadata==4.12.0
+iniconfig==1.1.1
+isort==5.10.1
+Jinja2==2.11.3
+jmespath==1.0.1
+jschema-to-python==1.2.3
+jsonpatch==1.32
+jsonpickle==2.2.0
+jsonpointer==2.3
+jsonschema==3.2.0
+junit-xml==1.9
+lazy-object-proxy==1.7.1
+markdown-it-py==2.1.0
+MarkupSafe==2.0.1
+mccabe==0.7.0
+mdformat==0.7.16
+mdurl==0.1.2
+mypy-extensions==0.4.3
+nested-lookup==0.2.25
+networkx==2.6.3
+ordered-set==4.1.0
+packaging==21.3
+pathspec==0.9.0
+pbr==5.10.0
+platformdirs==2.5.2
+pluggy==1.0.0
+py==1.11.0
+pylint==2.15.0
+pyparsing==3.0.9
+pyrsistent==0.18.1
+pytest==7.1.2
+pytest-localserver==0.6.0
+pytest-random-order==1.0.4
+python-dateutil==2.8.2
+PyYAML==5.4.1
+requests==2.28.1
+s3transfer==0.6.0
+sarif-om==1.0.4
+six==1.16.0
+sortedcontainers==2.4.0
+tomli==2.0.1
+tomlkit==0.11.4
+typed-ast==1.5.4
+types-dataclasses==0.6.6
+typing_extensions==4.3.0
+urllib3==1.26.12
+websocket-client==1.4.0
+Werkzeug==2.1.2
+wrapt==1.14.1
+zipp==3.8.1
diff --git a/resources/DeleteBucketContents/template.yml b/resources/DeleteBucketContents/template.yml
new file mode 100644
index 00000000..b0b3c3ae
--- /dev/null
+++ b/resources/DeleteBucketContents/template.yml
@@ -0,0 +1,24 @@
+AWSTemplateFormatVersion: "2010-09-09"
+Transform: AWS::Serverless-2016-10-31
+Description: AWS SAM template for the AwsCommunity::S3::DeleteBucketContents resource type
+
+Globals:
+  Function:
+    Timeout: 180  # docker start-up times can be long for SAM CLI
+    MemorySize: 256
+
+Resources:
+  TypeFunction:
+    Type: AWS::Serverless::Function
+    Properties:
+      Handler: awscommunity_s3_deletebucketcontents.handlers.resource
+      Runtime: python3.7
+      CodeUri: build/
+
+  TestEntrypoint:
+    Type: AWS::Serverless::Function
+    Properties:
+      Handler: awscommunity_s3_deletebucketcontents.handlers.test_entrypoint
+      Runtime: python3.7
+      CodeUri: build/
+


Test patch:
diff --git a/resources/BucketNotification/src/awscommunity_s3_bucketnotification/test_lambda.zip b/resources/BucketNotification/test/test_lambda.zip
similarity index 100%
rename from resources/BucketNotification/src/awscommunity_s3_bucketnotification/test_lambda.zip
rename to resources/BucketNotification/test/test_lambda.zip
diff --git a/resources/DeleteBucketContents/run-test.sh b/resources/DeleteBucketContents/run-test.sh
new file mode 100755
index 00000000..6f84c7d7
--- /dev/null
+++ b/resources/DeleteBucketContents/run-test.sh
@@ -0,0 +1,7 @@
+set -eou pipefail
+
+cd src
+pylint awscommunity_s3_deletebucketcontents/*.py
+cd ..
+cfn validate && cfn generate && cfn submit --dry-run && cfn test
+