How do I set up CloudFront and S3 with a policy on AWS?
In this guide, we will set up an AWS CloudFront distribution with an S3 bucket as the origin. We’ll also configure an S3 bucket policy to allow CloudFront to access the bucket. This setup is useful for serving static websites or other content with low latency and high transfer speeds.
Key Points
- Define an S3 bucket to store the content.
- Set up a CloudFront distribution to serve the content from the S3 bucket.
- Create an S3 bucket policy to allow CloudFront to access the bucket.
import * as aws from "@pulumi/aws";
import * as pulumi from "@pulumi/pulumi";
// Create an S3 bucket to store the content
const contentBucket = new aws.s3.Bucket("contentBucket", {
website: {
indexDocument: "index.html",
},
});
// Create an Origin Access Identity to access the S3 bucket from CloudFront
const originAccessIdentity = new aws.cloudfront.OriginAccessIdentity("originAccessIdentity", {});
// Create a CloudFront distribution to serve the content from the S3 bucket
const cdn = new aws.cloudfront.Distribution("cdn", {
enabled: true,
origins: [{
originId: contentBucket.arn,
domainName: contentBucket.bucketRegionalDomainName,
s3OriginConfig: {
originAccessIdentity: originAccessIdentity.cloudfrontAccessIdentityPath,
},
}],
defaultCacheBehavior: {
targetOriginId: contentBucket.arn,
viewerProtocolPolicy: "redirect-to-https",
allowedMethods: ["GET", "HEAD"],
cachedMethods: ["GET", "HEAD"],
forwardedValues: {
queryString: false,
cookies: {
forward: "none",
},
},
},
priceClass: "PriceClass_100",
restrictions: {
geoRestriction: {
restrictionType: "none",
},
},
viewerCertificate: {
cloudfrontDefaultCertificate: true,
},
});
// Create an S3 bucket policy to allow CloudFront to access the bucket
const bucketPolicy = new aws.s3.BucketPolicy("bucketPolicy", {
bucket: contentBucket.bucket,
policy: contentBucket.bucket.apply(bucketName => JSON.stringify({
Version: "2012-10-17",
Statement: [{
Effect: "Allow",
Principal: {
AWS: `arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity ${originAccessIdentity.id}`,
},
Action: "s3:GetObject",
Resource: `arn:aws:s3:::${bucketName}/*`,
}],
})),
});
// Export the CloudFront distribution domain name
export const cdnDomainName = cdn.domainName;
Summary
In this guide, we created an S3 bucket to store content and a CloudFront distribution to serve that content. We also set up an Origin Access Identity and configured an S3 bucket policy to allow CloudFront to access the bucket. This setup ensures that your content is delivered with low latency and high transfer speeds.
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.