Skip to content

Instantly share code, notes, and snippets.

@danstn
Created April 27, 2021 05:24
Show Gist options
  • Save danstn/51696a0d1e660b3b4bdb9f8bc0b55cc2 to your computer and use it in GitHub Desktop.
Save danstn/51696a0d1e660b3b4bdb9f8bc0b55cc2 to your computer and use it in GitHub Desktop.
CDK Construct for React FE on S3/CloudFront with Route53 and HTTPS
export class InfrastructureStack extends cdk.Stack {
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// Create a new bucket
const bucket = new s3.Bucket(this, BUCKET_ID, {
bucketName: "<your-domain>",
websiteIndexDocument: "index.html",
autoDeleteObjects: true,
enforceSSL: true,
removalPolicy: RemovalPolicy.DESTROY,
blockPublicAccess: BlockPublicAccess.BLOCK_ALL
});
// Lookup hosted zone in R53
const hostedZone = route53.HostedZone.fromLookup(this, 'HostedZone', {
domainName: "<your-hosted-zone-root-domain>",
});
const certificate = new certificateManager.DnsValidatedCertificate(this, 'Certificate', {
domainName: DOMAIN_NAME,
hostedZone,
region: "us-east-1" // this is a global service
});
// Create Origin Access Identity for CF
const cloudFrontOAI = new cloudfront.OriginAccessIdentity(this, "OAI");
// Create a distribution
const distribution = new cloudfront.CloudFrontWebDistribution(this, CLOUD_FRONT_ID, {
originConfigs: [
{
s3OriginSource: {
s3BucketSource: bucket,
originAccessIdentity: cloudFrontOAI,
},
behaviors: [{
isDefaultBehavior: true,
}],
}
],
// Specify certificate for CF to use
viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(certificate, {
aliases: [DOMAIN_NAME],
securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1,
sslMethod: cloudfront.SSLMethod.SNI
})
})
// Add a record with CF target
new route53.ARecord(this, "Alias", {
zone: hostedZone,
recordName: DOMAIN_NAME,
target: route53.RecordTarget.fromAlias(new targets.CloudFrontTarget(distribution))
})
// Grant read access to the bucket for the OAI
bucket.grantRead(cloudFrontOAI.grantPrincipal);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment