aws-cloudfront
Deploy an AWS CloudFront distribution for the provided origins using Serverless Components.
- Install
- Create
- Configure
- Deploy
1. Install
$ npm install -g serverless
2. Create
$ mkdir cdn
$ cd cdn
the directory should look something like this:
|- serverless.yml
|- .env # your AWS api keys
# .env
AWS_ACCESS_KEY_ID=XXX
AWS_SECRET_ACCESS_KEY=XXX
3. Configure
distribution:
component: '@serverless/aws-cloudfront'
inputs:
region: us-east-1
enabled: true
comment: 'My distribution'
defaults:
ttl: 15
allowedHttpMethods: ['HEAD', 'GET']
forward:
headers: ['Accept', 'Accept-Language']
cookies: ['my-cookie]
queryString: true
queryStringCacheKeys: ['queryKey']
viewerProtocolPolicy: 'https-only'
smoothStreaming: true
compress: true
fieldLevelEncryptionId: '123'
lambda@edge:
viewer-request: arn:aws:lambda:us-east-1:123:function:myFunc:version
origins:
- https://my-bucket.s3.amazonaws.com
Custom cache behavior
Custom cache behaviors support the same config parameters as the default cache behavior (see the example above).
distribution:
component: '@serverless/aws-cloudfront'
inputs:
origins:
- url: https://my-assets.com
pathPatterns:
/static/images:
ttl: 10
allowedHttpMethods: ['GET', 'HEAD']
forward:
headers: 'all'
cookies: ['auth-token']
queryString: true
compress: false
Lambda@Edge
distribution:
component: '@serverless/aws-cloudfront'
inputs:
origins:
- url: https://sampleorigin.com
pathPatterns:
/sample/path:
ttl: 10
lambda@edge:
viewer-request: arn:aws:lambda:us-east-1:123:function:myFunc:version
Private S3 Content
To restrict access to content that you serve from S3 you can mark as private
your S3 origins:
distribution:
component: '@serverless/aws-cloudfront'
inputs:
origins:
- url: https://my-private-bucket.s3.amazonaws.com
private: true
A bucket policy will be added that grants CloudFront with access to the bucket objects. Note that it doesn't remove any existing permissions on the bucket. If users currently have permission to access the files in your bucket using Amazon S3 URLs you will need to manually remove those.
This is documented in more detail here: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-restricting-access-to-s3.html
4. Deploy
$ serverless
New to Components?
Checkout the Serverless Components repo for more information.