AWS CloudFront

CloudFront

  • CDN (Content Delivery Network)
  • It retrieves data from Amazon S3 bucket and distributes it to multiple datacenter locations.
  • It delivers the data through a network of data centers called edge locations. The nearest edge location is routed when the user requests for data, resulting in lowest latency, low network traffic, fast access to data, etc.

Set up

AWS Console - public bucket

  1. Sign in to AWS management console.
  2. Upload Amazon S3 and choose every permission public.
  3. Go to CloudFront console: Select a delivery method for your content - > Get Started.
    4.Origin Domain Name -> Amazon S3 bucket created.
  4. Next, dafult, and Create Distribution button.
  5. When the Status column changes from “In Progress” to “Deployed”, select the Enable option.
  6. Wait around 15 minutes for the domain name to be available in the Distributions list.

Cloudformation - private bucket

graph LR;

A[Bucket]
B[Cloudfront]
C[User]

A -- bucket data --> B;
B -- bucket data --> C;
C --> B;
B -- request with OAI --> A;

Bucket

1
2
3
4
5
6
7
8
Bucket:
Type: AWS::S3::Bucket
Properties:
AccessControl: Private
BucketName: private-bucket
Tags:
- Key: description
Value: "Private files"

OAI (Origin Access Identity)

1
2
3
4
5
CloudFrontOriginIdentity:
Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: 'origin identity'

Update Bucket Policy

1
2
3
4
5
6
7
8
9
10
11
12
13
BucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket: private-bucket
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
AWS: !Sub 'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity'
# you may get the recently created with '${CloudFrontOriginIdentity}'
Action: 's3:GetObject'
Resource: arn:aws:s3:::private-bucket/*

CloudFront Distribution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
publicDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Origins:
- DomainName: private-bucket.s3.us-east-2.amazonaws.com
# careful with '${bucket name}.s3.${region}.amazonaws.com'
Id: S3-private-bucket
S3OriginConfig:
OriginAccessIdentity: !Sub 'origin-access-identity/cloudfront/${CloudFrontOriginIdentity}'
Enabled: 'true'
Comment: Some comment
DefaultCacheBehavior:
AllowedMethods:
- GET
- HEAD
TargetOriginId: S3-private-bucket
ForwardedValues:
QueryString: 'false'
Cookies:
Forward: none
ViewerProtocolPolicy: redirect-to-https
ViewerCertificate:
CloudFrontDefaultCertificate: 'true'