Untitled

 avatar
unknown
plain_text
6 months ago
1.7 kB
2
Indexable
from aws_cdk import aws_s3, RemovalPolicy, Stack, Duration
from principal_environment import PrincipalEnvironment
from aws_constructs.policy_statement import PolicyStatementConstruct


class BucketConstruct:
    @staticmethod
    def create_bucket(scope: Stack, bucket: str, env: PrincipalEnvironment) -> aws_s3.Bucket:

        bucket_obj = aws_s3.Bucket(
            scope,
            f"Bucket-{bucket}",
            block_public_access=aws_s3.BlockPublicAccess.BLOCK_ALL,
            encryption=aws_s3.BucketEncryption.KMS,
            enforce_ssl=True,
            bucket_name=f"{bucket}-{env.aws_environment_name}-{env.region}",
            versioned=False,
            removal_policy=RemovalPolicy.DESTROY,
            encryption_key=scope.kms,
            lifecycle_rules=[aws_s3.LifecycleRule(
                id="bucket_lifecycle",
                expiration=Duration.days(365 * 7)
            )]
        )

        if env.aws_environment_name != "dev":
            bucket_obj.add_to_resource_policy(PolicyStatementConstruct.deny_presigned_url(bucket_obj.bucket_arn))

        return bucket_obj

    @staticmethod
    def create_lifecyle_rules(bucket: aws_s3.Bucket, config: dict) -> None:
        for retention in config:
            for prefix in retention["prefixes"]:
                bucket.add_lifecycle_rule(
                    enabled=retention.get("enabled", True),
                    id=f"expire_{prefix}after_{retention['duration']}_days".replace("/", "_"),
                    expiration=Duration.days(retention["duration"]),
                    noncurrent_version_expiration=Duration.days(1),
                    prefix=prefix
                )
Editor is loading...
Leave a Comment