Configure S3 versioning using CDK
AWS S3 versioning is the ability to keep multiple versions of an object in one bucket.
By default, versioning is disabled, however, if you enable it you cannot disable it. You can only suspend it.
Configure S3 versioning using CDK
You can enable versioning on the S3 bucket by setting the versioned
property of the Bucket
construct to True
.
# filename: cdk_app/s3_stack.py
from aws_cdk import (
Stack,
aws_s3 as s3,
RemovalPolicy,
)
from constructs import Construct
class S3Stack(Stack):
BUCKET_ID = "MyS3Bucket"
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
my_bucket = s3.Bucket(
self,
id=self.BUCKET_ID,
versioned=True, # 👈🏽 Enable versioning
removal_policy=RemovalPolicy.DESTROY,
)
Configure the CDK app to use the S3Stack
stack.
# filename: app.py
import aws_cdk as cdk
from cdk_app.s3_stack import S3Stack
app = cdk.App()
s3_stack = S3Stack(app, "S3Stack")
app.synth()
To deploy the stack run cdk deploy
.
If you go to the AWS console and check the S3 bucket, you will see that versioning is enabled.
Suspending versioning
You can suspend versioning by setting the versioned
property of the Bucket
construct to False
.
# filename: cdk_app/s3_stack.py
from aws_cdk import (
Stack,
aws_s3 as s3,
RemovalPolicy,
)
from constructs import Construct
class S3Stack(Stack):
BUCKET_ID = "MyS3Bucket"
def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
my_bucket = s3.Bucket(
self,
id=self.BUCKET_ID,
versioned=False, # 👈🏽 Suspend versioning
removal_policy=RemovalPolicy.DESTROY,
)
Conclusion
Currently CDK doesn't support configuring MFADelete for S3 buckets. There is a feature request for it, however, most methods are workarounds.
Need Help? Open a discussion thread on GitHub.
Related Posts
📄
How to create a Lambda function in a Custom Docker image using AWS CDK in Python
📄
How to create a Lambda function in a ECR Docker image using AWS CDK in Python
📄
Add CORS configuration to a S3 bucket using AWS CDK
📄
How to create a lambda function using AWS CDK in Python
📄
How to import an existing lambda function using AWS CDK in Python