AWS CDK Python Set S3 bucket Removal Policy

0

I am trying to set the S3 bucket removal policy when I create a new S3 bucket with the aws_cdk.aws_s3 module. This is required so the bucket is deleted when I remove the stack.

According to the documentation I need the following:

removal_policy=cdk.RemovalPolicy.DESTROY, auto_delete_objects=True

When I set these options and deploy the CDK project I receive the following error: NameError: name 'cdk' is not defined

I'm sure I missing something very simple here!

asked 6 months ago312 views
1 Answer
0
Accepted Answer

Hello.

Is it possible for you to share the entire code?
I suspect that "cdk" may not be imported as shown below.

import aws_cdk as cdk
profile picture
EXPERT
answered 6 months ago
  • Hi Riku

    The full code is below. I take your point and the S3 module is imported as s3, and I have changed the code to reflect this, now get the following error:

    'aws_cdk.aws_s3' has no attribute 'RemovalPolicy'

    import aws_cdk.aws_s3 as s3 def init(self, scope: Construct, construct_id: str, **kwargs) -> None: super().init(scope, construct_id, **kwargs) bucket = s3.Bucket(self, "MyBucket", bucket_name="test-bucket", versioned=False, encryption=s3.BucketEncryption.S3_MANAGED, removal_policy=s3.RemovalPolicy.DESTROY, auto_delete_objects=True

  • Please try the code below.

    import aws_cdk.core as cdk
    import aws_cdk.aws_s3 as s3
    
    class CdkTestStack(cdk.stack):
        def __init__(self, scope: cdk.Construct, id: str, **kwargs):
            super().__init__(scope, id, **kwargs)
            
            bucket = s3.Bucket(self, "MyBucket",
                bucket_name="test-bucket",
                versioned=False,
                encryption=s3.BucketEncryption.S3_MANAGED,
                removal_policy=cdk.RemovalPolicy.DESTROY,
                auto_delete_objects=True)
    

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions