Configure S3 encryption using CDK
AWS S3 encryption is the ability to encrypt objects stored in S3.
AWS S3 supports the follow encryption states:
UNENCRYPTED
: - This is deprecated and no longer use for any new buckets.S3_MANAGED
: (SSE-S3) - S3 will use S3 managed keys for server side encryption. This is the default encryption state for all new buckets and will be used if no encryption state is specified.KMS_MANAGED
: (SSE-KMS) - Server Side encryption with S3 will use KMS managed keys that you have created using AWS KMS serviceKMS
:(SSE-C) - S3 will use customer managed keys using an external KMS serviceDSSE_MANAGED
: (DSSE-KMS) - S3 uses Dual Layer Server-Side Encryption (DSSE) with AWS KMS managed keysDSSE
: (DSSE-C) - S3 uses Double Server-Side Encryption (SSE) with customer provided keys from an external KMS service
Configure S3 encryption using CDK
You can enable encryption on the S3 bucket by setting the encryption
property of the Bucket
construct to BucketEncryption.S3_MANAGED
which is the default way of encrypting data in S3.
# 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,
# 👇🏽 Bucket encryption will use S3 managed keys
encryption=s3.BucketEncryption.S3_MANAGED,
removal_policy=RemovalPolicy.DESTROY,
)
If you want to use KMS managed keys, you can use the encryption_key
property of the Bucket
construct to specify the KMS key to use for encryption.
# 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)
# 👇🏽 Create a KMS key to use for encryption
kms_key = kms.Key(self, "MyKmsKey")
my_bucket = s3.Bucket(
self,
id=self.BUCKET_ID,
# 👇🏽 Bucket encryption will use KMS managed keys
encryption=s3.BucketEncryption.KMS_MANAGED,
# 👇🏽 Specify the KMS key to use for encryption
encryption_key=kms_key,
removal_policy=RemovalPolicy.DESTROY,
)