
I recently worked on implementing CloudFront for s3 bucket files. Most of the tutorials were doing that using console management(UI) but we at Blue Sky Analytics prefer “code as infrastructure”. So I had to do this using CloudFormation. With the help of a few StackOverflow links and tutorials, I was able to write CloudFormation Template.
How is this gonna work?
We are gonna use a private bucket, a public bucket can also be used but we don’t use it to avoid direct access to bucket and leakage.
CloudFront can access private bucket data using OAI(Origin Access Identity). An OAI is like a virtual user through which CloudFront can access private bucket. After creating OAI and using it in CloudFront, we need to update bucket policy, So that CloudFront with an OAI can access it.
Resources we are going to build using CloudFormation:
- S3 Bucket
- OAI(Origin Access Identity).
- Update Bucket Policy
- CloudFront Distribution
First, we need to define AWS template version and a “Resources” attribute to start writing resource templates. AWS template version defines the capabilities of a template.
S3 Bucket
Bucker resource template
“Bucket” is the name of resource template. We can use it any suitable name here. “Type” defines the type of resource, after this, we can define properties of resource. Each resource will have its own properties.
OAI(Origin Access Identity)
OAI resource template
Update Bucket Policy
Template resource to update bucket policy.
Two of the most important fields, here are AWS field under principle and Resource fields.
Recently created OAI can be used directly by using its template resource name like this “${CloudFrontOriginIdentity}”
CloudFront Distribution
Now the final CloudFront Distribution resource template.
One property you need to be careful here is “Origins”, that basically defines your bucket origin and “DomainName” will be like this “${bucket name}.s3.${region}.amazonaws.com”.
After completing CloudFromation template, you can use sam command to deploy and check status of its CloudFromation stack.