|
| 1 | +import { RemovalPolicy, CfnOutput } from "aws-cdk-lib"; |
| 2 | +import * as cdk from "aws-cdk-lib"; |
| 3 | +import { aws_cloudfront as cloudfront } from "aws-cdk-lib"; |
| 4 | +import { Construct } from "constructs"; |
| 5 | +import * as S3 from "aws-cdk-lib/aws-s3"; |
| 6 | +import * as S3Deploy from "aws-cdk-lib/aws-s3-deployment"; |
| 7 | +import { |
| 8 | + CloudFrontWebDistribution, |
| 9 | + OriginAccessIdentity, |
| 10 | +} from "aws-cdk-lib/aws-cloudfront"; |
| 11 | +import { join } from "path"; |
| 12 | + |
| 13 | +export class CdkStack extends cdk.Stack { |
| 14 | + constructor(scope: Construct, id: string, props?: cdk.StackProps) { |
| 15 | + super(scope, id, props); |
| 16 | + |
| 17 | + const bucket = new S3.Bucket(this, "MyFirstBucket", { |
| 18 | + removalPolicy: RemovalPolicy.DESTROY, |
| 19 | + autoDeleteObjects: true, |
| 20 | + // blockPublicAccess: S3.BlockPublicAccess.BLOCK_ACLS, |
| 21 | + accessControl: S3.BucketAccessControl.BUCKET_OWNER_FULL_CONTROL, |
| 22 | + websiteIndexDocument: "index.html", |
| 23 | + websiteErrorDocument: "index.html", |
| 24 | + }); |
| 25 | + |
| 26 | + const accessDeniedErrorResponse: cloudfront.CfnDistribution.CustomErrorResponseProperty = |
| 27 | + { |
| 28 | + errorCode: 403, |
| 29 | + errorCachingMinTtl: 30, |
| 30 | + responseCode: 200, |
| 31 | + responsePagePath: "/index.html", |
| 32 | + }; |
| 33 | + const notFoundErrorResponse: cloudfront.CfnDistribution.CustomErrorResponseProperty = |
| 34 | + { |
| 35 | + errorCode: 404, |
| 36 | + errorCachingMinTtl: 30, |
| 37 | + responseCode: 200, |
| 38 | + responsePagePath: "/index.html", |
| 39 | + }; |
| 40 | + |
| 41 | + const oai = new OriginAccessIdentity(this, `origin-access-id`, {}); |
| 42 | + bucket.grantRead(oai); |
| 43 | + |
| 44 | + const distribution = new CloudFrontWebDistribution( |
| 45 | + this, |
| 46 | + `MyFirstDistribution`, |
| 47 | + { |
| 48 | + originConfigs: [ |
| 49 | + { |
| 50 | + s3OriginSource: { |
| 51 | + s3BucketSource: bucket, |
| 52 | + originAccessIdentity: oai, |
| 53 | + }, |
| 54 | + behaviors: [{ isDefaultBehavior: true }], |
| 55 | + }, |
| 56 | + ], |
| 57 | + errorConfigurations: [accessDeniedErrorResponse, notFoundErrorResponse], |
| 58 | + } |
| 59 | + ); |
| 60 | + |
| 61 | + new S3Deploy.BucketDeployment(this, "MyFirstDeploy", { |
| 62 | + sources: [ |
| 63 | + S3Deploy.Source.asset(join(__dirname, "..", "..", "..", "dist")), |
| 64 | + ], |
| 65 | + destinationBucket: bucket, |
| 66 | + }); |
| 67 | + |
| 68 | + new CfnOutput(this, "BucketUrl", { |
| 69 | + value: bucket.bucketWebsiteUrl, |
| 70 | + exportName: "FrontendBucketUrl", |
| 71 | + }); |
| 72 | + |
| 73 | + new CfnOutput(this, "DistributionUrl", { |
| 74 | + value: distribution.distributionDomainName, |
| 75 | + exportName: "FrontendUrl", |
| 76 | + }); |
| 77 | + } |
| 78 | +} |
0 commit comments