Skip to content

Instantly share code, notes, and snippets.

@jcyuyi jcyuyi/s3-cf-ssl.yml
Last active Dec 26, 2018

Embed
What would you like to do?
AWS CloudFormation Templates: CloudFront distribution with an S3 origin and SSL for static pages
AWSTemplateFormatVersion: '2010-09-09'
Description: 'CloudFront distribution with an S3 origin for static pages'
Parameters:
domainName:
Description: 'Domain name for your website (example.com)'
Type: 'String'
acmCertArn:
Description: 'ACM Certification ARN (in us-east-1 region)'
Type: 'String'
app:
Description: 'App name tag'
Type: 'String'
env:
Description: 'Environment tag'
Type: 'String'
Resources:
bucket:
Type: 'AWS::S3::Bucket'
DeletionPolicy: 'Delete' # Dont't panic: you must delete all objects in the bucket for deletion to succeed
Properties:
BucketName: !Ref domainName
AccessControl: 'Private'
WebsiteConfiguration:
IndexDocument: 'index.html'
ErrorDocument: 'error.html'
Tags:
- Key: 'app'
Value: !Ref app
- Key: 'env'
Value: !Ref env
bucketPolicy:
Type: 'AWS::S3::BucketPolicy'
Metadata:
Comment: 'Bucket policy to allow cloudfront to access the data'
Properties:
Bucket: !Ref bucket
PolicyDocument:
Statement:
- Action:
- 's3:GetObject'
Effect: 'Allow'
Principal:
CanonicalUser: !GetAtt cfOriginAccessIdentity.S3CanonicalUserId
Resource:
- !Sub 'arn:aws:s3:::${bucket}/*'
cfDistribution:
Metadata:
Comment: 'CloudFront distribution with an S3 origin for static pages'
Properties:
DistributionConfig:
Aliases:
- !Ref domainName
DefaultCacheBehavior:
TargetOriginId: !Sub 's3-origin-${bucket}'
ViewerProtocolPolicy: 'redirect-to-https'
ForwardedValues:
QueryString: false
DefaultRootObject: 'index.html'
Enabled: true
Origins:
- DomainName: !GetAtt bucket.DomainName
Id: !Sub 's3-origin-${bucket}'
OriginPath: ''
S3OriginConfig:
OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/${cfOriginAccessIdentity}'
ViewerCertificate:
SslSupportMethod: 'sni-only'
AcmCertificateArn: !Ref acmCertArn
Tags:
- Key: 'app'
Value: !Ref app
- Key: 'env'
Value: !Ref env
Type: 'AWS::CloudFront::Distribution'
cfOriginAccessIdentity:
Type: 'AWS::CloudFront::CloudFrontOriginAccessIdentity'
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: 'Access S3 bucket content only through CloudFront'
Outputs:
bucketName:
Description: 'Bucket name'
Value: !Ref bucket
cfDistributionId:
Description: 'Id for our cloudfront distribution'
Value: !Ref cfDistribution
cfDistributionDomainName:
Description: 'Domain name for our cloudfront distribution'
Value: !GetAtt cfDistribution.DomainName
@jcyuyi

This comment has been minimized.

Copy link
Owner Author

jcyuyi commented Dec 26, 2018

Usage:

aws cloudformation deploy \
--template-file s3-cf-ssl.yml \
--stack-name stack-static \
--parameter-overrides \
domainName=www.example.com \
acmCertArn=YOUR_ACM_CERT_ARN \
app=myapp \
env=prd
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.