server

serverless framework and s3 buckets

Create a static website on AWS S3

app: playground
service: cdn-pseekoo-io

frameworkVersion: '2'

provider:
  name: aws
  stage: ${opt:stage}
  runtime: nodejs14.x
  lambdaHashingVersion: 20201221
  region: us-east-1
  memorySize: 1024

resources:
  Resources:
    StaticSite:
      Type: AWS::S3::Bucket
      Properties:
        BucketName: ${self:custom.bucket}
        AccessControl: PublicRead
        WebsiteConfiguration:
          IndexDocument: index.html
        CorsConfiguration:
          CorsRules:
            - AllowedMethods:
              - GET
              AllowedOrigins:
              - "*"
              AllowedHeaders:
              - "*"
    BucketPolicy:
      Type: AWS::S3::BucketPolicy
      Properties:
        Bucket:
          Ref: StaticSite
        PolicyDocument:
          Statement:
            - Sid: PublicReadGetObject
              Action:
                - s3:GetObject
              Resource:
                - arn:aws:s3:::${self:custom.bucket}/*
              Effect: Allow
              Principal: "*"

    CloudFrontDistribution:
      Type: AWS::CloudFront::Distribution
      Properties:
        DistributionConfig:
          Aliases:
            - ${self:custom.domainName}
          Origins:
            - DomainName: ${self:custom.bucket}.s3.${self:provider.region}.amazonaws.com
              Id: S3-${self:custom.bucket}
              CustomOriginConfig:
                HTTPSPort: 443
                OriginProtocolPolicy: https-only
          Enabled: 'true'
          HttpVersion: http2
          IPV6Enabled: 'true'
          DefaultRootObject: index.html
          DefaultCacheBehavior:
            AllowedMethods:
              - DELETE
              - GET
              - HEAD
              - OPTIONS
              - PATCH
              - POST
              - PUT
            TargetOriginId: S3-${self:custom.bucket}
            ForwardedValues:
              QueryString: 'false'
              Cookies:
                Forward: none
            ViewerProtocolPolicy: https-only
          ViewerCertificate:
            MinimumProtocolVersion: TLSv1.2_2021
            AcmCertificateArn:  CERTIFICATE_ARN
            SslSupportMethod: sni-only

package:
  patterns:
    - '!node_modules/**'
    - '!\.idea/**'
    - '!\.gitignore'
    - '!\.git/**'
    - handler.js

custom:
  project: PROJECT_NAME
  bucket: BUCKET_NAME
  domainName: DOMAIN_NAME

CERTIFICATE_ARN

The ARN of your AWS SSL certificate

PROJECT_NAME

A unique project name

BUCKET_NAME

The bucket name (must be equal to the domain name)

details here

DOMAIN_NAME

The domain name

invalidate cloudfront cache

aws cloudfront create-invalidation --distribution-id XXXXXXXXXXXX --paths "/*"

Links

Full documentation on CloudFormation here

Docs to serverless CloudFront here

serverless finch plugin here

serverless s3 sync here

aws credentials

aws regions