Repository: tobilg/serverless-aws-static-websites Branch: master Commit: 12db702c3a8b Files: 18 Total size: 21.9 KB Directory structure: gitextract_klkqwyo0/ ├── .gitignore ├── LICENSE ├── README.md ├── modules/ │ ├── output.js │ └── sanitizeStackName.js ├── package.json ├── resources/ │ ├── certificate.yml │ ├── cf-distribution.yml │ ├── cloudfront-origin-access-identity.yml │ ├── custom-acm-certificate-lambda-role.yml │ ├── custom-acm-certificate-lambda.yml │ ├── dns-records.yml │ ├── hosted-zone.yml │ ├── outputs.yml │ ├── s3-bucket.yml │ └── s3-policies.yml ├── serverless.yml └── src/ └── index.html ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ .idea .serverless .DS_Store # Logs logs *.log npm-debug.log* yarn-debug.log* yarn-error.log* # Runtime data pids *.pid *.seed *.pid.lock # Directory for instrumented libs generated by jscoverage/JSCover lib-cov # Coverage directory used by tools like istanbul coverage # nyc test coverage .nyc_output # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) .grunt # Bower dependency directory (https://bower.io/) bower_components # node-waf configuration .lock-wscript # Compiled binary addons (https://nodejs.org/api/addons.html) build/Release # Dependency directories node_modules/ jspm_packages/ # TypeScript v1 declaration files typings/ # Optional npm cache directory .npm # Optional eslint cache .eslintcache # Optional REPL history .node_repl_history # Output of 'npm pack' *.tgz # Yarn Integrity file .yarn-integrity # dotenv environment variables file .env # next.js build output .next ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2019 Tobi Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # serverless-aws-static-websites Host your static website on AWS via S3, with global CDN via CloudFront, using SSL certificates provided by ACM using your own domain name! All set up via one [Serverless](https://www.serverless.com) command and minimum manual configuration! ## Architecture ![Serverless static websites on AWS](docs/architecture.png)[]() ### What is provisioned in your AWS account? * A S3 bucket containing your static website * A CloudFront distribution for global hosting via CDN * A HostedZone on Route53 with A records for your domain name * A Lambda function for automatic SSL certificate generation via ACM for your domain name (run once upon deployment) ## Preconditions This guide assumes that you have a pre-existing domain which you want to use for hosting your static website. Furthermore, you need to have access to the domain's DNS configuration. Also, you need to have an install of [Serverless](https://www.serverless.com) on your machine. ## How-to To use this blueprint with your own static websites, you can follow the steps below to get started. ### Set up a Serverless project for your static website There are basically two ways to get started, either use [Serverless](https://www.serverless.com) to generate a basic project structure, or use the "traditional" fork and clone mechanisms. #### Use Serverless templates The following command will create a local project structure you can use to deploy your static website in the `mystaticwebsite` folder relative to your current working directory: ```bash $ sls create --template-url https://github.com/tobilg/serverless-aws-static-websites --path mystaticwebsite Serverless: Generating boilerplate... Serverless: Downloading and installing "serverless-aws-static-websites"... Serverless: Successfully installed "serverless-aws-static-websites" ``` **Hint** When using this method, Serverless is replacing the `service.name` in the `serverless.yml` file automatically with `mystaticwebiste`. If you want to use a different stack name, you have to replace it manually. You also need to take care of that the stack name is using only allowed characters. When using the "Fork and clone" method below, the stack name is automatically derived from the domain name and sanitized regarding the allowed characters. #### Fork and clone Once you forked the repo on GitHub, you can clone it locally via ```bash $ git clone git@github.com:youraccount/yourrepo.git ``` where `youraccount/yourrepo` needs to be replaced with the actual repository name of your forked repo. ### Install dependencies To install the dependencies, do a ```bash $ npm i ``` After that, the project is usable. ### Create your static website You can now create your static website in the `src` folder of your cloned repo. ### Deploy You can deploy your static website with the following command: ```bash $ sls deploy --domain yourdomain.yourtld ``` where `yourdomain.yourtld` needs to be replaced with your actual domain name. You can also specify a AWS region via the `--region` flag, otherwise `us-east-1` will be used. #### Manual update of DNS records on first deploy On the first deploy, it is necessary to update the DNS setting for the domain manually, otherwise the hosted zone will not be able to be established. Therefore, once you triggered the `sls deploy` command, you need to log into the AWS console, go to the [Hosted Zones](https://console.aws.amazon.com/route53/home?region=eu-central-1#hosted-zones:) menu and select the corresponding domain name you used for the deployment. The nameservers you have to configure your domain DNS to can be found under the `NS` record and will look similar to this: ```bash ns-1807.awsdns-33.co.uk. ns-977.awsdns-58.net. ns-1351.awsdns-40.org. ns-32.awsdns-04.com. ``` You should then update your DNS settings for your domain with those values, **otherwise the stack creation process will fail**. This is a bit misfortunate, but to the best of knowledge there's currently no other way possible if you use AWS external (non-Route53) domains. During my tests with [namecheap.com](https://www.namecheap.com) domains the DNS records were always updated fast enough, so that the stack creation didn't fail. #### Deployment process duration As a new CloudFront distribution is created (which is pretty slow), it can take **up to 45min** for the initial deploy to finish. This is normal and expected behavior. ### Post-deploy If the deployment finished successfully, you will be able to access your domain via `https://www.yourdomain.yourtld` and `https://yourdomain.yourtld`. This setup should give you some good [PageSpeed Insights](https://developers.google.com/speed/pagespeed/insights/?hl=en) results. ### Updates For every update of your website, you can trigger a deploy as stated above. This will effectively just do s S3 sync of the `src` folder. To do a manual sync, your can also use `sls s3sync`. There's also the possibility to customize the caching behavior for individual files or file types via the `serverless.yml`, see the [s3sync plugin's documentation](https://www.npmjs.com/package/serverless-s3-sync#setup). As **CloudFront caches the contents of the website**, a [Serverless plugin](https://github.com/aghadiry/serverless-cloudfront-invalidate) is used to invalidate files. This [may incur costs](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html#PayingForInvalidation), see the [docs](https://aws.amazon.com/de/premiumsupport/knowledge-center/cloudfront-serving-outdated-content-s3/) for more info. You can run `sls cloudfrontInvalidate` to do a standalone invalidation of the defined files in the `serverless.yml`. ## Removal If you want to remove the created stack, you will have to delete all records of the Hosted Zone of the respective domain except the `SOA` and `NS` records, otherwise the stack deletion via ```bash $ sls remove --domain yourdomain.yourtld ``` will fail. ================================================ FILE: modules/output.js ================================================ module.exports.handler = (data, serverless, options) => { serverless.cli.log(`DNS nameservers to be configured with your '${serverless.providers.aws.options.domain}' domain: ${data.HostedZoneNameservers}`); }; ================================================ FILE: modules/sanitizeStackName.js ================================================ module.exports.sanitize = (serverless) => { if (!serverless.providers.aws.options.hasOwnProperty('domain')) { serverless.cli.log('No domain flag found, exiting! Please specify --domain '); process.exit(1); } else { const sanitizedStackName = `website-${serverless.providers.aws.options.domain.replace(/\./g, '-')}`; serverless.cli.log(`Stack name is ${sanitizedStackName}`); return sanitizedStackName; } }; ================================================ FILE: package.json ================================================ { "name": "serverless-aws-static-websites", "version": "0.1.0", "description": "Deploy your static websites without all the hassle on AWS with CloudFront, S3, ACM and Route53 via Serverless", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "repository": { "type": "git", "url": "git@github.com:tobilg/serverless-aws-static-websites.git" }, "author": "", "license": "UNLICENSED", "bugs": { "url": "https://github.com/tobilg/serverless-aws-static-websites/issues" }, "homepage": "https://github.com/tobilg/serverless-aws-static-websites#readme", "devDependencies": { "serverless-cloudfront-invalidate": "^1.3.0", "serverless-pseudo-parameters": "^2.4.0", "serverless-s3-sync": "^1.8.0", "serverless-stack-output": "^0.2.3" }, "dependencies": {} } ================================================ FILE: resources/certificate.yml ================================================ Resources: SSLCertificate: Type: 'Custom::DNSCertificate' DependsOn: - HostedZone Properties: DomainName: '${opt:domain}' SubjectAlternativeNames: - 'www.${opt:domain}' ValidationMethod: DNS # Needs to be in us-east-1 because of CloudFront limitations Region: us-east-1 DomainValidationOptions: - DomainName: '${opt:domain}' HostedZoneId: '#{HostedZone}' ServiceToken: '#{CustomAcmCertificateLambda.Arn}' ================================================ FILE: resources/cf-distribution.yml ================================================ # See https://blog.m-taylor.co.uk/2018/01/cloudformation-template-for-a-cloudfront-enabled-s3-website.html Resources: CFDistribution: Type: 'AWS::CloudFront::Distribution' DependsOn: - WebsiteBucket - HostedZone - SSLCertificate - CloudFrontOriginAccessIdentity Properties: DistributionConfig: Aliases: - '${opt:domain}' - 'www.${opt:domain}' Origins: - DomainName: '#{WebsiteBucket.DomainName}' OriginPath: '' Id: S3BucketOrigin S3OriginConfig: OriginAccessIdentity: Fn::Join: - '' - - 'origin-access-identity/cloudfront/' - '#{CloudFrontOriginAccessIdentity}' Comment: 'CloudFront origin for ${opt:domain}' DefaultCacheBehavior: AllowedMethods: - GET - HEAD - OPTIONS TargetOriginId: S3BucketOrigin Compress: true ForwardedValues: QueryString: 'false' Cookies: Forward: none ViewerProtocolPolicy: redirect-to-https DefaultRootObject: index.html Enabled: 'true' HttpVersion: 'http2' PriceClass: 'PriceClass_100' ViewerCertificate: AcmCertificateArn: '#{SSLCertificate}' SslSupportMethod: sni-only ================================================ FILE: resources/cloudfront-origin-access-identity.yml ================================================ Resources: CloudFrontOriginAccessIdentity: Type: 'AWS::CloudFront::CloudFrontOriginAccessIdentity' Properties: CloudFrontOriginAccessIdentityConfig: Comment: '${self:service.name}-oai' ================================================ FILE: resources/custom-acm-certificate-lambda-role.yml ================================================ Resources: CustomAcmCertificateLambdaExecutionRole: Type: 'AWS::IAM::Role' Properties: AssumeRolePolicyDocument: Statement: - Action: - sts:AssumeRole Effect: Allow Principal: Service: lambda.amazonaws.com Version: '2012-10-17' ManagedPolicyArns: - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole - arn:aws:iam::aws:policy/service-role/AWSLambdaRole Policies: - PolicyDocument: Statement: - Action: - acm:AddTagsToCertificate - acm:DeleteCertificate - acm:DescribeCertificate - acm:RemoveTagsFromCertificate Effect: Allow Resource: - 'arn:aws:acm:*:#{AWS::AccountId}:certificate/*' - Action: - acm:RequestCertificate - acm:ListTagsForCertificate - acm:ListCertificates Effect: Allow Resource: - '*' - Action: - route53:ChangeResourceRecordSets Effect: Allow Resource: - arn:aws:route53:::hostedzone/* Version: '2012-10-17' PolicyName: 'CustomAcmCertificateLambdaExecutionPolicy-${self:service.name}' ================================================ FILE: resources/custom-acm-certificate-lambda.yml ================================================ Resources: CustomAcmCertificateLambda: Type: 'AWS::Lambda::Function' Metadata: Source: https://github.com/dflook/cloudformation-dns-certificate Version: 1.7.1 Properties: Description: Cloudformation custom resource for DNS validated certificates Handler: index.handler Role: '#{CustomAcmCertificateLambdaExecutionRole.Arn}' Runtime: python3.6 Timeout: 900 Code: ZipFile: "T=RuntimeError\nimport copy,hashlib as t,json,logging as B,time\ \ as b\nfrom boto3 import client as K\nfrom botocore.exceptions import ClientError\ \ as u,ParamValidationError as v\nfrom botocore.vendored import requests\ \ as w\nA=B.getLogger()\nA.setLevel(B.INFO)\nD=A.info\nS=A.exception\nd=json.dumps\n\ M=copy.copy\ne=b.sleep\ndef handler(event,c):\n\tA9='OldResourceProperties';A8='Update';A7='Delete';A6='None';A5='acm';A4='FAILED';A3='properties';A2='stack-id';A1='logical-id';A0='DNS';s='Old';r='Certificate';q='LogicalResourceId';p='DomainName';o='ValidationMethod';n='Route53RoleArn';m='Region';a='RequestType';Z='Reinvoked';Y='StackId';X=None;R='Status';Q='Key';P='';O=True;N='DomainValidationOptions';L=False;J='ResourceProperties';I='cloudformation:';H='Value';G='CertificateArn';F='Tags';C='PhysicalResourceId';A=event;f=c.get_remaining_time_in_millis;D(A)\n\ \tdef g():\n\t\tD=M(B)\n\t\tfor H in ['ServiceToken',m,F,n]:D.pop(H,X)\n\ \t\tif o in B:\n\t\t\tif B[o]==A0:\n\t\t\t\tfor I in set([B[p]]+B.get('SubjectAlternativeNames',[])):k(I)\n\ \t\t\t\tdel D[N]\n\t\tA[C]=E.request_certificate(IdempotencyToken=y,**D)[G];l()\n\ \tdef U(a):\n\t\twhile O:\n\t\t\ttry:E.delete_certificate(**{G:a});return\n\ \t\t\texcept u as B:\n\t\t\t\tS(P);A=B.response['Error']['Code']\n\t\t\t\ \tif A=='ResourceInUseException':\n\t\t\t\t\tif f()/1000<30:raise\n\t\t\t\ \t\te(5);continue\n\t\t\t\tif A in['ResourceNotFoundException','ValidationException']:return\n\ \t\t\t\traise\n\t\t\texcept v:return\n\tdef V(props):\n\t\tfor J in E.get_paginator('list_certificates').paginate():\n\ \t\t\tfor B in J['CertificateSummaryList']:\n\t\t\t\tD(B);C={A[Q]:A[H]for\ \ A in E.list_tags_for_certificate(**{G:B[G]})[F]}\n\t\t\t\tif C.get(I+A1)==A[q]and\ \ C.get(I+A2)==A[Y]and C.get(I+A3)==hash(props):return B[G]\n\tdef h():\n\ \t\tif A.get(Z,L):raise T('Certificate not issued in time')\n\t\tA[Z]=O;D(A);K('lambda').invoke(FunctionName=c.invoked_function_arn,InvocationType='Event',Payload=d(A).encode())\n\ \tdef i():\n\t\twhile f()/1000>30:\n\t\t\tB=E.describe_certificate(**{G:A[C]})[r];D(B)\n\ \t\t\tif B[R]=='ISSUED':return O\n\t\t\telif B[R]==A4:raise T(B.get('FailureReason',P))\n\ \t\t\te(5)\n\t\treturn L\n\tdef x():B=M(A[s+J]);B.pop(F,X);C=M(A[J]);C.pop(F,X);return\ \ B!=C\n\tdef j():\n\t\tW='Type';V='Name';U='HostedZoneId';T='ValidationStatus';S='PENDING_VALIDATION';L='ResourceRecord'\n\ \t\tif B.get(o)!=A0:return\n\t\twhile O:\n\t\t\tI=E.describe_certificate(**{G:A[C]})[r];D(I)\n\ \t\t\tif I[R]!=S:return\n\t\t\tif not[A for A in I.get(N,[{}])if T not in\ \ A or L not in A]:break\n\t\t\tb.sleep(1)\n\t\tfor F in I[N]:\n\t\t\tif\ \ F[T]==S:M=k(F[p]);P=M.get(n,B.get(n));J=K('sts').assume_role(RoleArn=P,RoleSessionName=(r+A[q])[:64],DurationSeconds=900)['Credentials']if\ \ P is not X else{};Q=K('route53',aws_access_key_id=J.get('AccessKeyId'),aws_secret_access_key=J.get('SecretAccessKey'),aws_session_token=J.get('SessionToken')).change_resource_record_sets(**{U:M[U],'ChangeBatch':{'Comment':'Domain\ \ validation for '+A[C],'Changes':[{'Action':'UPSERT','ResourceRecordSet':{V:F[L][V],W:F[L][W],'TTL':60,'ResourceRecords':[{H:F[L][H]}]}}]}});D(Q)\n\ \tdef k(n):\n\t\tC='.';n=n.rstrip(C);D={A[p].rstrip(C):A for A in B[N]};A=n.split(C)\n\ \t\twhile len(A):\n\t\t\tif C.join(A)in D:return D[C.join(A)]\n\t\t\tA=A[1:]\n\ \t\traise T(N+' missing'+' for '+n)\n\thash=lambda v:t.new('md5',d(v,sort_keys=O).encode()).hexdigest()\n\ \tdef l():B=M(A[J].get(F,[]));B+=[{Q:I+A1,H:A[q]},{Q:I+A2,H:A[Y]},{Q:I+'stack-name',H:A[Y].split('/')[1]},{Q:I+A3,H:hash(A[J])}];E.add_tags_to_certificate(**{G:A[C],F:B})\n\ \tdef W():D(A);B=w.put(A['ResponseURL'],json=A,headers={'content-type':P});B.raise_for_status()\n\ \ttry:\n\t\ty=hash(A['RequestId']+A[Y]);B=A[J];E=K(A5,region_name=B.get(m));A[R]='SUCCESS'\n\ \t\tif A[a]=='Create':\n\t\t\tif A.get(Z,L)is L:A[C]=A6;g()\n\t\t\tj()\n\ \t\t\tif not i():return h()\n\t\telif A[a]==A7:\n\t\t\tif A[C]!=A6:\n\t\t\ \t\tif A[C].startswith('arn:'):U(A[C])\n\t\t\t\telse:U(V(B))\n\t\telif A[a]==A8:\n\ \t\t\tif x():\n\t\t\t\tD(A8)\n\t\t\t\tif V(B)==A[C]:\n\t\t\t\t\ttry:E=K(A5,region_name=A[A9].get(m));D(A7);U(V(A[A9]))\n\ \t\t\t\t\texcept:S(P)\n\t\t\t\t\treturn W()\n\t\t\t\tif A.get(Z,L)is L:g()\n\ \t\t\t\tj()\n\t\t\t\tif not i():return h()\n\t\t\telse:\n\t\t\t\tif F in\ \ A[s+J]:E.remove_tags_from_certificate(**{G:A[C],F:A[s+J][F]})\n\t\t\t\t\ l()\n\t\telse:raise T(A[a])\n\t\treturn W()\n\texcept Exception as z:S(P);A[R]=A4;A['Reason']=str(z);return\ \ W()" ================================================ FILE: resources/dns-records.yml ================================================ # See RecordSet: https://docs.aws.amazon.com/de_de/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html # See AliasTarget: https://docs.aws.amazon.com/de_de/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html # See https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region (below the first table for hosted zone ids / website endpoints of S3) Resources: DnsRecord: Type: 'AWS::Route53::RecordSet' DependsOn: - HostedZone Properties: Comment: 'Alias CloudFront for ${opt:domain}' HostedZoneId: '#{HostedZone}' Type: A Name: '${opt:domain}' AliasTarget: # Generated domain name from CloudFront DNSName: '#{CFDistribution.DomainName}' # Default (static) hosted zone for CloudFront HostedZoneId: 'Z2FDTNDATAQYW2' WWWDnsRecord: Type: 'AWS::Route53::RecordSet' DependsOn: - HostedZone Properties: Comment: 'Alias CloudFront for www.${opt:domain}' HostedZoneId: '#{HostedZone}' Type: A Name: 'www.${opt:domain}' AliasTarget: # Generated domain name from CloudFront DNSName: '#{CFDistribution.DomainName}' # Default (static) hosted zone for CloudFront HostedZoneId: 'Z2FDTNDATAQYW2' ================================================ FILE: resources/hosted-zone.yml ================================================ # See https://docs.aws.amazon.com/de_de/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone.html Resources: HostedZone: Type: 'AWS::Route53::HostedZone' Properties: HostedZoneConfig: Comment: 'Hosted zone for ${opt:domain}' Name: '${opt:domain}' ================================================ FILE: resources/outputs.yml ================================================ Outputs: CloudFrontDistributionId: Description: CloudFront distribution id Value: Ref: CFDistribution HostedZoneNameservers: Description: The nameservers for the Hosted Zone (to be used with your external DNS configuration) Value: 'Fn::Join': - ', ' - 'Fn::GetAtt': ['HostedZone', 'NameServers'] ================================================ FILE: resources/s3-bucket.yml ================================================ Resources: WebsiteBucket: Type: 'AWS::S3::Bucket' Properties: BucketName: ${opt:domain} ================================================ FILE: resources/s3-policies.yml ================================================ Resources: WebsiteBucketPolicy: Type: AWS::S3::BucketPolicy DependsOn: - WebsiteBucket Properties: Bucket: Ref: WebsiteBucket PolicyDocument: Statement: - Sid: PublicReadGetObject Effect: Allow Principal: AWS: Fn::Join: - ' ' - - 'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity' - '#{CloudFrontOriginAccessIdentity}' Action: - s3:GetObject Resource: - Fn::Join: [ '', [ 'arn:aws:s3:::', { 'Ref': 'WebsiteBucket' }, '/*' ] ] ================================================ FILE: serverless.yml ================================================ service: name: ${file(./modules/sanitizeStackName.js):sanitize} plugins: - serverless-s3-sync - serverless-pseudo-parameters - serverless-stack-output - serverless-cloudfront-invalidate custom: # The domain name to be used domainName: ${opt:domain} # Output plugin configuration output: handler: modules/output.handler # CloudFront invalidation plugin configuration cloudfrontInvalidate: distributionIdKey: 'CloudFrontDistributionId' items: # Add your files to invalidate here: - '/index.html' # S3 sync plugin configuration s3Sync: - bucketName: ${opt:domain} localDir: src provider: name: aws runtime: nodejs8.10 region: ${opt:region, 'us-east-1'} resources: - ${file(resources/custom-acm-certificate-lambda.yml)} - ${file(resources/custom-acm-certificate-lambda-role.yml)} - ${file(resources/cloudfront-origin-access-identity.yml)} - ${file(resources/s3-bucket.yml)} - ${file(resources/s3-policies.yml)} - ${file(resources/hosted-zone.yml)} - ${file(resources/dns-records.yml)} - ${file(resources/certificate.yml)} - ${file(resources/cf-distribution.yml)} - ${file(resources/outputs.yml)} ================================================ FILE: src/index.html ================================================

Welcome to my static website!