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)
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 ])
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)
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'), ], )
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))
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 __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])
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')
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")
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), )
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 )
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")
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)
def create_asset_oai_config(self): """ Create OAI policy for S3/CloudFront Means bucket does not need to be public """ s3_oai = cloudfront.OriginAccessIdentity( self, self.config.get("stack_name") + "_OAI" ) return cloudfront.S3OriginConfig( s3_bucket_source=self.bucket_assets, origin_access_identity=s3_oai )
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, )
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)))
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, **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)
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}'
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)
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)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) website_bucket = s3.Bucket( self, 'FrontendBucket', versioned=True, website_index_document='index.html', website_error_document='index.html', public_read_access=True, ) distribution = cloudfront.CloudFrontWebDistribution( self, 'Distribution', alias_configuration=cloudfront.AliasConfiguration( acm_cert_ref=self.CERTIFICATE_ARN, names=[self.DOMAIN_NAME], ), origin_configs=[ cloudfront.SourceConfiguration( s3_origin_source=cloudfront.S3OriginConfig( s3_bucket_source=website_bucket), behaviors=[ cloudfront.Behavior(is_default_behavior=True, compress=True) ], ) ], error_configurations=[ cloudfront.CfnDistribution.CustomErrorResponseProperty( error_code=403, error_caching_min_ttl=300, response_code=200, response_page_path='/index.html', ), cloudfront.CfnDistribution.CustomErrorResponseProperty( error_code=404, error_caching_min_ttl=300, response_code=200, response_page_path='/index.html', ), ], ) s3deploy.BucketDeployment( self, 'DeployWithInvalidation', sources=[s3deploy.Source.asset('../frontend/dist/')], destination_bucket=website_bucket, distribution=distribution, distribution_paths=['/*'], ) # Django staticfiles s3.Bucket( self, 'StaticAssetsBucket', public_read_access=True, ) # non-www to www redirection redirect_bucket = s3.Bucket( self, 'RedirectedBucket', bucket_name=self.ROOT_DOMAIN_NAME, website_redirect={ 'host_name': 'https://www.{{cookiecutter.domain_name}}' }, public_read_access=True, ) cloudfront.CloudFrontWebDistribution( self, 'RedirectDistribution', alias_configuration=cloudfront.AliasConfiguration( acm_cert_ref=self.CERTIFICATE_ARN, names=[self.ROOT_DOMAIN_NAME], ), origin_configs=[ cloudfront.SourceConfiguration( s3_origin_source=cloudfront.S3OriginConfig( s3_bucket_source=redirect_bucket), behaviors=[cloudfront.Behavior(is_default_behavior=True)], ) ], )
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Define S3 bucket that will host site assets website_bucket = s3.Bucket( self, 'parthrparikh-com-assets-bucket', website_index_document='index.html', block_public_access=s3.BlockPublicAccess.BLOCK_ALL, ) # Deny non-SSL traffic website_bucket.add_to_resource_policy( iam.PolicyStatement( effect=iam.Effect.DENY, actions=["s3:*"], resources=[website_bucket.bucket_arn], conditions={'Bool': { 'aws:SecureTransport': False, }}, principals=[iam.AnyPrincipal()], )) s3_deploy.BucketDeployment( self, 'parthrparikh-com-deploy-website', sources=[s3_deploy.Source.asset('../website/')], destination_bucket=website_bucket, ) # Define certificate for parthrparikh.com cert = acm.Certificate(self, 'parthrparikh-com-cert', domain_name='parthrparikh.com', subject_alternative_names=[ 'www.parthrparikh.com', ]) # Define CloudFront distribution origin_access_identity = cf.OriginAccessIdentity( self, 'OriginAccessIdentity', comment='Personal website (parthrparikh.com) OAI to reach bucket', ) website_bucket.grant_read(origin_access_identity) distro = cf.CloudFrontWebDistribution( self, 'parthrparikh-com-distribution', origin_configs=[ cf.SourceConfiguration( s3_origin_source=cf.S3OriginConfig( s3_bucket_source=website_bucket, origin_access_identity=origin_access_identity), behaviors=[ cf.Behavior( is_default_behavior=True, default_ttl=core.Duration.minutes(10), max_ttl=core.Duration.hours(1), ) ], ), ], viewer_certificate=cf.ViewerCertificate.from_acm_certificate( certificate=cert, aliases=[ 'parthrparikh.com', 'www.parthrparikh.com', ]), viewer_protocol_policy=cf.ViewerProtocolPolicy.REDIRECT_TO_HTTPS, )
class TsWwwStack(core.Stack): def __init__(self, scope: core.Construct, id: str,domain_name:str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # Materialize existing AWS Hosted DNS Zone dns_zone = r53_.HostedZone.from_lookup(self,"dns_zone",domain_name = domain_name) # Compose site name for AWS Certificate site_fqdn = "www." + dns_zone.zone_name # Create a DNS Certificate certificate = cm_.DnsValidatedCertificate (self,"certificate", domain_name=site_fqdn, hosted_zone=dns_zone, region="us-east-1") # Define Bucket to store Site Contents ts_www_bucket = s3_.Bucket(self,"truesys-static-website", bucket_name = site_fqdn, website_index_document = "index.html", website_error_document = "404/index.html", public_read_access = True ) #Cria lambda function para fazr URL Rewriting de default document url_rewrite_lambda = _lambda.Function(self,'URLRewriteLambdaEdge', handler='url_rewrite_handler.handler', runtime=_lambda.Runtime.PYTHON_3_7, code=_lambda.Code.asset('lambda_edge'), ) // A numbered version to give to cloudfront const myOriginRequestHandlerVersion = new lambda.Version(this, "OriginRequestHandlerVersion", { lambda: myOriginRequestHandler, }); lea = clf_.AlambdaFunctionAssociation(event_type = cfl_AlambdaEdgeEventType.ORIGIN_REQUEST, myOriginRequestHandlerVersion) #Define Cloud Front distribution s3_origin_config = clf_.S3OriginConfig(s3_bucket_source = ts_www_bucket) behaviour = clf_.Behavior(is_default_behavior=True, lambda_function_associations = [lea]) source_config = clf_.SourceConfiguration(s3_origin_source=s3_origin_config, behaviors = [behaviour]) clf_alias_config = clf_.AliasConfiguration(acm_cert_ref = certificate.certificate_arn, names=[site_fqdn], ssl_method = clf_.SSLMethod.SNI, security_policy = clf_.SecurityPolicyProtocol.TLS_V1_1_2016) cf_distribution = clf_.CloudFrontWebDistribution(self,"TsDistribution", origin_configs=[source_config], alias_configuration=clf_alias_config, price_class = clf_.PriceClass.PRICE_CLASS_ALL ) #Define Route 53 Alias aka endereco do site cloud_front_target = r53tgs_.CloudFrontTarget(distribution = cf_distribution) r53_target = r53_.RecordTarget.from_alias(alias_target = cloud_front_target) r53_.ARecord(self,"EnderecoDosite",record_name = site_fqdn, target = r53_target, zone = dns_zone) #Faz deploy do conteudo do site para o S3 e invalida distribution site_assets = s3deploy_.Source.asset("./true-systems-static-site/public") s3deploy_.BucketDeployment(self,"truesys-website-content-deployment", sources = [site_assets], destination_bucket=ts_www_bucket, distribution=cf_distribution, distribution_paths = [ "/*"]) core.CfnOutput(self,"Site",value = site_fqdn)
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None: super().__init__(scope, id, **kwargs) # region IAM sa_role = aws_iam.Role( self, "Role", role_name="SaRole", assumed_by=aws_iam.ServicePrincipal("lambda.amazonaws.com")) sa_role.add_to_policy( aws_iam.PolicyStatement(effect=aws_iam.Effect.ALLOW, resources=["*"], actions=[ "cloudwatch:*", "s3:*", "logs:*", "dynamodb:*", "iam:*" ])) # endregion IAM # region S3 mask_images_bucket = aws_s3.Bucket(self, 'MaskImagesBucket') # endregion S3 # region DB masks_db = aws_dynamodb.Table( self, 'MasksTable', table_name='Masks', partition_key=aws_dynamodb.Attribute( name='id', type=aws_dynamodb.AttributeType.STRING), sort_key=aws_dynamodb.Attribute( name='mask_name', type=aws_dynamodb.AttributeType.STRING), removal_policy=core.RemovalPolicy.DESTROY) # endregion DB # region Lambda fetch_lambda = _lambda.Function( self, 'DynamoFetch', runtime=_lambda.Runtime.PYTHON_3_8, code=_lambda.Code.asset('lambda'), handler='dynamo_fetch.handler', environment=dict(DYNAMO_TABLE_NAME=masks_db.table_name), role=sa_role) insert_lambda = _lambda.Function( self, 'DynamoInsert', runtime=_lambda.Runtime.PYTHON_3_8, code=_lambda.Code.asset('lambda'), handler='dynamo_insert.handler', environment=dict(DYNAMO_TABLE_NAME=masks_db.table_name), role=sa_role) # endregion # region API base_api = aws_apigateway.LambdaRestApi( self, 'SaApi', rest_api_name='SaApi', handler=fetch_lambda, default_cors_preflight_options=aws_apigateway.CorsOptions( allow_origins=aws_apigateway.Cors.ALL_ORIGINS)) # endregion API # region Frontend frontend_bucket = aws_s3.Bucket(self, "CreateReactAppBucket", website_index_document="index.html") frontend_src = aws_s3_deployment.BucketDeployment( self, "DeployCRA", sources=[ aws_s3_deployment.Source.asset("../frontend/sa-app/build") ], destination_bucket=frontend_bucket) oia = aws_cloudfront.OriginAccessIdentity(self, 'OIA') frontend_bucket.grant_read(oia) cloudFront = aws_cloudfront.CloudFrontWebDistribution( self, "CDKCRAStaticDistribution", origin_configs=[ aws_cloudfront.SourceConfiguration( s3_origin_source=aws_cloudfront.S3OriginConfig( s3_bucket_source=frontend_bucket, origin_access_identity=oia), behaviors=[ aws_cloudfront.Behavior( is_default_behavior=True, default_ttl=core.Duration.seconds(0), max_ttl=core.Duration.seconds(0), min_ttl=core.Duration.seconds(0)) ]) ]) # endregion # region S3 triggers new_mask_image_notification = aws_s3_notifications.LambdaDestination( insert_lambda) mask_images_bucket.add_event_notification( aws_s3.EventType.OBJECT_CREATED, new_mask_image_notification)
def __init__(self, scope: Construct, id: str, *, sources: str, hosted_zone: HostedZone = None, site_domain: str = None, website_index: str = "index.html", website_error: str = "error.html"): """ This constructs creates: - S3 bucket - DNS Validated certificate - CloudFront web distribution - Route53 A record :param scope: The scope in which to define this construct. :param id: The scoped construct ID. Must be unique amongst siblings. If the ID includes a path separator (``/``), then it will be replaced by double dash ``--``. :param hosted_zone: A route53 hosted zone :param site_domain: The domain or subdomain you want to use for the website :param sources: A path to the location of the code :param website_index: Name of the index page, defaults to "index.html" :param website_error: Name of the error page, defaults to "error.html" """ super().__init__(scope, id) # Construct code goes here if site_domain: CfnOutput(self, "Site", value=f"https://{site_domain}") # Content bucket self.site_bucket = aws_s3.Bucket(self, "SiteBucket", bucket_name=site_domain, website_index_document=website_index, website_error_document=website_error, public_read_access=True, removal_policy=RemovalPolicy.DESTROY) CfnOutput(self, "BucketArn", value=self.site_bucket.bucket_arn) CfnOutput(self, "BucketWebsiteUrl", value=self.site_bucket.bucket_website_url) CfnOutput(self, "BucketWebsiteDomainName", value=self.site_bucket.bucket_website_domain_name) # Certificate alias_config = None if hosted_zone: self.cert = DnsValidatedCertificate(self, f"{id}-bucket", domain_name=site_domain, hosted_zone=hosted_zone) CfnOutput(self, 'CertificateArn', value=self.cert.certificate_arn) alias_config = AliasConfiguration( acm_cert_ref=self.cert.certificate_arn, names=[site_domain], ssl_method=aws_cloudfront.SSLMethod.SNI, security_policy=aws_cloudfront.SecurityPolicyProtocol. TLS_V1_1_2016, ) self.distr = CloudFrontWebDistribution( self, "SiteDistribution", alias_configuration=alias_config, origin_configs=[ SourceConfiguration( s3_origin_source=aws_cloudfront.S3OriginConfig( s3_bucket_source=self.site_bucket), behaviors=[ aws_cloudfront.Behavior(is_default_behavior=True) ]) ]) CfnOutput(self, "DistributionId", value=self.distr.distribution_id) # Route 53 alias record for the cloudfront distribution if hosted_zone: aws_route53.ARecord( self, "SiteAliasRecord", zone=hosted_zone, target=aws_route53.AddressRecordTarget.from_alias( aws_route53_targets.CloudFrontTarget(self.distr)), record_name=site_domain) aws_s3_deployment.BucketDeployment( self, "DeployWithInvalidation", sources=[aws_s3_deployment.Source.asset(sources)], destination_bucket=self.site_bucket, distribution=self.distr, distribution_paths=["/*"])