How do I build an AWS CloudFront distribution with Pulumi?
In this guide, we will create an AWS CloudFront distribution using Pulumi. AWS CloudFront is a fast content delivery network (CDN) service that securely delivers data, videos, applications, and APIs to customers globally with low latency and high transfer speeds.
Key Points
- We will define an S3 bucket as the origin for our CloudFront distribution.
- We will configure the CloudFront distribution to use the S3 bucket.
- We will set up caching and other distribution settings.
import * as pulumi from "@pulumi/pulumi";
import * as aws from "@pulumi/aws";
// Create an S3 bucket to serve as the origin for the CloudFront distribution
const bucket = new aws.s3.Bucket("myBucket", {
website: {
indexDocument: "index.html",
errorDocument: "error.html",
},
});
// Create an S3 Bucket Policy to allow CloudFront to access the bucket
const bucketPolicy = new aws.s3.BucketPolicy("bucketPolicy", {
bucket: bucket.bucket,
policy: bucket.bucket.apply(bucketName => JSON.stringify({
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Principal: {
Service: "cloudfront.amazonaws.com",
},
Action: "s3:GetObject",
Resource: `arn:aws:s3:::${bucketName}/*`,
}],
})),
});
// Create a CloudFront distribution
const cdn = new aws.cloudfront.Distribution("myDistribution", {
enabled: true,
origins: [{
originId: bucket.arn,
domainName: bucket.websiteEndpoint,
s3OriginConfig: {
originAccessIdentity: "origin-access-identity/cloudfront/E127EXAMPLE51Z",
},
}],
defaultCacheBehavior: {
targetOriginId: bucket.arn,
viewerProtocolPolicy: "allow-all",
allowedMethods: ["GET", "HEAD"],
cachedMethods: ["GET", "HEAD"],
forwardedValues: {
queryString: false,
cookies: {
forward: "none",
},
},
minTtl: 0,
defaultTtl: 3600,
maxTtl: 86400,
},
priceClass: "PriceClass_100",
customErrorResponses: [{
errorCode: 404,
responseCode: 200,
responsePagePath: "/error.html",
}],
restrictions: {
geoRestriction: {
restrictionType: "none",
},
},
viewerCertificate: {
cloudfrontDefaultCertificate: true,
},
});
// Export the bucket name and CloudFront distribution domain name
export const bucketName = bucket.bucket;
export const cdnDomainName = cdn.domainName;
Summary
In this guide, we created an AWS CloudFront distribution using Pulumi. We set up an S3 bucket as the origin and configured the CloudFront distribution to use this bucket. We also defined caching behaviors and error responses. This setup helps deliver content with low latency and high transfer speeds globally.
Deploy this code
Want to deploy this code? Sign up for a free Pulumi account to deploy in a few clicks.
Sign upNew to Pulumi?
Want to deploy this code? Sign up with Pulumi to deploy in a few clicks.
Sign upThank you for your feedback!
If you have a question about how to use Pulumi, reach out in Community Slack.
Open an issue on GitHub to report a problem or suggest an improvement.