Skip to content

Instantly share code, notes, and snippets.

@fourgates
Created May 26, 2023 16:28
Show Gist options
  • Save fourgates/31c236ca7b156852709cba5e795ed208 to your computer and use it in GitHub Desktop.
Save fourgates/31c236ca7b156852709cba5e795ed208 to your computer and use it in GitHub Desktop.
Custom AWS CDK Construct to Create S3 + Cloudfront Dist
import { Stack,
aws_s3 as s3,
aws_cloudfront as cloudfront,
aws_cloudfront_origins as cfOrigins,
aws_certificatemanager as certificatemanager,
aws_s3_deployment as s3deploy,
RemovalPolicy,
Duration
} from "aws-cdk-lib";
import { Construct } from "constructs";
export interface S3CloudFrontDistConstructProps {
bucketName: string,
domainName: string,
usEast1SSlCertificateArn: string,
assetLocation: string
}
export class S3CloudFrontDistConstruct extends Construct {
constructor(scope: Stack, id: string, props: S3CloudFrontDistConstructProps) {
super(scope, id);
this.addS3Dist(props);
}
private addS3Dist(s3DistProps: S3CloudFrontDistConstructProps) {
const { bucketName, domainName, usEast1SSlCertificateArn, assetLocation } = s3DistProps;
// create a bucket to hold frontend assets
const myBucket = new s3.Bucket(this, bucketName, {
publicReadAccess: false,
removalPolicy: RemovalPolicy.DESTROY,
});
// upload assets to bucket
new s3deploy.BucketDeployment(this, "DeployWebsite", {
sources: [s3deploy.Source.asset(assetLocation)],
destinationBucket: myBucket,
});
// load ssl certificate
const certificate = certificatemanager.Certificate.fromCertificateArn(
this,
`CertificateImported-${bucketName}`,
usEast1SSlCertificateArn
);
// create a cloudfront distribution
new cloudfront.Distribution(this, `${bucketName}-dist`, {
// route to s3 bucket
defaultBehavior: {
origin: new cfOrigins.S3Origin(myBucket),
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
compress: true,
},
// since this is a SPA, error pages need to redirect to index.html
errorResponses: [
{
httpStatus: 403,
responseHttpStatus: 200,
responsePagePath: "/index.html",
ttl: Duration.seconds(10),
},
{
httpStatus: 404,
responseHttpStatus: 200,
responsePagePath: "/index.html",
ttl: Duration.seconds(10),
},
],
domainNames: [domainName],
certificate,
minimumProtocolVersion: cloudfront.SecurityPolicyProtocol.TLS_V1_2_2021,
defaultRootObject: "index.html",
comment: domainName,
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment