Skip to content

Commit

Permalink
CloudWebホスティング用FrontとS3を作成しました
Browse files Browse the repository at this point in the history
  • Loading branch information
AsukaNamiki committed Mar 11, 2024
1 parent 5dff296 commit 0504550
Showing 1 changed file with 73 additions and 0 deletions.
73 changes: 73 additions & 0 deletions src/backend/lib/backend-stack.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,78 @@ export class BackendStack extends cdk.Stack {
new s3.Bucket(this, `diary-${props.environment}-bucket`, {
removalPolicy: cdk.RemovalPolicy.DESTROY,
});

// Hosting S3 & CloudFront
const websiteBucket = new s3.Bucket(this, 'diary-hosting-bucket', {
removalPolicy: cdk.RemovalPolicy.DESTROY,
});

const originAccessIdentity = new cdk.aws_cloudfront.OriginAccessIdentity(
this,
'OriginAccessIdentity',
{
comment: 'website-distribution-originAccessIdentity',
}
);

const webSiteBucketPolicyStatement = new cdk.aws_iam.PolicyStatement({
actions: ['s3:GetObject'],
effect: cdk.aws_iam.Effect.ALLOW,
principals: [
new cdk.aws_iam.CanonicalUserPrincipal(
originAccessIdentity.cloudFrontOriginAccessIdentityS3CanonicalUserId
),
],
resources: [`${websiteBucket.bucketArn}/*`],
});

websiteBucket.addToResourcePolicy(webSiteBucketPolicyStatement);

const distribution = new cdk.aws_cloudfront.Distribution(this, 'distribution', {
comment: 'website-distribution',
defaultRootObject: 'index.html',
errorResponses: [
{
ttl: cdk.Duration.seconds(300),
httpStatus: 403,
responseHttpStatus: 403,
responsePagePath: '/error.html',
},
{
ttl: cdk.Duration.seconds(300),
httpStatus: 404,
responseHttpStatus: 404,
responsePagePath: '/error.html',
},
],
defaultBehavior: {
allowedMethods: cdk.aws_cloudfront.AllowedMethods.ALLOW_GET_HEAD,
cachedMethods: cdk.aws_cloudfront.CachedMethods.CACHE_GET_HEAD,
cachePolicy: cdk.aws_cloudfront.CachePolicy.CACHING_OPTIMIZED,
viewerProtocolPolicy:
cdk.aws_cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
origin: new cdk.aws_cloudfront_origins.S3Origin(websiteBucket, {
originAccessIdentity,
}),
},
priceClass: cdk.aws_cloudfront.PriceClass.PRICE_CLASS_ALL,
});

new cdk.aws_s3_deployment.BucketDeployment(this, 'WebsiteDeploy', {
sources: [
cdk.aws_s3_deployment.Source.data(
'/index.html',
'<html><body><h1>Hello World</h1></body></html>'
),
cdk.aws_s3_deployment.Source.data(
'/error.html',
'<html><body><h1>Error!!!!!!!!!!!!!</h1></body></html>'
),
],
destinationBucket: websiteBucket,
distribution: distribution,
distributionPaths: ['/*'],
});

}
}

0 comments on commit 0504550

Please sign in to comment.