Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Secure S3 hosting bucket with CloudFront distro. Only allows distro access to the bucket
AWSTemplateFormatVersion: "2010-09-09"
Description: AWS S3 Hosting bucket and CloudFront Distrobution
Resources:
## Origin Access ID for CloudFront
HostAccessIdentity:
Type: "AWS::CloudFront::CloudFrontOriginAccessIdentity"
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: MyHostBucketId
## Hosting Bucket
HostBucket:
Type: AWS::S3::Bucket
## Host Buckey Policy
HostBucketPolicy:
Type: 'AWS::S3::BucketPolicy'
Properties:
PolicyDocument:
Version: 2012-10-17
Statement:
Effect: Allow
Principal:
CanonicalUser: !GetAtt HostAccessIdentity.S3CanonicalUserId
Action: 's3:GetObject'
Resource: !Sub arn:aws:s3:::${HostBucket}/*
Bucket: !Ref HostBucket
HostDistro:
Type: "AWS::CloudFront::Distribution"
Properties:
DistributionConfig:
Origins:
- DomainName: !Sub ${HostBucket}.s3.amazonaws.com
Id: MyS3Origin
S3OriginConfig:
OriginAccessIdentity: !Sub origin-access-identity/cloudfront/${HostAccessIdentity}
Enabled: true
DefaultCacheBehavior:
ForwardedValues:
QueryString: true
TargetOriginId: MyS3Origin
ViewerProtocolPolicy: redirect-to-https
DefaultRootObject: index.html
## Uncomment for routing to index for SPA's
##CustomErrorResponses:
## - ErrorCode: 403
## ResponseCode: 200
## ResponsePagePath: /index.html
## - ErrorCode: 404
## ResponseCode: 200
## ResponsePagePath: /index.html
Outputs:
HostBucketAddress:
Description: Bucket location for hosting
Value: !Sub s3://${HostBucket}
ClientDomain:
Description: Domain of Client
Value: !GetAtt HostDistro.DomainName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.