├── .gitignore ├── LICENSE ├── README.md ├── api ├── baseApi.js ├── routes │ ├── defaults.js │ └── v1 │ │ └── api.js └── static │ ├── apiDocs.yml │ └── favicon.ico ├── docs └── architecture.png ├── modules ├── output.js └── sanitizeStackName.js ├── package-lock.json ├── package.json ├── resources ├── api-gw-basepath-mapping.yml ├── api-gw-domain-name.yml ├── api-gw.yml ├── 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 └── website └── index.html /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | # Serverless 64 | .serverless 65 | 66 | # MacOS stuff 67 | .DS_Store -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Tobi 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-fullstack-website 2 | Deploy your fullstack websites without all the hassle on AWS with CloudFront, S3, ACM, Route53, API Gateway and Lambda via Serverless. 3 | 4 | All set up via one [Serverless](https://www.serverless.com) command and minimum manual configuration! 5 | 6 | ## Architecture 7 | 8 | ![Serverless fullstack website on AWS](docs/architecture.png) 9 | 10 | ### What is provisioned in your AWS account? 11 | * A S3 bucket containing your static website 12 | * A CloudFront distribution for global hosting of your static website via CDN 13 | * An API Gateway endpoint for the API backend Lambda function 14 | * A Lambda function for the API backend 15 | * A HostedZone on Route53 with A records for your domain name 16 | * A Lambda function for automatic SSL certificate generation via ACM for your domain name (run once upon deployment) 17 | * DNS records for your custom domain (with `www.` and `api.` subdomains) 18 | 19 | All of the CloudFormation resources reside in the `resources` subfolder. 20 | 21 | ## Preconditions 22 | 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. 23 | 24 | Also, you need to have an install of [Serverless](https://www.serverless.com) on your machine. 25 | 26 | ## How-to 27 | To use this blueprint with your own static websites, you can follow the steps below to get started. 28 | 29 | ### Set up a Serverless project for your static website 30 | 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. 31 | 32 | #### Use Serverless templates 33 | The following command will create a local project structure you can use to deploy your static website in the `myfullstackwebsite` folder relative to your current working directory: 34 | 35 | ```bash 36 | $ sls create --template-url https://github.com/tobilg/aws-fullstack-website --path myfullstackwebsite 37 | Serverless: Generating boilerplate... 38 | Serverless: Downloading and installing "aws-fullstack-website"... 39 | Serverless: Successfully installed "aws-fullstack-website" 40 | ``` 41 | 42 | **Hint** 43 | When using this method, Serverless is replacing the `service.name` in the `serverless.yml` file automatically with `myfullstackwebsite`. 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. 44 | 45 | #### Fork and clone 46 | Once you forked the repo on GitHub, you can clone it locally via 47 | 48 | ```bash 49 | $ git clone git@github.com:youraccount/yourrepo.git 50 | ``` 51 | 52 | where `youraccount/yourrepo` needs to be replaced with the actual repository name of your forked repo. 53 | 54 | ### Install dependencies 55 | To install the dependencies, do a 56 | 57 | ```bash 58 | $ npm i 59 | ``` 60 | 61 | After that, the project is usable. 62 | 63 | ### Create your static website 64 | You can now create your static website in the `website` folder of your cloned repo. 65 | 66 | ### Create your API backend 67 | The API backend files can be found in the `api` subfolder. There are some default files which yoou can leave unchanged, the actual API lives in the `api/routes/v1/api.js` file. 68 | 69 | It uses the [Lambda API package](https://www.npmjs.com/package/lambda-api), which provides an intuitive way to write API routes and has a lot of built-in functionalities. If you're familiar with writing APIs with [Express](https://www.npmjs.com/package/express), you should be able to come up to speed quite quickly. 70 | 71 | #### Base routes 72 | The following routes do pre-exist: 73 | 74 | ```text 75 | GET /favicon.ico Returns the static favicon.ico from the 'api/static' folder 76 | GET /v1/info Returns the API version information 77 | (derived from the 'package.json' file) 78 | GET /v1/api-docs Returns the OpenAPI v3 documentation of the API 79 | ``` 80 | 81 | #### API docs 82 | Just point [editor.swagger.io](https://editor.swagger.io/) with `File -> Import URL` to `https://api.yourdomain.yourtld/v1/api-docs` where `yourdomain.yourtld` is the domain name you specified as `--domain` argument while deploying. Once you finished editing, just copy and paste the Swagger Editor contents to the `api/static/api-docs.yml` file. After a new deployment, your API docs will be updated. 83 | 84 | ### Additional AWS resources 85 | If you want to add additional AWS resources, such as a DynamoDB table, you can do this by creating a new file in the `resources` folder, and then use it in the `serverless.yml` file's `resources` section like this: 86 | 87 | ```yaml 88 | resources: 89 | - ${file(resources/my-new-resource.yml)} 90 | ``` 91 | 92 | #### Example 93 | An example on how to add a DynamoDB table might look like this: Create a new file `resources/dynamodb-table.yml` with the following content: 94 | 95 | ```yaml 96 | Resources: 97 | BaseDataTable: 98 | Type: AWS::DynamoDB::Table 99 | Properties: 100 | TableName: 'my-table' 101 | KeySchema: 102 | - 103 | AttributeName: 'partitionKey' 104 | KeyType: 'HASH' 105 | - 106 | AttributeName: 'sortKey' 107 | KeyType: 'RANGE' 108 | AttributeDefinitions: 109 | - 110 | AttributeName: 'partitionKey' 111 | AttributeType: 'S' 112 | - 113 | AttributeName: 'sortKey' 114 | AttributeType: 'S' 115 | BillingMode: PAY_PER_REQUEST 116 | ``` 117 | 118 | Then, add the following line to the `resources` section of the `serverless.yml` file: 119 | 120 | ```yaml 121 | resources: 122 | # other resources 123 | - ${file(resources/dynamodb-table.yml)} 124 | # other resources 125 | ``` 126 | 127 | After that, you can (re-)deploy your fullstack wesite (see below). 128 | 129 | ### Deploy 130 | You can deploy your static website with the following command: 131 | 132 | ```bash 133 | $ sls deploy --domain yourdomain.yourtld 134 | ``` 135 | 136 | 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. 137 | 138 | #### Manual update of DNS records on first deploy 139 | 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. 140 | 141 | 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=us-east-1#hosted-zones:) menu and select the corresponding domain name you used for the deployment. 142 | 143 | The nameservers you have to configure your domain DNS to can be found under the `NS` record and will look similar to this: 144 | 145 | ```bash 146 | ns-1807.awsdns-33.co.uk. 147 | ns-977.awsdns-58.net. 148 | ns-1351.awsdns-40.org. 149 | ns-32.awsdns-04.com. 150 | ``` 151 | 152 | You should then update your DNS settings for your domain with those values, **otherwise the stack creation process will fail**. 153 | 154 | 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. 155 | 156 | #### Deployment process duration 157 | 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. 158 | 159 | ### Post-deploy 160 | If the deployment finished successfully, you will be able to access your domain via `https://www.yourdomain.yourtld` and `https://yourdomain.yourtld`. 161 | 162 | ### Updates 163 | For every update of your website, you can trigger a deploy as stated above. This will effectively just do s S3 sync of the `website` folder. 164 | 165 | 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). 166 | 167 | 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. 168 | 169 | You can run `sls cloudfrontInvalidate` to do a standalone invalidation of the defined files in the `serverless.yml`. 170 | 171 | ## Removal 172 | If you want to remove the created stack, your 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 173 | 174 | ```bash 175 | $ sls remove --domain yourdomain.yourtld 176 | ``` 177 | 178 | will fail. -------------------------------------------------------------------------------- /api/baseApi.js: -------------------------------------------------------------------------------- 1 | // See 2 | // * https://www.jeremydaly.com/build-serverless-api-serverless-aws-lambda-lambda-api/ 3 | // * https://www.npmjs.com/package/lambda-api 4 | 5 | // Require and init API router module 6 | const api = require('lambda-api')({ 7 | logger: { 8 | level: 'debug', 9 | access: true, 10 | stack: true, 11 | timestamp: () => new Date().toUTCString() 12 | } 13 | }); 14 | 15 | // Register default routes 16 | api.register(require('./routes/defaults'), {}); 17 | 18 | // Register v1 routes 19 | api.register(require('./routes/v1/api'), { prefix: `/${process.env.BASE_PATH}` }); 20 | 21 | // Declare Lambda handler 22 | module.exports.router = async (event, context) => { 23 | // Log event 24 | console.log(event); 25 | // Run the request 26 | return await api.run(event, context) 27 | } -------------------------------------------------------------------------------- /api/routes/defaults.js: -------------------------------------------------------------------------------- 1 | module.exports = (api, opts) => { 2 | api.get('/favicon.ico', (req, res) => { 3 | res.sendFile('./api/static/favicon.ico', { maxAge: 3600000 }); 4 | }); 5 | } -------------------------------------------------------------------------------- /api/routes/v1/api.js: -------------------------------------------------------------------------------- 1 | // Global modules 2 | const fs = require('fs'); 3 | const path = require('path'); 4 | 5 | // Local modules 6 | const package = require('../../../package.json'); 7 | const apiDocs = fs.readFileSync(path.join(__dirname, '../../static/apiDocs.yml'), { encoding: 'utf8' }); 8 | 9 | module.exports = (api, opts) => { 10 | 11 | api.get('/info', async (req, res) => { 12 | res.status(200).json({ 13 | name: process.env.DOMAIN_NAME, 14 | description: package.description, 15 | version: process.env.BASE_PATH 16 | }); 17 | }); 18 | 19 | api.get('/api-docs', async (req, res) => { 20 | res.header('Content-Type', 'application/yaml') 21 | .header('Access-Control-Allow-Origin', '*') 22 | .send(apiDocs); 23 | }); 24 | 25 | } -------------------------------------------------------------------------------- /api/static/apiDocs.yml: -------------------------------------------------------------------------------- 1 | openapi: 3.0.0 2 | info: 3 | title: "AWS Fullstack Website API" 4 | description: "Additional information resources for this API can be found below:\n-" 5 | version: "1.0" 6 | contact: 7 | email: contact@yourdomain.test 8 | license: 9 | name: "MIT" 10 | 11 | servers: 12 | - url: "https://{domain}/{version}" 13 | description: "AWS Fullstack Website API server" 14 | variables: 15 | domain: 16 | default: yourdomain.test 17 | version: 18 | default: v1 19 | 20 | paths: 21 | /api-docs: 22 | get: 23 | summary: "Retrieve the OpenAPI v3.0 specification." 24 | responses: 25 | 200: 26 | description: "Return the api docs" 27 | content: 28 | application/x-yaml: 29 | examples: 30 | get-response: 31 | $ref: "#/components/examples/apiDocsResponse" 32 | 500: 33 | description: "Default AWS error" 34 | content: 35 | application/json: 36 | schema: 37 | $ref: "#/components/schemas/defaultError" 38 | tags: 39 | - "Documentation" 40 | 41 | /info: 42 | get: 43 | summary: "Retrieve API version information." 44 | responses: 45 | 200: 46 | description: "Get API version info." 47 | content: 48 | application/json: 49 | schema: 50 | $ref: "#/components/schemas/infoResponse" 51 | 500: 52 | description: "Default error" 53 | content: 54 | application/json: 55 | schema: 56 | $ref: "#/components/schemas/defaultError" 57 | tags: 58 | - "Documentation" 59 | 60 | components: 61 | schemas: 62 | defaultError: 63 | type: object 64 | properties: 65 | error: 66 | type: string 67 | required: 68 | - error 69 | infoResponse: 70 | description: "Response for API version information request" 71 | type: object 72 | properties: 73 | name: 74 | type: string 75 | description: 76 | type: string 77 | version: 78 | type: string 79 | examples: 80 | apiDocsResponse: 81 | summary: "Response in case getting the api doc is successful" 82 | value: "openapi: 3.0.0 ..." 83 | emptyResponse: 84 | summary: "Response in case the querying the schema returns no data" 85 | value: "{}" -------------------------------------------------------------------------------- /api/static/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tobilg/aws-fullstack-website/50c636451fef91ca7517c2c3d10c1380a65d6123/api/static/favicon.ico -------------------------------------------------------------------------------- /docs/architecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/tobilg/aws-fullstack-website/50c636451fef91ca7517c2c3d10c1380a65d6123/docs/architecture.png -------------------------------------------------------------------------------- /modules/output.js: -------------------------------------------------------------------------------- 1 | module.exports.handler = (data, serverless, options) => { 2 | serverless.cli.log(`DNS nameservers to be configured with your '${serverless.providers.aws.options.domain}' domain: ${data.HostedZoneNameservers}`); 3 | serverless.cli.log(`API info endpoint: 'https://api.${serverless.providers.aws.options.domain}/v1/info'`); 4 | }; 5 | -------------------------------------------------------------------------------- /modules/sanitizeStackName.js: -------------------------------------------------------------------------------- 1 | module.exports.sanitize = (serverless) => { 2 | if (!serverless.providers.aws.options.hasOwnProperty('domain')) { 3 | serverless.cli.log('No domain flag found, exiting! Please specify --domain '); 4 | process.exit(1); 5 | } else { 6 | const sanitizedStackName = `fullstack-website-${serverless.providers.aws.options.domain.replace(/\./g, '-')}`; 7 | serverless.cli.log(`Stack name is ${sanitizedStackName}`); 8 | return sanitizedStackName; 9 | } 10 | }; 11 | -------------------------------------------------------------------------------- /package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "aws-fullstack-website", 3 | "version": "0.1.0", 4 | "lockfileVersion": 1, 5 | "requires": true, 6 | "dependencies": { 7 | "@auth0/s3": { 8 | "version": "1.0.0", 9 | "resolved": "https://registry.npmjs.org/@auth0/s3/-/s3-1.0.0.tgz", 10 | "integrity": "sha512-O8PTXJnA7n8ONBSwqlWa+aZ/vlOdZYnSCGQt25h87ALWNItY/Yij79TOnzIkMTJZ8aCpGXQPuIRziLmBliV++Q==", 11 | "dev": true, 12 | "requires": { 13 | "aws-sdk": "^2.346.0", 14 | "fd-slicer": "~1.0.0", 15 | "findit2": "~2.2.3", 16 | "graceful-fs": "~4.1.4", 17 | "mime": "^2.3.1", 18 | "mkdirp": "~0.5.0", 19 | "pend": "~1.2.0", 20 | "rimraf": "~2.2.8", 21 | "streamsink": "~1.2.0" 22 | } 23 | }, 24 | "ansi-styles": { 25 | "version": "3.2.1", 26 | "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", 27 | "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", 28 | "dev": true, 29 | "requires": { 30 | "color-convert": "^1.9.0" 31 | } 32 | }, 33 | "argparse": { 34 | "version": "1.0.10", 35 | "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", 36 | "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", 37 | "dev": true, 38 | "requires": { 39 | "sprintf-js": "~1.0.2" 40 | } 41 | }, 42 | "array-uniq": { 43 | "version": "1.0.2", 44 | "resolved": "https://registry.npmjs.org/array-uniq/-/array-uniq-1.0.2.tgz", 45 | "integrity": "sha1-X8w3OSB3VyPP1k1lxkvvU7+eum0=", 46 | "dev": true 47 | }, 48 | "aws-sdk": { 49 | "version": "2.444.0", 50 | "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.444.0.tgz", 51 | "integrity": "sha512-3vdC7l5BJ3zHzVNgtIxD+TDviti/sAA/1T8zAXAm2XhZ7AePR5lYIMNAwqu+J44Nm6PFSK1QNSzRQ6A4/6b9eA==", 52 | "dev": true, 53 | "requires": { 54 | "buffer": "4.9.1", 55 | "events": "1.1.1", 56 | "ieee754": "1.1.8", 57 | "jmespath": "0.15.0", 58 | "querystring": "0.2.0", 59 | "sax": "1.2.1", 60 | "url": "0.10.3", 61 | "uuid": "3.3.2", 62 | "xml2js": "0.4.19" 63 | }, 64 | "dependencies": { 65 | "ieee754": { 66 | "version": "1.1.8", 67 | "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.8.tgz", 68 | "integrity": "sha1-vjPUCsEO8ZJnAfbwii2G+/0a0+Q=", 69 | "dev": true 70 | } 71 | } 72 | }, 73 | "balanced-match": { 74 | "version": "1.0.0", 75 | "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz", 76 | "integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=", 77 | "dev": true 78 | }, 79 | "base64-js": { 80 | "version": "1.3.0", 81 | "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.0.tgz", 82 | "integrity": "sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw==", 83 | "dev": true 84 | }, 85 | "bluebird": { 86 | "version": "3.5.4", 87 | "resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.4.tgz", 88 | "integrity": "sha512-FG+nFEZChJrbQ9tIccIfZJBz3J7mLrAhxakAbnrJWn8d7aKOC+LWifa0G+p4ZqKp4y13T7juYvdhq9NzKdsrjw==", 89 | "dev": true 90 | }, 91 | "brace-expansion": { 92 | "version": "1.1.11", 93 | "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", 94 | "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", 95 | "dev": true, 96 | "requires": { 97 | "balanced-match": "^1.0.0", 98 | "concat-map": "0.0.1" 99 | } 100 | }, 101 | "buffer": { 102 | "version": "4.9.1", 103 | "resolved": "https://registry.npmjs.org/buffer/-/buffer-4.9.1.tgz", 104 | "integrity": "sha1-bRu2AbB6TvztlwlBMgkwJ8lbwpg=", 105 | "dev": true, 106 | "requires": { 107 | "base64-js": "^1.0.2", 108 | "ieee754": "^1.1.4", 109 | "isarray": "^1.0.0" 110 | } 111 | }, 112 | "chalk": { 113 | "version": "2.4.2", 114 | "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", 115 | "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", 116 | "dev": true, 117 | "requires": { 118 | "ansi-styles": "^3.2.1", 119 | "escape-string-regexp": "^1.0.5", 120 | "supports-color": "^5.3.0" 121 | } 122 | }, 123 | "color-convert": { 124 | "version": "1.9.3", 125 | "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", 126 | "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", 127 | "dev": true, 128 | "requires": { 129 | "color-name": "1.1.3" 130 | } 131 | }, 132 | "color-name": { 133 | "version": "1.1.3", 134 | "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", 135 | "integrity": "sha1-p9BVi9icQveV3UIyj3QIMcpTvCU=", 136 | "dev": true 137 | }, 138 | "concat-map": { 139 | "version": "0.0.1", 140 | "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", 141 | "integrity": "sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=", 142 | "dev": true 143 | }, 144 | "escape-string-regexp": { 145 | "version": "1.0.5", 146 | "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", 147 | "integrity": "sha1-G2HAViGQqN/2rjuyzwIAyhMLhtQ=", 148 | "dev": true 149 | }, 150 | "events": { 151 | "version": "1.1.1", 152 | "resolved": "https://registry.npmjs.org/events/-/events-1.1.1.tgz", 153 | "integrity": "sha1-nr23Y1rQmccNzEwqH1AEKI6L2SQ=", 154 | "dev": true 155 | }, 156 | "fd-slicer": { 157 | "version": "1.0.1", 158 | "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.0.1.tgz", 159 | "integrity": "sha1-i1vL2ewyfFBBv5qwI/1nUPEXfmU=", 160 | "dev": true, 161 | "requires": { 162 | "pend": "~1.2.0" 163 | } 164 | }, 165 | "findit2": { 166 | "version": "2.2.3", 167 | "resolved": "https://registry.npmjs.org/findit2/-/findit2-2.2.3.tgz", 168 | "integrity": "sha1-WKRmaX34piBc39vzlVNri9d3pfY=", 169 | "dev": true 170 | }, 171 | "fs.realpath": { 172 | "version": "1.0.0", 173 | "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", 174 | "integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=", 175 | "dev": true 176 | }, 177 | "glob": { 178 | "version": "7.1.3", 179 | "resolved": "https://registry.npmjs.org/glob/-/glob-7.1.3.tgz", 180 | "integrity": "sha512-vcfuiIxogLV4DlGBHIUOwI0IbrJ8HWPc4MU7HzviGeNho/UJDfi6B5p3sHeWIQ0KGIU0Jpxi5ZHxemQfLkkAwQ==", 181 | "dev": true, 182 | "requires": { 183 | "fs.realpath": "^1.0.0", 184 | "inflight": "^1.0.4", 185 | "inherits": "2", 186 | "minimatch": "^3.0.4", 187 | "once": "^1.3.0", 188 | "path-is-absolute": "^1.0.0" 189 | } 190 | }, 191 | "graceful-fs": { 192 | "version": "4.1.15", 193 | "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.15.tgz", 194 | "integrity": "sha512-6uHUhOPEBgQ24HM+r6b/QwWfZq+yiFcipKFrOFiBEnWdy5sdzYoi+pJeQaPI5qOLRFqWmAXUPQNsielzdLoecA==", 195 | "dev": true 196 | }, 197 | "has-flag": { 198 | "version": "3.0.0", 199 | "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", 200 | "integrity": "sha1-tdRU3CGZriJWmfNGfloH87lVuv0=", 201 | "dev": true 202 | }, 203 | "ieee754": { 204 | "version": "1.1.12", 205 | "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.12.tgz", 206 | "integrity": "sha512-GguP+DRY+pJ3soyIiGPTvdiVXjZ+DbXOxGpXn3eMvNW4x4irjqXm4wHKscC+TfxSJ0yw/S1F24tqdMNsMZTiLA==", 207 | "dev": true 208 | }, 209 | "inflight": { 210 | "version": "1.0.6", 211 | "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", 212 | "integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=", 213 | "dev": true, 214 | "requires": { 215 | "once": "^1.3.0", 216 | "wrappy": "1" 217 | } 218 | }, 219 | "inherits": { 220 | "version": "2.0.3", 221 | "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", 222 | "integrity": "sha1-Yzwsg+PaQqUC9SRmAiSA9CCCYd4=", 223 | "dev": true 224 | }, 225 | "isarray": { 226 | "version": "1.0.0", 227 | "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", 228 | "integrity": "sha1-u5NdSFgsuhaMBoNJV6VKPgcSTxE=", 229 | "dev": true 230 | }, 231 | "jmespath": { 232 | "version": "0.15.0", 233 | "resolved": "https://registry.npmjs.org/jmespath/-/jmespath-0.15.0.tgz", 234 | "integrity": "sha1-o/Iiqarp+Wb10nx5ZRDigJF2Qhc=", 235 | "dev": true 236 | }, 237 | "lambda-api": { 238 | "version": "0.10.4", 239 | "resolved": "https://registry.npmjs.org/lambda-api/-/lambda-api-0.10.4.tgz", 240 | "integrity": "sha512-6egpxMunATKnglX4koFHGa+YWtjVx1CCB9Zu374rnkMkHZiV7qer0k+jbMNEK8xhSlzn494hJHTUr4BSOy12yg==" 241 | }, 242 | "mime": { 243 | "version": "2.4.2", 244 | "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.2.tgz", 245 | "integrity": "sha512-zJBfZDkwRu+j3Pdd2aHsR5GfH2jIWhmL1ZzBoc+X+3JEti2hbArWcyJ+1laC1D2/U/W1a/+Cegj0/OnEU2ybjg==", 246 | "dev": true 247 | }, 248 | "minimatch": { 249 | "version": "3.0.4", 250 | "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.0.4.tgz", 251 | "integrity": "sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==", 252 | "dev": true, 253 | "requires": { 254 | "brace-expansion": "^1.1.7" 255 | } 256 | }, 257 | "minimist": { 258 | "version": "0.0.8", 259 | "resolved": "https://registry.npmjs.org/minimist/-/minimist-0.0.8.tgz", 260 | "integrity": "sha1-hX/Kv8M5fSYluCKCYuhqp6ARsF0=", 261 | "dev": true 262 | }, 263 | "mkdirp": { 264 | "version": "0.5.1", 265 | "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.1.tgz", 266 | "integrity": "sha1-MAV0OOrGz3+MR2fzhkjWaX11yQM=", 267 | "dev": true, 268 | "requires": { 269 | "minimist": "0.0.8" 270 | } 271 | }, 272 | "once": { 273 | "version": "1.4.0", 274 | "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", 275 | "integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=", 276 | "dev": true, 277 | "requires": { 278 | "wrappy": "1" 279 | } 280 | }, 281 | "path-is-absolute": { 282 | "version": "1.0.1", 283 | "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", 284 | "integrity": "sha1-F0uSaHNVNP+8es5r9TpanhtcX18=", 285 | "dev": true 286 | }, 287 | "pend": { 288 | "version": "1.2.0", 289 | "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", 290 | "integrity": "sha1-elfrVQpng/kRUzH89GY9XI4AelA=", 291 | "dev": true 292 | }, 293 | "punycode": { 294 | "version": "1.3.2", 295 | "resolved": "https://registry.npmjs.org/punycode/-/punycode-1.3.2.tgz", 296 | "integrity": "sha1-llOgNvt8HuQjQvIyXM7v6jkmxI0=", 297 | "dev": true 298 | }, 299 | "querystring": { 300 | "version": "0.2.0", 301 | "resolved": "https://registry.npmjs.org/querystring/-/querystring-0.2.0.tgz", 302 | "integrity": "sha1-sgmEkgO7Jd+CDadW50cAWHhSFiA=", 303 | "dev": true 304 | }, 305 | "randomstring": { 306 | "version": "1.1.5", 307 | "resolved": "https://registry.npmjs.org/randomstring/-/randomstring-1.1.5.tgz", 308 | "integrity": "sha1-bfBij3XL1ZMpMNn+OrTpVqGFGMM=", 309 | "dev": true, 310 | "requires": { 311 | "array-uniq": "1.0.2" 312 | } 313 | }, 314 | "rimraf": { 315 | "version": "2.2.8", 316 | "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-2.2.8.tgz", 317 | "integrity": "sha1-5Dm+Kq7jJzIZUnMPmaiSnk/FBYI=", 318 | "dev": true 319 | }, 320 | "sax": { 321 | "version": "1.2.1", 322 | "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.1.tgz", 323 | "integrity": "sha1-e45lYZCyKOgaZq6nSEgNgozS03o=", 324 | "dev": true 325 | }, 326 | "serverless-cloudfront-invalidate": { 327 | "version": "1.3.0", 328 | "resolved": "https://registry.npmjs.org/serverless-cloudfront-invalidate/-/serverless-cloudfront-invalidate-1.3.0.tgz", 329 | "integrity": "sha512-AX/3aFd+U71cUK0ANL8afe8h5E7lBhma7coJMSfiUlvUvdsGVMWIbiDmiqSBqO4MXwRQKeegLPuOJ9NPHZc52A==", 330 | "dev": true, 331 | "requires": { 332 | "aws-sdk": "^2.224.1", 333 | "chalk": "^2.3.1", 334 | "randomstring": "^1.1.5" 335 | }, 336 | "dependencies": { 337 | "aws-sdk": { 338 | "version": "2.441.0", 339 | "resolved": "https://registry.npmjs.org/aws-sdk/-/aws-sdk-2.441.0.tgz", 340 | "integrity": "sha512-PnS2lih7p6sPJYUeUSxab7VNsldcHEsCJddHXnnAZRxd2nVa8pAAbPSAauJIN9E6Z4DBhvX3nuQjj+roP/KBTg==", 341 | "dev": true, 342 | "requires": { 343 | "buffer": "4.9.1", 344 | "events": "1.1.1", 345 | "ieee754": "1.1.8", 346 | "jmespath": "0.15.0", 347 | "querystring": "0.2.0", 348 | "sax": "1.2.1", 349 | "url": "0.10.3", 350 | "uuid": "3.3.2", 351 | "xml2js": "0.4.19" 352 | } 353 | }, 354 | "ieee754": { 355 | "version": "1.1.8", 356 | "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.1.8.tgz", 357 | "integrity": "sha1-vjPUCsEO8ZJnAfbwii2G+/0a0+Q=", 358 | "dev": true 359 | }, 360 | "uuid": { 361 | "version": "3.3.2", 362 | "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", 363 | "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==", 364 | "dev": true 365 | }, 366 | "xml2js": { 367 | "version": "0.4.19", 368 | "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.19.tgz", 369 | "integrity": "sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q==", 370 | "dev": true, 371 | "requires": { 372 | "sax": ">=0.6.0", 373 | "xmlbuilder": "~9.0.1" 374 | } 375 | }, 376 | "xmlbuilder": { 377 | "version": "9.0.7", 378 | "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz", 379 | "integrity": "sha1-Ey7mPS7FVlxVfiD0wi35rKaGsQ0=", 380 | "dev": true 381 | } 382 | } 383 | }, 384 | "serverless-pseudo-parameters": { 385 | "version": "2.4.0", 386 | "resolved": "https://registry.npmjs.org/serverless-pseudo-parameters/-/serverless-pseudo-parameters-2.4.0.tgz", 387 | "integrity": "sha512-lb9R62PUFdEAbbYH7pe1wzR7vtIpa8YI8OVcQ5LlLyE0+AxWG4bwEw33X5LE8+5oLwTy57Y/EevnxKnMeyiXxw==", 388 | "dev": true 389 | }, 390 | "serverless-s3-sync": { 391 | "version": "1.8.0", 392 | "resolved": "https://registry.npmjs.org/serverless-s3-sync/-/serverless-s3-sync-1.8.0.tgz", 393 | "integrity": "sha512-WD937VPDITWsXpGpvLKHBJf7/4vAwbHPEhK1NJxsAhPq0I5ZA6dNw28qtBJLri9bwM1Zx3zZ7dsrhKHkPjDMgg==", 394 | "dev": true, 395 | "requires": { 396 | "@auth0/s3": "^1.0.0", 397 | "bluebird": "^3.5.4", 398 | "chalk": "^2.4.2", 399 | "minimatch": "^3.0.4" 400 | } 401 | }, 402 | "serverless-stack-output": { 403 | "version": "0.2.3", 404 | "resolved": "https://registry.npmjs.org/serverless-stack-output/-/serverless-stack-output-0.2.3.tgz", 405 | "integrity": "sha512-bJUUXJ+bc0E+IBlWz+FyUpdNjEmSM0dYd2UpDX0h2zeW+luPOJeP//rbIamBmteJjbed9S3FtRWnLLRAJbzM5g==", 406 | "dev": true, 407 | "requires": { 408 | "tomlify-j0.4": "^2.0.0", 409 | "yamljs": "^0.3.0" 410 | } 411 | }, 412 | "sprintf-js": { 413 | "version": "1.0.3", 414 | "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", 415 | "integrity": "sha1-BOaSb2YolTVPPdAVIDYzuFcpfiw=", 416 | "dev": true 417 | }, 418 | "streamsink": { 419 | "version": "1.2.0", 420 | "resolved": "https://registry.npmjs.org/streamsink/-/streamsink-1.2.0.tgz", 421 | "integrity": "sha1-76/unx4i01ke1949yqlcP1559zw=", 422 | "dev": true 423 | }, 424 | "supports-color": { 425 | "version": "5.5.0", 426 | "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", 427 | "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", 428 | "dev": true, 429 | "requires": { 430 | "has-flag": "^3.0.0" 431 | } 432 | }, 433 | "tomlify-j0.4": { 434 | "version": "2.2.1", 435 | "resolved": "https://registry.npmjs.org/tomlify-j0.4/-/tomlify-j0.4-2.2.1.tgz", 436 | "integrity": "sha512-0kCocYX8ujnbK6jQ9e+g9GLiCIfVkFaCB3DCTQDP7J79gPVZVmZgQZ/KUNe1a6hUfrmHHaErVGUjedfpaX5EZw==", 437 | "dev": true 438 | }, 439 | "url": { 440 | "version": "0.10.3", 441 | "resolved": "https://registry.npmjs.org/url/-/url-0.10.3.tgz", 442 | "integrity": "sha1-Ah5NnHcF8hu/N9A861h2dAJ3TGQ=", 443 | "dev": true, 444 | "requires": { 445 | "punycode": "1.3.2", 446 | "querystring": "0.2.0" 447 | } 448 | }, 449 | "uuid": { 450 | "version": "3.3.2", 451 | "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", 452 | "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==", 453 | "dev": true 454 | }, 455 | "wrappy": { 456 | "version": "1.0.2", 457 | "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", 458 | "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=", 459 | "dev": true 460 | }, 461 | "xml2js": { 462 | "version": "0.4.19", 463 | "resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.4.19.tgz", 464 | "integrity": "sha512-esZnJZJOiJR9wWKMyuvSE1y6Dq5LCuJanqhxslH2bxM6duahNZ+HMpCLhBQGZkbX6xRf8x1Y2eJlgt2q3qo49Q==", 465 | "dev": true, 466 | "requires": { 467 | "sax": ">=0.6.0", 468 | "xmlbuilder": "~9.0.1" 469 | } 470 | }, 471 | "xmlbuilder": { 472 | "version": "9.0.7", 473 | "resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-9.0.7.tgz", 474 | "integrity": "sha1-Ey7mPS7FVlxVfiD0wi35rKaGsQ0=", 475 | "dev": true 476 | }, 477 | "yamljs": { 478 | "version": "0.3.0", 479 | "resolved": "https://registry.npmjs.org/yamljs/-/yamljs-0.3.0.tgz", 480 | "integrity": "sha512-C/FsVVhht4iPQYXOInoxUM/1ELSf9EsgKH34FofQOp6hwCPrW4vG4w5++TED3xRUo8gD7l0P1J1dLlDYzODsTQ==", 481 | "dev": true, 482 | "requires": { 483 | "argparse": "^1.0.7", 484 | "glob": "^7.0.5" 485 | } 486 | } 487 | } 488 | } 489 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "aws-fullstack-website", 3 | "version": "0.1.0", 4 | "description": "Deploy your fullstack websites without all the hassle on AWS with CloudFront, S3, ACM, Route53, API Gateway and Lambda via Serverless", 5 | "scripts": { 6 | "test": "echo \"Error: no test specified\" && exit 1" 7 | }, 8 | "repository": { 9 | "type": "git", 10 | "url": "git@github.com:tobilg/aws-fullstack-website.git" 11 | }, 12 | "author": "TobiLG ", 13 | "license": "MIT", 14 | "bugs": { 15 | "url": "https://github.com/tobilg/aws-fullstack-website/issues" 16 | }, 17 | "homepage": "https://github.com/tobilg/aws-fullstack-website#readme", 18 | "devDependencies": { 19 | "serverless-cloudfront-invalidate": "^1.3.0", 20 | "serverless-pseudo-parameters": "^2.4.0", 21 | "serverless-s3-sync": "^1.8.0", 22 | "serverless-stack-output": "^0.2.3" 23 | }, 24 | "dependencies": { 25 | "lambda-api": "^0.10.2" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /resources/api-gw-basepath-mapping.yml: -------------------------------------------------------------------------------- 1 | Resources: 2 | ApiBasePathMapping: 3 | Type: AWS::ApiGateway::BasePathMapping 4 | DependsOn: 5 | - ApiGatewayRestApi 6 | - ApiDomainName 7 | Properties: 8 | BasePath: '' 9 | DomainName: 'api.${opt:domain}' 10 | RestApiId: 11 | Ref: ApiGatewayRestApi 12 | Stage: ${self:provider.stage} -------------------------------------------------------------------------------- /resources/api-gw-domain-name.yml: -------------------------------------------------------------------------------- 1 | Resources: 2 | ApiDomainName: 3 | Type: AWS::ApiGateway::DomainName 4 | Properties: 5 | CertificateArn: '#{SSLCertificate}' 6 | DomainName: 'api.${opt:domain}' 7 | -------------------------------------------------------------------------------- /resources/api-gw.yml: -------------------------------------------------------------------------------- 1 | # Create the API Gateway instance 2 | # See https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-apigateway-resource.html 3 | Resources: 4 | ApiGatewayRestApi: 5 | Type: AWS::ApiGateway::RestApi 6 | Properties: 7 | Name: '${self:custom.domainName} API' 8 | EndpointConfiguration: 9 | Types: 10 | - ${self:custom.endpointType} -------------------------------------------------------------------------------- /resources/certificate.yml: -------------------------------------------------------------------------------- 1 | Resources: 2 | SSLCertificate: 3 | Type: 'Custom::DNSCertificate' 4 | DependsOn: 5 | - HostedZone 6 | Properties: 7 | DomainName: '${opt:domain}' 8 | SubjectAlternativeNames: 9 | - 'www.${opt:domain}' 10 | - 'api.${opt:domain}' 11 | ValidationMethod: DNS 12 | # Needs to be in us-east-1 because of CloudFront limitations 13 | Region: us-east-1 14 | DomainValidationOptions: 15 | - DomainName: '${opt:domain}' 16 | HostedZoneId: '#{HostedZone}' 17 | ServiceToken: '#{CustomAcmCertificateLambda.Arn}' 18 | -------------------------------------------------------------------------------- /resources/cf-distribution.yml: -------------------------------------------------------------------------------- 1 | # See https://blog.m-taylor.co.uk/2018/01/cloudformation-template-for-a-cloudfront-enabled-s3-website.html 2 | Resources: 3 | CFDistribution: 4 | Type: 'AWS::CloudFront::Distribution' 5 | DependsOn: 6 | - WebsiteBucket 7 | - HostedZone 8 | - SSLCertificate 9 | - CloudFrontOriginAccessIdentity 10 | Properties: 11 | DistributionConfig: 12 | Aliases: 13 | - '${opt:domain}' 14 | - 'www.${opt:domain}' 15 | Origins: 16 | - DomainName: '#{WebsiteBucket.DomainName}' 17 | OriginPath: '' 18 | Id: S3BucketOrigin 19 | S3OriginConfig: 20 | OriginAccessIdentity: 21 | Fn::Join: 22 | - '' 23 | - - 'origin-access-identity/cloudfront/' 24 | - '#{CloudFrontOriginAccessIdentity}' 25 | Comment: 'CloudFront origin for ${opt:domain}' 26 | DefaultCacheBehavior: 27 | AllowedMethods: 28 | - GET 29 | - HEAD 30 | - OPTIONS 31 | TargetOriginId: S3BucketOrigin 32 | ForwardedValues: 33 | QueryString: 'false' 34 | Cookies: 35 | Forward: none 36 | ViewerProtocolPolicy: redirect-to-https 37 | DefaultRootObject: index.html 38 | Enabled: 'true' 39 | HttpVersion: 'http2' 40 | PriceClass: 'PriceClass_100' 41 | ViewerCertificate: 42 | AcmCertificateArn: '#{SSLCertificate}' 43 | SslSupportMethod: sni-only -------------------------------------------------------------------------------- /resources/cloudfront-origin-access-identity.yml: -------------------------------------------------------------------------------- 1 | Resources: 2 | CloudFrontOriginAccessIdentity: 3 | Type: 'AWS::CloudFront::CloudFrontOriginAccessIdentity' 4 | Properties: 5 | CloudFrontOriginAccessIdentityConfig: 6 | Comment: '${self:service.name}-oai' -------------------------------------------------------------------------------- /resources/custom-acm-certificate-lambda-role.yml: -------------------------------------------------------------------------------- 1 | Resources: 2 | CustomAcmCertificateLambdaExecutionRole: 3 | Type: 'AWS::IAM::Role' 4 | Properties: 5 | AssumeRolePolicyDocument: 6 | Statement: 7 | - Action: 8 | - sts:AssumeRole 9 | Effect: Allow 10 | Principal: 11 | Service: lambda.amazonaws.com 12 | Version: '2012-10-17' 13 | ManagedPolicyArns: 14 | - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole 15 | - arn:aws:iam::aws:policy/service-role/AWSLambdaRole 16 | Policies: 17 | - PolicyDocument: 18 | Statement: 19 | - Action: 20 | - acm:AddTagsToCertificate 21 | - acm:DeleteCertificate 22 | - acm:DescribeCertificate 23 | - acm:RemoveTagsFromCertificate 24 | Effect: Allow 25 | Resource: 26 | - 'arn:aws:acm:*:#{AWS::AccountId}:certificate/*' 27 | - Action: 28 | - acm:RequestCertificate 29 | - acm:ListTagsForCertificate 30 | - acm:ListCertificates 31 | Effect: Allow 32 | Resource: 33 | - '*' 34 | - Action: 35 | - route53:ChangeResourceRecordSets 36 | Effect: Allow 37 | Resource: 38 | - arn:aws:route53:::hostedzone/* 39 | Version: '2012-10-17' 40 | PolicyName: 'CustomAcmCertificateLambdaExecutionPolicy-${self:service.name}' 41 | -------------------------------------------------------------------------------- /resources/custom-acm-certificate-lambda.yml: -------------------------------------------------------------------------------- 1 | Resources: 2 | CustomAcmCertificateLambda: 3 | Type: 'AWS::Lambda::Function' 4 | Metadata: 5 | Source: https://github.com/dflook/cloudformation-dns-certificate 6 | Version: 1.7.1 7 | Properties: 8 | Description: Cloudformation custom resource for DNS validated certificates 9 | Handler: index.handler 10 | Role: '#{CustomAcmCertificateLambdaExecutionRole.Arn}' 11 | Runtime: python3.6 12 | Timeout: 900 13 | Code: 14 | ZipFile: "T=RuntimeError\nimport copy,hashlib as t,json,logging as B,time\ 15 | \ as b\nfrom boto3 import client as K\nfrom botocore.exceptions import ClientError\ 16 | \ as u,ParamValidationError as v\nfrom botocore.vendored import requests\ 17 | \ as w\nA=B.getLogger()\nA.setLevel(B.INFO)\nD=A.info\nS=A.exception\nd=json.dumps\n\ 18 | 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\ 19 | \tdef g():\n\t\tD=M(B)\n\t\tfor H in ['ServiceToken',m,F,n]:D.pop(H,X)\n\ 20 | \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\ 21 | \t\t\t\tdel D[N]\n\t\tA[C]=E.request_certificate(IdempotencyToken=y,**D)[G];l()\n\ 22 | \tdef U(a):\n\t\twhile O:\n\t\t\ttry:E.delete_certificate(**{G:a});return\n\ 23 | \t\t\texcept u as B:\n\t\t\t\tS(P);A=B.response['Error']['Code']\n\t\t\t\ 24 | \tif A=='ResourceInUseException':\n\t\t\t\t\tif f()/1000<30:raise\n\t\t\t\ 25 | \t\te(5);continue\n\t\t\t\tif A in['ResourceNotFoundException','ValidationException']:return\n\ 26 | \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\ 27 | \t\t\tfor B in J['CertificateSummaryList']:\n\t\t\t\tD(B);C={A[Q]:A[H]for\ 28 | \ A in E.list_tags_for_certificate(**{G:B[G]})[F]}\n\t\t\t\tif C.get(I+A1)==A[q]and\ 29 | \ C.get(I+A2)==A[Y]and C.get(I+A3)==hash(props):return B[G]\n\tdef h():\n\ 30 | \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\ 31 | \tdef i():\n\t\twhile f()/1000>30:\n\t\t\tB=E.describe_certificate(**{G:A[C]})[r];D(B)\n\ 32 | \t\t\tif B[R]=='ISSUED':return O\n\t\t\telif B[R]==A4:raise T(B.get('FailureReason',P))\n\ 33 | \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\ 34 | \ B!=C\n\tdef j():\n\t\tW='Type';V='Name';U='HostedZoneId';T='ValidationStatus';S='PENDING_VALIDATION';L='ResourceRecord'\n\ 35 | \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\ 36 | \t\t\tif I[R]!=S:return\n\t\t\tif not[A for A in I.get(N,[{}])if T not in\ 37 | \ A or L not in A]:break\n\t\t\tb.sleep(1)\n\t\tfor F in I[N]:\n\t\t\tif\ 38 | \ 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\ 39 | \ 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\ 40 | \ 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\ 41 | \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\ 42 | \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\ 43 | \t\traise T(N+' missing'+' for '+n)\n\thash=lambda v:t.new('md5',d(v,sort_keys=O).encode()).hexdigest()\n\ 44 | \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\ 45 | \tdef W():D(A);B=w.put(A['ResponseURL'],json=A,headers={'content-type':P});B.raise_for_status()\n\ 46 | \ttry:\n\t\ty=hash(A['RequestId']+A[Y]);B=A[J];E=K(A5,region_name=B.get(m));A[R]='SUCCESS'\n\ 47 | \t\tif A[a]=='Create':\n\t\t\tif A.get(Z,L)is L:A[C]=A6;g()\n\t\t\tj()\n\ 48 | \t\t\tif not i():return h()\n\t\telif A[a]==A7:\n\t\t\tif A[C]!=A6:\n\t\t\ 49 | \t\tif A[C].startswith('arn:'):U(A[C])\n\t\t\t\telse:U(V(B))\n\t\telif A[a]==A8:\n\ 50 | \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\ 51 | \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\ 52 | \t\t\t\tj()\n\t\t\t\tif not i():return h()\n\t\t\telse:\n\t\t\t\tif F in\ 53 | \ A[s+J]:E.remove_tags_from_certificate(**{G:A[C],F:A[s+J][F]})\n\t\t\t\t\ 54 | 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\ 55 | \ W()" 56 | -------------------------------------------------------------------------------- /resources/dns-records.yml: -------------------------------------------------------------------------------- 1 | # See RecordSet: https://docs.aws.amazon.com/de_de/AWSCloudFormation/latest/UserGuide/aws-properties-route53-recordset.html 2 | # See AliasTarget: https://docs.aws.amazon.com/de_de/AWSCloudFormation/latest/UserGuide/aws-properties-route53-aliastarget.html 3 | # 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) 4 | Resources: 5 | DnsRecord: 6 | Type: 'AWS::Route53::RecordSet' 7 | DependsOn: 8 | - HostedZone 9 | Properties: 10 | Comment: 'Alias CloudFront for ${opt:domain}' 11 | HostedZoneId: '#{HostedZone}' 12 | Type: A 13 | Name: '${opt:domain}' 14 | AliasTarget: 15 | # Generated domain name from CloudFront 16 | DNSName: '#{CFDistribution.DomainName}' 17 | # Default (static) hosted zone for CloudFront 18 | HostedZoneId: 'Z2FDTNDATAQYW2' 19 | WWWDnsRecord: 20 | Type: 'AWS::Route53::RecordSet' 21 | DependsOn: 22 | - HostedZone 23 | Properties: 24 | Comment: 'Alias CloudFront for www.${opt:domain}' 25 | HostedZoneId: '#{HostedZone}' 26 | Type: A 27 | Name: 'www.${opt:domain}' 28 | AliasTarget: 29 | # Generated domain name from CloudFront 30 | DNSName: '#{CFDistribution.DomainName}' 31 | # Default (static) hosted zone for CloudFront 32 | HostedZoneId: 'Z2FDTNDATAQYW2' 33 | ApiDnsRecord: 34 | Type: 'AWS::Route53::RecordSet' 35 | Properties: 36 | Comment: 'API subdomain for ${opt:domain}' 37 | HostedZoneId: '#{HostedZone}' 38 | Type: A 39 | Name: 'api.${opt:domain}' 40 | AliasTarget: 41 | HostedZoneId: '#{ApiDomainName.DistributionHostedZoneId}' 42 | DNSName: '#{ApiDomainName.DistributionDomainName}' -------------------------------------------------------------------------------- /resources/hosted-zone.yml: -------------------------------------------------------------------------------- 1 | # See https://docs.aws.amazon.com/de_de/AWSCloudFormation/latest/UserGuide/aws-resource-route53-hostedzone.html 2 | Resources: 3 | HostedZone: 4 | Type: 'AWS::Route53::HostedZone' 5 | Properties: 6 | HostedZoneConfig: 7 | Comment: 'Hosted zone for ${opt:domain}' 8 | Name: '${opt:domain}' -------------------------------------------------------------------------------- /resources/outputs.yml: -------------------------------------------------------------------------------- 1 | Outputs: 2 | CloudFrontDistributionId: 3 | Description: CloudFront distribution id 4 | Value: 5 | Ref: CFDistribution 6 | HostedZoneNameservers: 7 | Description: The nameservers for the Hosted Zone (to be used with your external DNS configuration) 8 | Value: 9 | 'Fn::Join': 10 | - ', ' 11 | - 'Fn::GetAtt': ['HostedZone', 'NameServers'] -------------------------------------------------------------------------------- /resources/s3-bucket.yml: -------------------------------------------------------------------------------- 1 | Resources: 2 | WebsiteBucket: 3 | Type: 'AWS::S3::Bucket' 4 | Properties: 5 | BucketName: ${opt:domain} 6 | -------------------------------------------------------------------------------- /resources/s3-policies.yml: -------------------------------------------------------------------------------- 1 | Resources: 2 | WebsiteBucketPolicy: 3 | Type: AWS::S3::BucketPolicy 4 | DependsOn: 5 | - WebsiteBucket 6 | Properties: 7 | Bucket: 8 | Ref: WebsiteBucket 9 | PolicyDocument: 10 | Statement: 11 | - Sid: PublicReadGetObject 12 | Effect: Allow 13 | Principal: 14 | AWS: 15 | Fn::Join: 16 | - ' ' 17 | - - 'arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity' 18 | - '#{CloudFrontOriginAccessIdentity}' 19 | Action: 20 | - s3:GetObject 21 | Resource: 22 | - Fn::Join: [ 23 | '', [ 24 | 'arn:aws:s3:::', 25 | { 26 | 'Ref': 'WebsiteBucket' 27 | }, 28 | '/*' 29 | ] 30 | ] 31 | -------------------------------------------------------------------------------- /serverless.yml: -------------------------------------------------------------------------------- 1 | service: 2 | name: ${file(./modules/sanitizeStackName.js):sanitize} 3 | 4 | plugins: 5 | - serverless-s3-sync 6 | - serverless-pseudo-parameters 7 | - serverless-stack-output 8 | - serverless-cloudfront-invalidate 9 | 10 | custom: 11 | 12 | # The domain name to be used 13 | domainName: ${opt:domain} 14 | 15 | # API base path 16 | basePath: 'v1' 17 | 18 | # API endpoint type 19 | endpointType: 'EDGE' 20 | 21 | # API Gateway settings 22 | apiGateway: 23 | # See https://docs.aws.amazon.com/general/latest/gr/rande.html#apigateway_region 24 | hostedZone: 'Z2FDTNDATAQYW2' 25 | 26 | # Output plugin configuration 27 | output: 28 | handler: modules/output.handler 29 | 30 | # CloudFront invalidation plugin configuration 31 | cloudfrontInvalidate: 32 | distributionIdKey: 'CloudFrontDistributionId' 33 | items: # Add your files to invalidate here: 34 | - '/index.html' 35 | 36 | # S3 sync plugin configuration 37 | s3Sync: 38 | - bucketName: ${opt:domain} 39 | localDir: website 40 | 41 | provider: 42 | name: aws 43 | runtime: nodejs10.x 44 | region: ${opt:region, 'us-east-1'} 45 | # API Gateway settings 46 | apiGateway: 47 | restApiId: '#{ApiGatewayRestApi}' 48 | restApiRootResourceId: '#{ApiGatewayRestApi.RootResourceId}' 49 | 50 | functions: 51 | api: 52 | handler: api/baseApi.router 53 | memorySize: 256 54 | timeout: 5 55 | environment: 56 | AWS_NODEJS_CONNECTION_REUSE_ENABLED: '1' # Enable HTTP keep-alive connections for the AWS SDK 57 | DOMAIN_NAME: '${self:custom.domainName}' 58 | BASE_PATH: '${self:custom.basePath}' 59 | events: 60 | - http: 61 | path: '{proxy+}' 62 | method: any 63 | 64 | resources: 65 | - ${file(resources/api-gw.yml)} 66 | - ${file(resources/api-gw-basepath-mapping.yml)} 67 | - ${file(resources/api-gw-domain-name.yml)} 68 | - ${file(resources/custom-acm-certificate-lambda.yml)} 69 | - ${file(resources/custom-acm-certificate-lambda-role.yml)} 70 | - ${file(resources/cloudfront-origin-access-identity.yml)} 71 | - ${file(resources/s3-bucket.yml)} 72 | - ${file(resources/s3-policies.yml)} 73 | - ${file(resources/hosted-zone.yml)} 74 | - ${file(resources/dns-records.yml)} 75 | - ${file(resources/certificate.yml)} 76 | - ${file(resources/cf-distribution.yml)} 77 | - ${file(resources/outputs.yml)} 78 | 79 | package: 80 | exclude: 81 | - docs/** 82 | - modules/** 83 | - resources/** 84 | - website/** 85 | - LICENSE 86 | - README.md 87 | -------------------------------------------------------------------------------- /website/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 |

Welcome to my static website!

4 | 5 | --------------------------------------------------------------------------------