I want to have a CloudFront distribution with access to a private S3 bucket. For that, I have to create an origin access identity. Manually, I can do that using the AWS console, but I wanted to create it via a CloudFormation script or with Serverless (using serverless.yml). While doing this, I am able to add a physical Id of the origin access identity to my CloudFront distribution (using one script).
Relevant documentation: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/quickref-cloudfront.html
I tried this:
myDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Origins:
- DomainName:bucket.s3.amazonaws.com
Id: myS3Origin
S3OriginConfig: {
OriginAccessIdentity:origin-access-identity/cloudfront/ !Ref cloudfrontoriginaccessidentity
}
Enabled: 'true'
Comment: Some comment
DefaultCacheBehavior:
ForwardedValues:
QueryString: 'false'
Cookies:
Forward: none
AllowedMethods:
- GET
- HEAD
- OPTIONS
TargetOriginId: myS3Origin
ViewerProtocolPolicy: redirect-to-https
PriceClass: PriceClass_200
ViewerCertificate:
CloudFrontDefaultCertificate: 'true'
cloudfrontoriginaccessidentity:
Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: "some comment"
I have to create an origin access identity and a CloudFront distribution having this identity. Can we do both of these things in one CloudFormation script or with Serverless (using serverless.yml)?
You definitely can create an origin access identity and the CloudFront distribution in the same serverless.yml.
I've modified your scenario and changed the OriginAccessIdentity to use Fn::Join.
myDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Origins:
- DomainName:bucket.s3.amazonaws.com
Id: myS3Origin
S3OriginConfig:
OriginAccessIdentity:
Fn::Join:
- ''
-
- 'origin-access-identity/cloudfront/'
- Ref: cloudfrontoriginaccessidentity
Enabled: 'true'
Comment: Some comment
DefaultCacheBehavior:
ForwardedValues:
QueryString: 'false'
Cookies:
Forward: none
AllowedMethods:
- GET
- HEAD
- OPTIONS
TargetOriginId: myS3Origin
ViewerProtocolPolicy: redirect-to-https
PriceClass: PriceClass_200
ViewerCertificate:
CloudFrontDefaultCertificate: 'true'
cloudfrontoriginaccessidentity:
Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: "some comment"
The serverless examples repo has a great example of this too: https://github.com/serverless/examples/blob/master/aws-node-single-page-app-via-cloudfront/serverless.yml
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With