Example #1
0
    def __init__(self, scope: cdk.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # Create AWS S3 Bucket
        bucket = s3.Bucket(
            self,
            id=AWS_S3_BUCKET_NAME,
            bucket_name=AWS_S3_BUCKET_NAME,
            public_read_access=True,
            website_index_document="index.html",
            removal_policy=core.RemovalPolicy.DESTROY,
            auto_delete_objects=True,
        )

        source_config = cloudfront.SourceConfiguration(
            s3_origin_source=cloudfront.S3OriginConfig(
                s3_bucket_source=bucket),
            behaviors=[cloudfront.Behavior(is_default_behavior=True)])

        # Create CloudFront distribution
        distribution = cloudfront.CloudFrontWebDistribution(
            self,
            id=AWS_CLOUDFRONT_DISTRIBUTION_NAME,
            origin_configs=[source_config])
Example #2
0
    def __init__(self, scope: core.Construct, id: str, bucket_name: str,
                 cf_id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here
        bucket = s3.Bucket(self,
                           id=id,
                           bucket_name=bucket_name,
                           access_control=s3.BucketAccessControl.PUBLIC_READ,
                           website_index_document="index.html")
        bucket.grant_public_access()
        cert = acm.Certificate(self,
                               "Cert",
                               domain_name=bucket_name,
                               validation=acm.CertificateValidation.from_dns())

        cf.CloudFrontWebDistribution(
            self,
            id=cf_id,
            price_class=cf.PriceClass.PRICE_CLASS_200,
            origin_configs=[
                cf.SourceConfiguration(
                    behaviors=[cf.Behavior(is_default_behavior=True)],
                    s3_origin_source=cf.S3OriginConfig(
                        s3_bucket_source=bucket))
            ],
            alias_configuration=cf.AliasConfiguration(
                names=[bucket_name], acm_cert_ref=cert.certificate_arn))
Example #3
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # The code that defines your stack goes here
        source_bucket = s3.Bucket(self, 'DnaFront', versioned=True,)
        source_bucket.add_to_resource_policy(iam.PolicyStatement(
            actions=["s3:GetObject"],
            resources=[source_bucket.arn_for_objects("*")],
            principals=[iam.AnyPrincipal()],
        ))

        distribution = cfn.CloudFrontWebDistribution(self, "DnaFrontEndDistributor",
            origin_configs=[
                cfn.SourceConfiguration(
                    s3_origin_source=cfn.S3OriginConfig(
                        s3_bucket_source=source_bucket
                    ),
                    behaviors=[cfn.Behavior(is_default_behavior=True)]
                )
            ],
            default_root_object='index.html',
            viewer_protocol_policy=cfn.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
            error_configurations=[
                cfn.CfnDistribution.CustomErrorResponseProperty(error_code=403, response_code=200, error_caching_min_ttl=5, response_page_path='/index.html'),
                cfn.CfnDistribution.CustomErrorResponseProperty(error_code=404, response_code=200, error_caching_min_ttl=5, response_page_path='/index.html'),
            ],
        )
Example #4
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self.bucket = s3.Bucket(
            self,
            "bucket",
            website_index_document=f"{stack_vars.root_html}",
            bucket_name=f"{stack_vars.bucket_name}")
        self.bucket.grant_public_access()
        names = [f"{stack_vars.bucket_name}", f"www.{stack_vars.bucket_name}"],

        cf.CloudFrontWebDistribution(
            self,
            "cloudwebdistribution",
            price_class=cf.PriceClass.PRICE_CLASS_ALL,
            default_root_object=f"{stack_vars.root_html}",
            alias_configuration=cf.AliasConfiguration(
                ssl_method=cf.SSLMethod.SNI,
                acm_cert_ref=stack_vars.cert_arn,
                names=[
                    f"{stack_vars.bucket_name}",
                    f"www.{stack_vars.bucket_name}"
                ],
                security_policy=cf.SecurityPolicyProtocol.TLS_V1_2_2018),
            origin_configs=[
                cf.SourceConfiguration(
                    behaviors=[cf.Behavior(is_default_behavior=True)],
                    s3_origin_source=cf.S3OriginConfig(
                        s3_bucket_source=self.bucket))
            ])
def generate_cloudfront_distribution(scope, certificate, beanstalk_url):
    cloudfront_distribution = cloudfront.CloudFrontWebDistribution(
        scope=scope,
        id="JVSANTOSTier1CloudfrontDistribution",
        default_root_object="",
        origin_configs=[
            SourceConfiguration(
                custom_origin_source=CustomOriginConfig(
                    domain_name=beanstalk_url,
                    origin_protocol_policy=OriginProtocolPolicy.MATCH_VIEWER,
                    http_port=80,
                    https_port=443),
                behaviors=[
                    Behavior(allowed_methods=CloudFrontAllowedMethods.ALL,
                             is_default_behavior=True,
                             forwarded_values=CfnDistribution.
                             ForwardedValuesProperty(
                                 query_string=True,
                                 cookies=CfnDistribution.CookiesProperty(
                                     forward="all"),
                                 headers=["*"]))
                ])
        ],
        viewer_certificate=ViewerCertificate.from_acm_certificate(
            certificate=certificate,
            aliases=["jvsantos-tier1.apperdevops.com"]),
    )
    return cloudfront_distribution
Example #6
0
    def __init__(self, scope: core.Construct, construct_id: str, domain: str,
                 **kwargs) -> None:
        self.domain = domain
        super().__init__(scope, construct_id, **kwargs)

        bucket = s3.Bucket(self,
                           "sitebucket",
                           bucket_name=domain,
                           public_read_access=True,
                           website_index_document="index.html")
        core.CfnOutput(self, "siteBucketName", value=bucket.bucket_name)
        core.CfnOutput(self,
                       "siteBucketWebsite",
                       value=bucket.bucket_website_url)

        source_config = cf.SourceConfiguration(
            s3_origin_source=cf.S3OriginConfig(s3_bucket_source=bucket, ),
            behaviors=[cf.Behavior(is_default_behavior=True)])

        dist = cf.CloudFrontWebDistribution(self,
                                            "staticSiteDist",
                                            origin_configs=[source_config])
        core.CfnOutput(self, 'static_site_dist_id', value=dist.distribution_id)
        core.CfnOutput(self,
                       'static_site_cloudfront_domain',
                       value=dist.domain_name)
Example #7
0
    def _create_cloudfront_distribution(self):
        """Create a cloudfront distribution with a public bucket as the origin"""
        origin_source = cloudfront.CustomOriginConfig(
            domain_name=self.bucket.bucket_website_domain_name,
            origin_protocol_policy=cloudfront.OriginProtocolPolicy.HTTP_ONLY,
            origin_headers={"Referer": self.__origin_referer_header},
        )

        self.distribution = cloudfront.CloudFrontWebDistribution(
            self,
            "cloudfront_distribution",
            viewer_certificate = cloudfront.ViewerCertificate.from_acm_certificate(self.certificate,
                aliases=[self._site_domain_name],
                security_policy=cloudfront.SecurityPolicyProtocol.TLS_V1_2_2019,
                ssl_method=cloudfront.SSLMethod.SNI
            ),
            origin_configs=[
                cloudfront.SourceConfiguration(
                    custom_origin_source=origin_source,
                    behaviors=[
                        cloudfront.Behavior(
                            is_default_behavior=True,
                        )
                    ],
                )
            ],
            viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
            price_class=cloudfront.PriceClass.PRICE_CLASS_ALL,
        )
Example #8
0
    def __init__(self, scope: core.Construct, id: str, s3bucket,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        bucketName = s3.Bucket.from_bucket_name(self, "s3bucket", s3bucket)
        webAclId = self.node.try_get_context("web_acl_id")

        cdnId = cdn.CloudFrontWebDistribution(
            self,
            "webhosting-cdn",
            origin_configs=[
                cdn.SourceConfiguration(
                    behaviors=[
                        cdn.Behavior(is_default_behavior=True)
                        #cdn.Behavior(is_default_behavior=False,path_pattern="/img/")
                    ],
                    origin_path="/build",
                    s3_origin_source=cdn.S3OriginConfig(
                        s3_bucket_source=bucketName,
                        origin_access_identity=cdn.OriginAccessIdentity(
                            self, 'webhosting-origin'),
                    ),
                )
            ],
            web_acl_id=webAclId)
        core.CfnOutput(self,
                       'cdnid',
                       value=cdnId.distribution_id,
                       export_name='distribution-id')
Example #9
0
 def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
     super().__init__(scope, id, **kwargs)
     table = ddb.Table(self,
                       'WeatherData',
                       partition_key={
                           'name': 'date_part',
                           'type': ddb.AttributeType.NUMBER
                       },
                       sort_key={
                           'name': 'time_part',
                           'type': ddb.AttributeType.NUMBER
                       },
                       read_capacity=1,
                       write_capacity=1)
     main_lambda = _lambda.Function(
         self,
         'MainHandler',
         runtime=_lambda.Runtime.PYTHON_3_8,
         code=_lambda.Code.asset('lambda'),
         handler='main.handler',
         environment={'WEATHERDATA_TABLE_NAME': table.table_name},
         log_retention=logs.RetentionDays.TWO_WEEKS)
     table.grant_read_write_data(main_lambda)
     api = apigw.LambdaRestApi(self, 'MainEndpoint', handler=main_lambda)
     api.add_usage_plan('UsagePlan',
                        throttle=apigw.ThrottleSettings(rate_limit=10,
                                                        burst_limit=10))
     cloud_front = cf.CloudFrontWebDistribution(
         self,
         'Https2HttpDistribution',
         viewer_protocol_policy=cf.ViewerProtocolPolicy.ALLOW_ALL,
         geo_restriction=cf.GeoRestriction.whitelist('US'),
         origin_configs=[
             cf.SourceConfiguration(
                 custom_origin_source=cf.CustomOriginConfig(
                     domain_name=api.url.lstrip("https://").split("/")[0],
                     origin_protocol_policy=cf.OriginProtocolPolicy.
                     HTTPS_ONLY,
                 ),
                 origin_path='/prod',
                 behaviors=[
                     cf.Behavior(
                         is_default_behavior=True,
                         allowed_methods=cf.CloudFrontAllowedMethods.ALL,
                         cached_methods=cf.CloudFrontAllowedCachedMethods.
                         GET_HEAD,
                         compress=True,
                         forwarded_values=cf.CfnDistribution.
                         ForwardedValuesProperty(query_string=True, )),
                 ],
             )
         ])
     core.CfnOutput(
         self,
         'HttpEndpointDomain',
         value=f'http://{cloud_front.domain_name}',
         description=
         'CloudFront domain name that accepts requests both in HTTP and HTTPS protocols.',
         export_name='HTTP-Endpoint')
Example #10
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        # S3 bucket for website content
        websiteBucket = aws_s3.Bucket(
            self,
            "websiteBucket",
            public_read_access=True,
            website_index_document="index.html",
            access_control=aws_s3.BucketAccessControl.PUBLIC_READ)

        # S3 bucket for uploaded image and video content. This is setup to be used to upload content which is to be viewed by the
        # public. This can't be the same bucket as the website if you're using aws_s3_deployment as  aws_s3_deployment clears the
        # bucket out before deploying
        imagesBucket = aws_s3.Bucket(
            self,
            "imagesBucket",
            public_read_access=True,
            access_control=aws_s3.BucketAccessControl.PUBLIC_READ)
        # Used to enable uploading to the S3 bucket directly from client side code. Pretty unnecessary otherwise, unless you want to get
        # bucket listings from client side code
        imagesBucket.add_cors_rule(allowed_methods=[
            aws_s3.HttpMethods.GET, aws_s3.HttpMethods.PUT,
            aws_s3.HttpMethods.HEAD, aws_s3.HttpMethods.POST,
            aws_s3.HttpMethods.DELETE
        ],
                                   allowed_origins=["*"],
                                   allowed_headers=["*"],
                                   exposed_headers=["ETag"])

        # CloudFront distribution. Creates a combined front for the two buckets. The second bucket must have a folder called /media
        # (name can be changed) containing all the stuff you want distributed. The content will appear under /media in the
        # distribution. The one pitfall with this is that subfolders of the website bucket (e.g. /admin) don't redirect to their
        # index.html properly. So, if /admin contains a index.html, navigating to /admin would get a 404 but /admin/index.html works
        # fine
        distribution = aws_cloudfront.CloudFrontWebDistribution(
            self,
            "S3BucketDistribution",
            origin_configs=[
                aws_cloudfront.SourceConfiguration(
                    s3_origin_source=aws_cloudfront.S3OriginConfig(
                        s3_bucket_source=websiteBucket),
                    behaviors=[
                        aws_cloudfront.Behavior(is_default_behavior=True)
                    ]),
                aws_cloudfront.SourceConfiguration(
                    s3_origin_source=aws_cloudfront.S3OriginConfig(
                        s3_bucket_source=imagesBucket),
                    behaviors=[
                        aws_cloudfront.Behavior(path_pattern="/media/*")
                    ])
            ])

        # Code to automatically deploy the frontend code to the website bucket
        deployment = aws_s3_deployment.BucketDeployment(
            self,
            "deployStaticWebsite",
            sources=[aws_s3_deployment.Source.asset("PATH_TO_FRONTEND_CODE")],
            destination_bucket=websiteBucket,
            distribution=distribution)
Example #11
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        bucket = s3.Bucket(self, "Bucket", website_index_document="index.html")

        config = {"comment": "mythical-mysfits"}

        origin = cloudfront.CfnCloudFrontOriginAccessIdentity(
            self,
            "BucketOrigin",
            cloud_front_origin_access_identity_config=config)

        identity = iam.CanonicalUserPrincipal(
            canonical_user_id=origin.attr_s3_canonical_user_id)

        bucket.grant_read(identity)

        cloudfront_behaviour = cloudfront.Behavior(
            max_ttl=core.Duration.seconds(60),
            allowed_methods=cloudfront.CloudFrontAllowedMethods.
            GET_HEAD_OPTIONS,
            is_default_behavior=True)
        cloudfront_distribution = cloudfront.CloudFrontWebDistribution(
            self,
            "CloudFront",
            viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.ALLOW_ALL,
            price_class=cloudfront.PriceClass.PRICE_CLASS_ALL,
            origin_configs=[
                cloudfront.SourceConfiguration(
                    behaviors=[cloudfront_behaviour],
                    origin_path="/web",
                    s3_origin_source=cloudfront.S3OriginConfig(
                        s3_bucket_source=bucket,
                        origin_access_identity_id=origin.ref),
                )
            ],
        )

        contentDir = os.path.realpath("../web/")
        source = deployment.Source.asset(contentDir)
        deployment.BucketDeployment(
            self,
            "DeployWebsite",
            sources=[source],
            destination_key_prefix="web/",
            destination_bucket=bucket,
            distribution=cloudfront_distribution,
            retain_on_delete=False,
        )

        core.CfnOutput(
            self,
            "CloudFrontURL",
            description="The CloudFront distribution URL",
            value="http://{}".format(cloudfront_distribution.domain_name),
        )
Example #12
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        # Create an S3 Bucket):
        static_site_assets_bkt = _s3.Bucket(
            self,
            "assetsBucket",
            versioned=True,
            # public_read_access=True,
            # website_index_document="index.html",
            # website_error_document="404.html",
            removal_policy=core.RemovalPolicy.DESTROY)

        # Add assets to static site bucket
        add_assets_to_site = _s3_deployment.BucketDeployment(
            self,
            "deployStaticSiteAssets",
            sources=[
                _s3_deployment.Source.asset("advanced_use_cases/static_assets")
            ],
            destination_bucket=static_site_assets_bkt)

        # Create OAI for Cloudfront
        static_site_oai = _cloudfront.OriginAccessIdentity(
            self,
            "staticSiteOai",
            comment=f"OAI for static site from stack:{core.Aws.STACK_NAME}")

        # Deploy Cloudfront Configuration: Connecting OAI with static asset bucket
        cf_source_configuration = _cloudfront.SourceConfiguration(
            s3_origin_source=_cloudfront.S3OriginConfig(
                s3_bucket_source=static_site_assets_bkt,
                origin_access_identity=static_site_oai),
            behaviors=[
                _cloudfront.Behavior(
                    is_default_behavior=True,
                    compress=True,
                    allowed_methods=_cloudfront.CloudFrontAllowedMethods.ALL,
                    cached_methods=_cloudfront.CloudFrontAllowedCachedMethods.
                    GET_HEAD)
            ])

        # Create Cloudfront Distribution
        static_site_distribution = _cloudfront.CloudFrontWebDistribution(
            self,
            "staticSiteCfDistribution",
            comment="CDN for static website",
            origin_configs=[cf_source_configuration],
            price_class=_cloudfront.PriceClass.PRICE_CLASS_100)

        # Output Cloudfront Url
        output_1 = core.CfnOutput(
            self,
            "CloudfrontUrl",
            value=f"{static_site_distribution.domain_name}",
            description="The domain name of the static site")
Example #13
0
    def __init__(self, scope: core.Construct, id: str, s3bucket,acmcert, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        prj_name = self.node.try_get_context("project_name")
        env_name = self.node.try_get_context("env")

        bucketName = s3.Bucket.from_bucket_name(self,'s3bucket',s3bucket)

        self.cdn_id = cdn.CloudFrontWebDistribution(self,'webhosting-cdn',
            origin_configs=[cdn.SourceConfiguration(
                behaviors=[
                    cdn.Behavior(is_default_behavior=True)
                ],
                origin_path="/build",
                s3_origin_source=cdn.S3OriginConfig(
                    s3_bucket_source=bucketName,
                    origin_access_identity=cdn.OriginAccessIdentity(self,'webhosting-origin')
                )

            )],
            error_configurations=[cdn.CfnDistribution.CustomErrorResponseProperty(
                error_code=400,
                response_code=200,
                response_page_path="/"

            ),
                cdn.CfnDistribution.CustomErrorResponseProperty(
                    error_code=403,
                    response_code=200,
                    response_page_path="/"
                ),
                cdn.CfnDistribution.CustomErrorResponseProperty(
                    error_code=404,
                    response_code=200,
                    response_page_path="/"
                )
            ],
            alias_configuration=cdn.AliasConfiguration(
                acm_cert_ref=acmcert.certificate_arn,
                names=['app.cloudevangelist.ca']
            )
            
        )

        ssm.StringParameter(self,'cdn-dist-id',
            parameter_name='/'+env_name+'/app-distribution-id',
            string_value=self.cdn_id.distribution_id
        )

        ssm.StringParameter(self,'cdn-url',
            parameter_name='/'+env_name+'/app-cdn-url',
            string_value='https://'+self.cdn_id.domain_name
        )
Example #14
0
    def __init__(self, scope: core.Construct, id: str, hostedzoneid: str, hostedzonename: str, origin_name: str, **kwargs) -> None:

        super().__init__(scope, id, **kwargs)

        domain_name = "{}.{}".format("test",hostedzonename)

        hostedzone = dns.HostedZone.from_hosted_zone_attributes(
            self,
            "hosted_zone",
            hosted_zone_id=hostedzoneid,
            zone_name=hostedzonename
        )

        acm_certificate = acm.DnsValidatedCertificate(
            self, 
            "ACMCertGenerator",
            hosted_zone=hostedzone , 
            region="us-east-1", 
            domain_name="test.awsels.com" , 
            validation_method =  acm.ValidationMethod.DNS
        )

        source_configuration = cloudfront.SourceConfiguration(
            custom_origin_source=cloudfront.CustomOriginConfig(
                domain_name=origin_name,
                allowed_origin_ssl_versions=[cloudfront.OriginSslPolicy.TLS_V1_2],
                http_port=80,
                https_port=443,
                origin_protocol_policy=cloudfront.OriginProtocolPolicy.HTTPS_ONLY
            ),
            behaviors=[cloudfront.Behavior(
                compress=False,
                allowed_methods=cloudfront.CloudFrontAllowedMethods.ALL,
                is_default_behavior=True,
                cached_methods=cloudfront.CloudFrontAllowedCachedMethods.GET_HEAD
            )]
        )

        viewer_configuration = cloudfront.ViewerCertificate.from_acm_certificate(
                certificate=acm.Certificate.from_certificate_arn(self, "certificate", certificate_arn=acm_certificate.certificate_arn),
                aliases=[origin_name],
                security_policy=cloudfront.SecurityPolicyProtocol.TLS_V1,
                ssl_method=cloudfront.SSLMethod.SNI
        )


        distribution = cloudfront.CloudFrontWebDistribution(
            self,
            'Distribution',
            origin_configs=[source_configuration],
            viewer_certificate=viewer_configuration,
            price_class=cloudfront.PriceClass.PRICE_CLASS_100,
        )
Example #15
0
    def __init__(self, scope: core.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        #s3 bucket
        static_bucket = aws_s3.Bucket(
            self,
            "StaticBucket",
            versioned=True,
            removal_policy=core.RemovalPolicy.DESTROY)

        #import html files
        add_assets = aws_s3_deployment.BucketDeployment(
            self,
            "AssetsDeploy",
            sources=[aws_s3_deployment.Source.asset("deployments/assets")],
            destination_bucket=static_bucket)

        #add cloudfront origin access identity
        cloudfront_assets = aws_cloudfront.OriginAccessIdentity(
            self,
            "CloudfrontAssets",
            comment=f"CloudFront Assets for:{core.Aws.STACK_NAME}")

        #cloudfront configuration
        cloudfront_config = aws_cloudfront.SourceConfiguration(
            s3_origin_source=aws_cloudfront.S3OriginConfig(
                s3_bucket_source=static_bucket,
                origin_access_identity=cloudfront_assets),
            behaviors=[
                aws_cloudfront.Behavior(
                    is_default_behavior=True,
                    compress=True,
                    allowed_methods=aws_cloudfront.CloudFrontAllowedMethods.
                    ALL,
                    cached_methods=aws_cloudfront.
                    CloudFrontAllowedCachedMethods.GET_HEAD)
            ])

        #cloudfront distribution
        cloudfront_distribution = aws_cloudfront.CloudFrontWebDistribution(
            self,
            "CloudfrontDistribution",
            comment="CDN for static web",
            origin_configs=[cloudfront_config],
            price_class=aws_cloudfront.PriceClass.PRICE_CLASS_100)

        #cloudfront url
        cloudfront_output = core.CfnOutput(
            self,
            "cloudfrontURL",
            value=f"{cloudfront_distribution.domain_name}",
            description="Static web page url")
Example #16
0
    def __init__(self, scope: cdk.Construct, construct_id: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        web_app_root = os.path.abspath('./web')

        bucket = _s3.Bucket(self,
                            'Bucket',
                            website_index_document='index.html')

        origin = cloudfront.OriginAccessIdentity(self,
                                                 'BucketOrigin',
                                                 comment='mythical-mysfits')

        bucket.grant_read(
            _iam.CanonicalUserPrincipal(
                origin.cloud_front_origin_access_identity_s3_canonical_user_id)
        )

        cdn = cloudfront.CloudFrontWebDistribution(
            self,
            'CloudFront',
            viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.ALLOW_ALL,
            price_class=cloudfront.PriceClass.PRICE_CLASS_ALL,
            origin_configs=[
                cloudfront.SourceConfiguration(
                    behaviors=[
                        cloudfront.Behavior(
                            is_default_behavior=True,
                            max_ttl=cdk.Duration.seconds(31536000),
                            allowed_methods=cloudfront.
                            CloudFrontAllowedMethods.GET_HEAD_OPTIONS)
                    ],
                    origin_path='/web',
                    s3_origin_source=cloudfront.S3OriginConfig(
                        s3_bucket_source=bucket,
                        origin_access_identity=origin))
            ])

        s3deploy.BucketDeployment(
            self,
            'DeployWebsite',
            sources=[s3deploy.Source.asset(web_app_root)],
            destination_key_prefix='web/',
            destination_bucket=bucket,
            distribution=cdn,
            retain_on_delete=False)

        cdk.CfnOutput(self,
                      'CloudFrontURL',
                      description='The CloudFront distribution URL',
                      value='https://' + cdn.domain_name)
    def __init__(self, scope: core.Construct, id: str, domain: DomainInfo,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)
        if domain.stage == 'prod':
            self.final_domain = domain.domain_name
        else:
            self.final_domain = f'{domain.stage}.{domain.domain_name}'
        self.domain = domain

        # Create the static site website bucket
        bucket = s3.Bucket(self,
                           "sitebucket",
                           bucket_name=self.final_domain,
                           public_read_access=True,
                           website_index_document="index.html")
        core.CfnOutput(self, 'site_bucket_name', value=bucket.bucket_name)
        core.CfnOutput(self,
                       'site_bucket_website',
                       value=bucket.bucket_website_url)

        #create Cloudfront distribution return dist ID
        alias_configuration = cf.AliasConfiguration(
            acm_cert_ref=self.domain.cert_arn,
            names=[self.final_domain],
        )
        source_configuration = cf.SourceConfiguration(
            s3_origin_source=cf.S3OriginConfig(s3_bucket_source=bucket, ),
            behaviors=[cf.Behavior(is_default_behavior=True)])
        dist = cf.CloudFrontWebDistribution(
            self,
            'staticsitecf',
            alias_configuration=alias_configuration,
            origin_configs=[source_configuration],
        )
        core.CfnOutput(self,
                       'static_site_cf_dist_id',
                       value=dist.distribution_id)
        core.CfnOutput(self, 'static_site_cf_domain', value=dist.domain_name)

        #route53 logic
        if self.domain.stage == 'prod':
            zone = route53.HostedZone.from_hosted_zone_attributes(
                self,
                id="HostedZoneID",
                hosted_zone_id=self.domain.hosted_zone_id,
                zone_name=self.domain.domain_name)
            route53.ARecord(self,
                            'SiteAliasRecord',
                            record_name=self.final_domain,
                            target=route53.AddressRecordTarget.from_alias(
                                targets.CloudFrontTarget(dist)),
                            zone=zone)
Example #18
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        static_bucket = aws_s3.Bucket(
            self,
            'MiscPublicFilesBucket',
            removal_policy=core.RemovalPolicy.RETAIN,
        )

        origin = aws_cloudfront.OriginAccessIdentity(
            self,
            'MiscPublicFilesOrigin',
            comment='CDN origin for miscellaneous public files',
        )

        cdn = aws_cloudfront.CloudFrontWebDistribution(
            self,
            'MiscPublicFilesCDN',
            comment='CDN for miscellaneous public files',
            origin_configs=[
                aws_cloudfront.SourceConfiguration(
                    s3_origin_source=aws_cloudfront.S3OriginConfig(
                        s3_bucket_source=static_bucket,
                        origin_access_identity=origin,
                    ),
                    behaviors=[
                        aws_cloudfront.Behavior(
                            is_default_behavior=True,
                            min_ttl=core.Duration.days(90),
                            max_ttl=core.Duration.days(360),
                            default_ttl=core.Duration.days(180),
                            compress=True,
                        )
                    ],
                )
            ],
            default_root_object='index.html',
            enable_ip_v6=True,
            http_version=aws_cloudfront.HttpVersion.HTTP2,
            price_class=aws_cloudfront.PriceClass.PRICE_CLASS_100,
            viewer_protocol_policy=aws_cloudfront.ViewerProtocolPolicy.
            REDIRECT_TO_HTTPS,  # NOQA
        )

        aws_s3_deployment.BucketDeployment(
            self,
            'MiscPublicFilesDeployment',
            sources=[aws_s3_deployment.Source.asset('public')],
            destination_bucket=static_bucket,
            distribution=cdn,
        )
Example #19
0
    def __init__(self, parent: core.Construct, name: str,
                 props: StaticSiteProps) -> None:
        super().__init__(parent, name)

        site_domain = props.site_sub_domain + '.' + props.domain_name

        # Content bucket
        site_bucket = s3.Bucket(self,
                                "SiteBucket",
                                bucket_name=site_domain,
                                website_index_document="index.html",
                                website_error_document="error.html",
                                public_read_access=True,
                                removal_policy=core.RemovalPolicy.DESTROY)

        core.CfnOutput(self, 'Bucket', value=site_bucket.bucket_name)

        #cloudfront distribution that provies HTTPS
        distribution = cfront.CloudFrontWebDistribution(
            self,
            'SiteDistribution',
            origin_configs=[
                cfront.SourceConfiguration(
                    behaviors=[cfront.Behavior(is_default_behavior=True)],
                    s3_origin_source=cfront.S3OriginConfig(
                        s3_bucket_source=site_bucket))
            ],
            alias_configuration=cfront.AliasConfiguration(
                acm_cert_ref=props.certificate_arn,
                names=[site_domain],
                ssl_method=cfront.SSLMethod.SNI,
                security_policy=cfront.SecurityPolicyProtocol.TLS_V1_1_2016))

        core.CfnOutput(self,
                       'DistributionID',
                       value=distribution.distribution_id)

        # Route 53 alias record for the CloudFront distribution
        zone = route53.HostedZone.from_lookup(self,
                                              'MyHostedZone',
                                              domain_name=props.domain_name)

        # Add a A record to the hosted zone
        route53.ARecord(
            self,
            'SiteAliasRecord',
            zone=zone,
            record_name=site_domain,
            target=route53.AddressRecordTarget.from_alias(
                aws_route53_targets.CloudFrontTarget(distribution)))
    def __init__(self, app: core.App, id: str, **kwargs) -> None:
        super().__init__(app, id)
        #create an S3 bucket
        domainName = 'accelerate.dev'
        myBucket = s3.Bucket(self,
                             'accelerate.dev-s3bucket',
                             bucket_name='accelerate-website',
                             public_read_access=True,
                             website_index_document='index.html',
                             website_error_document='404.html',
                             removal_policy=core.RemovalPolicy.DESTROY)
        myBucket.grant_public_access
        myBucket.add_to_resource_policy(  #Grant read access to everyone in your account
            iam.PolicyStatement(
                actions=['s3:GetObject'],
                resources=[myBucket.arn_for_objects('*')],
                principals=[
                    iam.AccountPrincipal(account_id=core.Aws.ACCOUNT_ID)
                ]))
        myUser = iam.User(self, 'deploy_' +
                          domainName)  #Grant write access to a specific user
        myBucket.grant_write(myUser)
        hostedZone = route53.HostedZone.from_hosted_zone_attributes(
            self,
            "HostedZone_" + domainName,
            hosted_zone_id='Z00154093I7THXRTRF8QB',
            zone_name=domainName)
        cert = certmgr.DnsValidatedCertificate(self,
                                               "cert_" + domainName,
                                               domain_name=domainName,
                                               hosted_zone=hostedZone)
        distribution = cloudfront.CloudFrontWebDistribution(
            self,
            "accelerate.dev-distribution",
            price_class=cloudfront.PriceClass.PRICE_CLASS_100,
            origin_configs=[
                cloudfront.SourceConfiguration(
                    s3_origin_source=cloudfront.S3OriginConfig(
                        s3_bucket_source=myBucket),
                    behaviors=[cloudfront.Behavior(is_default_behavior=True)])
            ],
            viewer_certificate=cloudfront.ViewerCertificate.
            from_acm_certificate(cert, aliases=['accelerate.dev']))

        route53.ARecord(self,
                        "Alias_" + domainName,
                        zone=hostedZone,
                        target=route53.RecordTarget.from_alias(
                            targets.CloudFrontTarget(distribution)))
Example #21
0
    def __init__(self, scope: core.Construct, id: str, vpc, alb,
                 **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        self.website_bucket = _s3.Bucket(
            self,
            "websiteBucket",
            website_index_document="index.html",
            website_error_document="error.html",
            removal_policy=core.RemovalPolicy.DESTROY)

        self.static_bucket = _s3.Bucket(
            self, "staticBucket", removal_policy=core.RemovalPolicy.DESTROY)

        # Website
        web_behavior = _cf.Behavior(is_default_behavior=True,
                                    default_ttl=core.Duration.minutes(0))
        web_source_config = _cf.SourceConfiguration(
            behaviors=[web_behavior],
            s3_origin_source=_cf.S3OriginConfig(
                s3_bucket_source=self.website_bucket))

        # Static Content
        static_behavior = _cf.Behavior(path_pattern="images/*",
                                       default_ttl=core.Duration.minutes(0))
        static_source_config = _cf.SourceConfiguration(
            behaviors=[static_behavior],
            s3_origin_source=_cf.S3OriginConfig(
                s3_bucket_source=self.static_bucket))

        # ALB
        alb_behavior = _cf.Behavior(
            path_pattern="api/*",
            allowed_methods=_cf.CloudFrontAllowedMethods.ALL,
            default_ttl=core.Duration.minutes(0))
        alb_source_config = _cf.SourceConfiguration(
            behaviors=[alb_behavior],
            custom_origin_source=_cf.CustomOriginConfig(
                domain_name=alb.load_balancer_dns_name,
                origin_protocol_policy=_cf.OriginProtocolPolicy.HTTP_ONLY))

        self.cf = _cf.CloudFrontWebDistribution(
            self,
            "cfDistribution",
            price_class=_cf.PriceClass.PRICE_CLASS_100,
            origin_configs=[
                web_source_config, static_source_config, alb_source_config
            ])
Example #22
0
    def __init__(self, scope:core.Construct, id:str, s3bucket, **kwargs):
        super().__init__(scope, id, **kwargs)

        prj_name = self.node.try_get_context('project_name')
        env_name = self.node.try_get_context('env')

        bucketName = s3.Bucket.from_bucket_name(self, 's3bucket', s3bucket)

        cdn_id = cdn.CloudFrontWebDistribution(
            self,
            'webhosting-cdn',
            origin_configs=[
                cdn.SourceConfiguration(
                    behaviors=[cdn.Behavior(is_default_behavior=True)],
                    origin_path='/build',
                    s3_origin_source=cdn.S3OriginConfig(
                        s3_bucket_source=bucketName,
                        origin_access_identity=cdn.OriginAccessIdentity(self, 'webhosting-origin')
                    )

                )
            ],
            error_configurations=[
                cdn.CfnDistribution.CustomErrorResponseProperty(
                    error_code=400,
                    response_code=200,
                    response_page_path='/'
                ),
                cdn.CfnDistribution.CustomErrorResponseProperty(
                    error_code=403,
                    response_code=200,
                    response_page_path='/'
                ),
                cdn.CfnDistribution.CustomErrorResponseProperty(
                    error_code=404,
                    response_code=200,
                    response_page_path='/'
                )
            ],
        )

        ## ssm params
        ssm.StringParameter(self, 'cdn-id',
                            parameter_name=f'/{env_name}/cdn-id',
                            string_value=cdn_id.distribution_id)
        ssm.StringParameter(self, 'cdn-url',
                            parameter_name=f'/{env_name}/cdn-url',
                            string_value=f'https://{cdn_id.distribution_domain_name}')
    def create_cloudfront_distribution(self,
                                       cloudfront_alias=typing.Optional[dict]):
        r"""Creates the Cloudfront distribution required to access the SPA website

    The Cloudfront distribution will automatically forward requests to the s3 bucket /index.html
    file and serve that as the default for all HTTP URIs that don't exist so that the index file
    can be served for any dynamic path

    NOTE: If cloudfront_alias is defined, the default `security_policy` is
      aws_cloudfront.SecurityPolicyProtocol.TLS_V1_2_2018 which can be by defining `security_policy`
      in the dictionary if required

    Args:
      cloudfront_alias: Aliases your Cloudfront distribution should use and should
        include a dictionary containing array(`names`) and str(`acm_cert_ref`)
    """
        cloudfront_originaccesspolicy = cloudfront.OriginAccessIdentity(
            self,
            f"{self.__website_identifier}-originpolicy",
        )
        alias_configuration = None
        if cloudfront_alias is not None:
            if 'security_policy' not in cloudfront_alias:
                cloudfront_alias[
                    'security_policy'] = cloudfront.SecurityPolicyProtocol.TLS_V1_2_2018
            cloudfront_alias = cloudfront.AliasConfiguration(
                **cloudfront_alias)
        self.cloudfront_distro = cloudfront.CloudFrontWebDistribution(
            self,
            id=f"{self.__website_identifier}-cloudfront",
            price_class=cloudfront.PriceClass.PRICE_CLASS_ALL,
            alias_configuration=alias_configuration,
            origin_configs=[
                cloudfront.SourceConfiguration(
                    behaviors=[cloudfront.Behavior(is_default_behavior=True)],
                    s3_origin_source=cloudfront.S3OriginConfig(
                        s3_bucket_source=self.website_assets_bucket,
                        origin_access_identity=cloudfront_originaccesspolicy))
            ],
            error_configurations=[
                cloudfront.CfnDistribution.CustomErrorResponseProperty(
                    error_code=404,
                    error_caching_min_ttl=0,
                    response_code=200,
                    response_page_path="/index.html")
            ])
    def __init__(
        self,
        scope: core.Construct,
        id: str,
        generate_exports_and_bundle: Callable[[], None],
        **kwargs,
    ) -> None:
        super().__init__(scope, id, **kwargs)

        # generate exports file and bundle application
        generate_exports_and_bundle()

        # deploy application to s3 bucket behind cloudfront
        bucket = s3.Bucket(
            self,
            "ReactAppBucket",
            website_index_document="index.html",
            website_error_document="404.html",
        )

        s3_dep.BucketDeployment(
            self,
            "DeployNextJSReactApp",
            sources=[s3_dep.Source.asset(path.join("client", "out"))],
            destination_bucket=bucket,
        )

        oai = cloudfront.OriginAccessIdentity(self, "OAI")
        cfd = cloudfront.CloudFrontWebDistribution(
            self,
            "ReactAppDistribution",
            origin_configs=[{
                "s3OriginSource": {
                    "s3BucketSource": bucket,
                    "originAccessIdentity": oai,
                },
                "behaviors": [cloudfront.Behavior(is_default_behavior=True)],
            }],
        )

        # only allows cloudfront distribution to read from bucket
        bucket.grant_read(oai.grant_principal)

        core.CfnOutput(self,
                       id="appurl",
                       value=f"https://{cfd.distribution_domain_name}")
Example #25
0
    def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        prj_name = self.node.try_get_context("project_name")
        env_name = self.node.try_get_context("env")

        media_distribution_oai = cloudfront.OriginAccessIdentity(
            self, 'media-distribution-oai')
        media_distribution_oai.apply_removal_policy(core.RemovalPolicy.DESTROY)

        frontend_bucket = s3.Bucket(
            self,
            'frontend-bucket',
            access_control=s3.BucketAccessControl.BUCKET_OWNER_FULL_CONTROL,
            encryption=s3.BucketEncryption.S3_MANAGED,
            bucket_name=prj_name + env_name + '-bucket',
            website_index_document='index.html',
            website_error_document='index.html',
            block_public_access=s3.BlockPublicAccess(
                block_public_acls=True,
                block_public_policy=True,
                ignore_public_acls=True,
                restrict_public_buckets=True),
            removal_policy=core.RemovalPolicy.DESTROY)

        media_assets = s3_deployment.BucketDeployment(
            self,
            'media-assets',
            sources=[s3_deployment.Source.asset('./assets')],
            destination_bucket=frontend_bucket)

        media_distribution = cloudfront.CloudFrontWebDistribution(
            self,
            'media-distribution',
            origin_configs=[
                cloudfront.SourceConfiguration(
                    behaviors=[cloudfront.Behavior(is_default_behavior=True)],
                    s3_origin_source=cloudfront.S3OriginConfig(
                        s3_bucket_source=frontend_bucket,
                        origin_access_identity=cloudfront.OriginAccessIdentity(
                            self, 'frontend-origin')))
            ],
            #Edege server location https://docs.aws.amazon.com/cdk/api/latest/python/aws_cdk.aws_cloudfront/PriceClass.html#aws_cdk.aws_cloudfront.PriceClass
            price_class=cloudfront.PriceClass.PRICE_CLASS_ALL)
        media_distribution.apply_removal_policy(core.RemovalPolicy.DESTROY)
Example #26
0
 def create_redirect_distribution(self):
     return cloudfront.CloudFrontWebDistribution(
         self, 
         self.config.get("stack_name") + "_cloudfront_redirect",
         origin_configs=[
             cloudfront.SourceConfiguration(
                 custom_origin_source=self.create_redirect_oai_config(),
                 behaviors=[
                     cloudfront.Behavior(is_default_behavior=True)
                 ]
             )
         ],
         viewer_certificate=cloudfront.ViewerCertificate.from_acm_certificate(
             self.certificate,
             aliases=[self.domain],
             security_policy=cloudfront.SecurityPolicyProtocol.TLS_V1_2_2018,
             ssl_method=cloudfront.SSLMethod.SNI
         ),
         price_class=self.get_pricing_class()
     )
Example #27
0
    def __init__(self, scope: core.Construct, id: str, **kwargs):
        super().__init__(scope, id, **kwargs)

        self.www_site_bucket = s3.Bucket.from_bucket_name(
            self, 'SiteBucket', core.Fn.import_value("WWWSITEBUCKETNAME"))

        www_source_configuration = cloudfront.SourceConfiguration(
            s3_origin_source=cloudfront.S3OriginConfig(
                s3_bucket_source=self.www_site_bucket),
            behaviors=[cloudfront.Behavior(is_default_behavior=True)])

        www_distribution = cloudfront.CloudFrontWebDistribution(
            self,
            'SiteDistribution',
            origin_configs=[www_source_configuration])

        self.rest_api = aws_apigateway.RestApi(self,
                                               'RestApiGateway',
                                               deploy=False)
        api_domain_name = f'api.{startuptoolbag_config.website_domain_name}'
Example #28
0
    def __init__(self, scope: core.Construct, id: str, aliases: List[str],
                 certificate_arn: str, **kwargs) -> None:
        super().__init__(scope, id, **kwargs)

        bucket = s3.Bucket(self, 'Storage')

        origin_identity = cloudfront.OriginAccessIdentity(self, 'Identity')

        bucket.grant_read(origin_identity.grant_principal)

        certificate = acm.Certificate.from_certificate_arn(
            self, 'Certificate', certificate_arn=certificate_arn)

        distribution = cloudfront.CloudFrontWebDistribution(
            self,
            'CDN',
            price_class=cloudfront.PriceClass.PRICE_CLASS_ALL,
            alias_configuration=cloudfront.AliasConfiguration(
                names=aliases,
                acm_cert_ref=certificate.certificate_arn,
                security_policy=cloudfront.SecurityPolicyProtocol.
                TLS_V1_2_2019,
            ),
            origin_configs=[
                cloudfront.SourceConfiguration(
                    s3_origin_source=cloudfront.S3OriginConfig(
                        s3_bucket_source=bucket,
                        origin_access_identity=origin_identity,
                    ),
                    behaviors=[
                        cloudfront.Behavior(
                            default_ttl=core.Duration.days(1),
                            min_ttl=core.Duration.days(1),
                            max_ttl=core.Duration.days(365),
                            is_default_behavior=True,
                        )
                    ])
            ])

        self.bucket = bucket
        self.distribution = distribution
    def __init__(self, scope: Construct, construct_id: str, stage: str,
                 **kwargs) -> None:
        super().__init__(scope, construct_id)

        _access_logs_bucket = self.get_access_logs_bucket(stage)
        _staticsite_bucket = self.create_bucket(_access_logs_bucket, stage)
        _cfront_oai = self.create_origin_access_identity()
        _policy_statement = self.create_s3_cfront_policy(
            _staticsite_bucket, _cfront_oai)
        _staticsite_bucket.add_to_resource_policy(_policy_statement)

        _cfront_dist = _cfront.CloudFrontWebDistribution(
            self,
            "staticsitedistribution",
            http_version=_cfront.HttpVersion.HTTP2,
            origin_configs=[
                _cfront.SourceConfiguration(
                    behaviors=[
                        _cfront.Behavior(
                            allowed_methods=_cfront.CloudFrontAllowedMethods.
                            GET_HEAD_OPTIONS,
                            is_default_behavior=True)
                    ],
                    s3_origin_source=_cfront.S3OriginConfig(
                        s3_bucket_source=_staticsite_bucket),
                )
            ],
            default_root_object="index.html",
            viewer_protocol_policy=_cfront.ViewerProtocolPolicy.
            REDIRECT_TO_HTTPS,
            price_class=_cfront.PriceClass.PRICE_CLASS_ALL,
            enable_ip_v6=False,
        )

        self.bucket = _staticsite_bucket
        self.access_logs_bucket = _access_logs_bucket
        self.cfront_dist = _cfront_dist

        self.sourcebucketname = CfnOutput(self,
                                          "sourceBucketName",
                                          value=_staticsite_bucket.bucket_name)
Example #30
0
def add_static_site(stack: CDKMasterStack, domain: str, bucket_name: str, prefix: str = ""):

    # Construct code goes here
    core.CfnOutput(stack, f"{prefix}Site", value=f"https://{domain}")

    # Content bucket
    kix.info("Bucket Name: " + bucket_name)
    site_bucket = aws_s3.Bucket(
        stack, f"{prefix}SiteBucket",
        bucket_name=bucket_name,
        website_index_document="index.html",
        website_error_document="index.html",
        public_read_access=True,
        removal_policy=core.RemovalPolicy.DESTROY)
    core.CfnOutput(stack, f"{prefix}BucketArn", value=site_bucket.bucket_arn)

    # Certificate
    kix.info("Creating Certificate")
    cert = aws_certificatemanager.DnsValidatedCertificate(
        stack, f"{prefix}ValidatedCert",
        domain_name=domain,
        hosted_zone=stack.zone)
    core.CfnOutput(stack, f"{prefix}CertificateArn", value=cert.certificate_arn)

    kix.info("Creating Distribution")
    distribution = aws_cloudfront.CloudFrontWebDistribution(
        stack, f"{prefix}SiteDistribution",
        alias_configuration=aws_cloudfront.AliasConfiguration(
            acm_cert_ref=cert.certificate_arn,
            names=[domain],
            ssl_method=aws_cloudfront.SSLMethod.SNI,
            security_policy=aws_cloudfront.SecurityPolicyProtocol.TLS_V1_1_2016,
        ),
        origin_configs=[
            aws_cloudfront.SourceConfiguration(
                s3_origin_source=aws_cloudfront.S3OriginConfig(s3_bucket_source=site_bucket),
                behaviors=[aws_cloudfront.Behavior(is_default_behavior=True)]
            )],
        error_configurations=[
            aws_cloudfront.CfnDistribution.CustomErrorResponseProperty(
                error_code=403,
                response_code=200,
                response_page_path="/index.html"
            ),
            aws_cloudfront.CfnDistribution.CustomErrorResponseProperty(
                error_code=404,
                response_code=200,
                response_page_path="/index.html"
            )
        ]
    )
    core.CfnOutput(stack, f"{prefix}DistributionId", value=distribution.distribution_id)
    a_record_target = aws_route53.AddressRecordTarget.from_alias(aws_route53_targets.CloudFrontTarget(distribution))

    # Route 53 alias record for the CloudFront distribution
    kix.info("Routing A-Record Alias")
    aws_route53.ARecord(
        stack, f"{prefix}SiteAliasRecord",
        zone=stack.zone,
        target=a_record_target,
        record_name=domain)