├── .gitignore ├── LICENSE ├── README.md ├── images └── architecture.jpg ├── index.js ├── install.sh └── serverless.cfn.yml /.gitignore: -------------------------------------------------------------------------------- 1 | # AWS SAM artifacts 2 | serverless-xfm.cfn.yml 3 | awscli-bundle/ 4 | 5 | # zip files 6 | *.zip 7 | 8 | .idea 9 | *.iml 10 | 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AWS Startup Kit Serverless Workload 2 | 3 | An example serverless application project: a RESTful API backed by DynamoDB. The architecture is as follows: 4 | 5 | ![Architecture](images/architecture.jpg) 6 | 7 | More specifically, components include multiple AWS Lambda functions, Amazon API Gateway, and an Amazon DynamoDB table. The project uses the Lambda Node.js runtime. It generally follows the ECMAScript 6 standard, and the Lambda function handlers are implemented using the async/await pattern introduced along with the Lambda Node.js 8.10 runtime. The AWS Serverless Application Model (SAM) is used to deploy the project. 8 | 9 | ## LAUNCHING THE APP ON AWS 10 | 11 | ### Prerequisites 12 | 13 | - [Install the AWS CLI](http://docs.aws.amazon.com/cli/latest/userguide/installing.html), or update 14 | the version you have installed previously (some commands used here may not 15 | exist in older versions of the AWS CLI). 16 | 17 | - [Create an IAM user with admin access](http://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html). 18 | The IAM user you associate with the AWS CLI should have admin permissions, including the ability to create IAM roles. 19 | 20 | - [Configure the AWS CLI to use the admin user](http://docs.aws.amazon.com/cli/latest/reference/configure/) 21 | 22 | 23 | To begin your deployment, either download a zip file of the code from GitHub (via the green button above), or clone the GitHub repository with the command: 24 | 25 | ``` 26 | 27 | git clone https://github.com/aws-samples/startup-kit-serverless-workload.git 28 | 29 | ``` 30 | 31 | 32 | ### Deployment Via Installation Script 33 | 34 | You can use the installation script to deploy the app, or continue to the manual deployment section below to gain insight regarding what's happening under the hood. 35 | 36 | The installation script (install.sh) is in the code you downloaded or cloned from this GitHub repository. First make sure you can execute the script. Using the command line, grant execution permissions for the script file by running the following command: 37 | 38 | ``` 39 | 40 | chmod +x install.sh 41 | 42 | ``` 43 | 44 | Then you can run the installation script: 45 | 46 | ``` 47 | 48 | ./install.sh 49 | 50 | ``` 51 | 52 | That's it! Your Startup Kit Serverless Workload is now fully deployed and ready to be tested. To test it, try the curl commands output by the installation script. See the **TESTING AND CORS** section below for further testing options and CORS details. 53 | 54 | 55 | ### Manual Deployment 56 | 57 | To understand the steps involved in an AWS SAM deployment, deploy the workload 58 | manually. Once you have a S3 bucket in place to hold deployment artifacts, the 59 | workflow for using AWS SAM primarily consists of using just two AWS CLI commands. 60 | 61 | In the AWS Region where you plan to do your deployment, be sure you have an 62 | existing Amazon S3 bucket in which SAM can put the deployment artifacts, or 63 | create a new bucket using the following AWS CLI command: 64 | 65 | ``` 66 | 67 | aws s3 mb s3://. 68 | 69 | ``` 70 | 71 | Next, to deploy the project for the first time with SAM, and for each subsequent 72 | code update, run both of the following AWS CLI commands in order. For the 73 | first command, package, replace the s3-bucket argument with the name of your 74 | S3 bucket. For the second command, deploy, replace the template-file argument 75 | with the full path to your output template file. 76 | 77 | ``` 78 | 79 | aws cloudformation package \ 80 | --template-file serverless.cfn.yml \ 81 | --output-template-file serverless-xfm.cfn.yml \ 82 | --s3-bucket 83 | 84 | aws cloudformation deploy \ 85 | --template-file \ 86 | --stack-name StartupKitServerless \ 87 | --capabilities CAPABILITY_IAM 88 | 89 | ``` 90 | 91 | 92 | ### AWS Cloud9 93 | 94 | When you are working with a non-sample serverless application, you might consider using AWS Cloud9 to help manage your serverless application project. Cloud9 is a cloud-based integrated development environment (IDE) that lets you write, run, and debug your code with just a browser. It has the AWS CLI pre-installed so you don’t need to install files or configure your laptop to use the AWS CLI. You can use Cloud9 to work with AWS Lambda functions and their related Amazon API Gateway APIs in a Cloud9 development environment. It enables easy local testing of Lambda functions as well as one-click remote deployment of Lambda functions. For more details, see https://docs.aws.amazon.com/cloud9/latest/user-guide/lambda-functions.html. 95 | 96 | 97 | ## TESTING AND CORS 98 | 99 | ### Testing From the Command Line 100 | 101 | First get the invoke URL of your API. If you did not use the installation script, do this by going to the API Gateway console, selecting the StartupKitServerless API, then **Stages** in the left navigation panel, and finally **Stage** in the list of stages. The invoke URL should now appear at the top of the right hand panel. 102 | 103 | Begin testing by adding some TODO items using the create API. This may be 104 | accomplished using the following command: 105 | 106 | ``` 107 | 108 | curl -X POST -H 'Content-Type: application/json' -d '{"todo_id": "1001", "active": true, "description": "What TODO next?"}' https:///todo/new 109 | 110 | ``` 111 | 112 | To fetch the active TODO items you created, execute the following command: 113 | 114 | ``` 115 | 116 | curl https:///todo/active 117 | 118 | ``` 119 | 120 | Similar commands can be used to test all of the other API calls. 121 | 122 | 123 | ### Testing From A Front End With CORS Enbabled 124 | 125 | Without CORS enabled, the API should work fine with a mobile client such as iOS or Android. The API also should work when called from a server. However, unless CORS is enabled, the API will not work with a web front end due to CORS. 126 | 127 | By default, CORS is enabled for this project. This involves two files: serverless.cfn.yml, and the source code file index.js. In serverless.cfn.yml, the Globals section has a **Cors** property under **Api** to enable CORS. In index.js, the **createResponse** function returns an Access-Control-Allow-Origin header. To disable CORS, remove this code. If you retain CORS enablement for a real world project, it is a best practice to replace the domain name-related wildcards in both files with a specific domain name. 128 | 129 | 130 | ## CLEAN UP 131 | 132 | If you do not need to retain the workload created by this project, you can delete the resources associated with it. To do so, go to the AWS console and select the **AWS CloudFormation** service from the list of AWS services. Inside the CloudFormation console, examine the table of stacks. Find the stack named ```StartupKitServerlessWorkload```, click the check box next to it, then select **Delete Stack** from the **Actions** drop down menu above the stack table. 133 | 134 | 135 | -------------------------------------------------------------------------------- /images/architecture.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/aws-samples/startup-kit-serverless-workload/c0527fdda1bca293ce80a8a256f6dc8150a7f05d/images/architecture.jpg -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | 4 | const AWS = require('aws-sdk'); 5 | const dynamo = new AWS.DynamoDB.DocumentClient(); 6 | const tableName = process.env.TABLE_NAME; 7 | 8 | // API Gateway's Lambda proxy integration requires a 9 | // Lambda function to return JSON in this format; 10 | // see the Developer Guide for further details 11 | const createResponse = (statusCode, body) => { 12 | 13 | // to restrict the origin for CORS purposes, replace the wildcard 14 | // origin with a specific domain name 15 | return { 16 | statusCode: statusCode, 17 | body: body, 18 | headers: { 19 | 'Content-Type': 'application/json', 20 | 'Access-Control-Allow-Origin': '*' 21 | } 22 | } 23 | }; 24 | 25 | 26 | // API call to create a TODO item 27 | 28 | exports.create = async (event) => { 29 | 30 | let params = { 31 | TableName: tableName, 32 | Item: JSON.parse(event.body) 33 | }; 34 | let data; 35 | 36 | try { 37 | data = await dynamo.put(params).promise(); 38 | } 39 | catch(err) { 40 | console.log(`CREATE ITEM FAILED FOR todo_id = ${params.Item.todo_id}, WITH ERROR: ${err}`); 41 | return createResponse(500, err); 42 | } 43 | 44 | console.log(`CREATE ITEM SUCCEEDED FOR todo_id = ${params.Item.todo_id}`); 45 | return createResponse(200, `TODO item created with todo_id = ${params.Item.todo_id}\n`); 46 | }; 47 | 48 | 49 | // API call to retrieve all TODO items 50 | 51 | exports.getAll = async (event) => { 52 | 53 | let params = { 54 | TableName: tableName 55 | }; 56 | let data; 57 | 58 | try { 59 | data = await dynamo.scan(params).promise(); 60 | } 61 | catch(err) { 62 | console.log(`GET ALL ITEMS FAILED, WITH ERROR: ${err}`); 63 | return createResponse(500, err); 64 | } 65 | 66 | if (!data.Items) { 67 | console.log('NO ITEMS FOUND FOR GET ALL API CALL'); 68 | return createResponse(404, 'ITEMS NOT FOUND\n'); 69 | } 70 | 71 | console.log(`RETRIEVED ALL ITEMS SUCCESSFULLY WITH count = ${data.Count}`); 72 | return createResponse(200, JSON.stringify(data.Items) + '\n'); 73 | }; 74 | 75 | 76 | // API calls related to active TODO items 77 | 78 | exports.getActive = async (event) => { 79 | 80 | let params = { 81 | TableName: tableName, 82 | FilterExpression : 'active = :active', 83 | ExpressionAttributeValues : {':active' : true} 84 | }; 85 | let data; 86 | 87 | try { 88 | data = await dynamo.scan(params).promise(); 89 | } 90 | catch(err) { 91 | console.log(`GET ACTIVE ITEMS FAILED, WITH ERROR: ${err}`); 92 | return createResponse(500, err); 93 | } 94 | 95 | if (!data.Items) { 96 | console.log('NO ACTIVE ITEMS FOUND FOR GET ACTIVE API CALL'); 97 | return createResponse(404, 'ITEMS NOT FOUND\n'); 98 | } 99 | 100 | console.log(`RETRIEVED ACTIVE ITEMS SUCCESSFULLY WITH count = ${data.Count}`); 101 | return createResponse(200, JSON.stringify(data.Items) + '\n'); 102 | }; 103 | 104 | 105 | exports.updateActive = async (event) => { 106 | 107 | let params = { 108 | TableName: tableName, 109 | Item: JSON.parse(event.body) 110 | }; 111 | let data; 112 | 113 | try { 114 | data = await dynamo.put(params).promise(); 115 | } 116 | catch(err) { 117 | console.log(`UPDATE ACTIVE FAILED FOR todo_id = ${params.Item.todo_id}, WITH ERROR: ${err}`); 118 | return createResponse(500, err); 119 | } 120 | 121 | console.log(`UPDATE ACTIVE SUCCEEDED FOR todo_id = ${params.Item.todo_id}`); 122 | return createResponse(200, `TODO item updated with todo_id = ${params.Item.todo_id}\n`); 123 | }; 124 | 125 | 126 | // API calls related to complete TODO items 127 | 128 | exports.getComplete = async (event) => { 129 | 130 | let params = { 131 | TableName: tableName, 132 | FilterExpression : 'active = :active', 133 | ExpressionAttributeValues : {':active' : false} 134 | }; 135 | let data; 136 | 137 | try { 138 | data = await dynamo.scan(params).promise(); 139 | } 140 | catch(err) { 141 | console.log(`GET COMPLETE ITEMS FAILED, WITH ERROR: ${err}`); 142 | return createResponse(500, err); 143 | } 144 | 145 | if (!data.Items) { 146 | console.log('NO ITEMS FOUND FOR GET COMPLETE API CALL'); 147 | return createResponse(404, 'COMPLETE ITEMS NOT FOUND\n'); 148 | } 149 | 150 | console.log(`RETRIEVED COMPLETE ITEMS SUCCESSFULLY WITH count = ${data.Count}`); 151 | return createResponse(200, JSON.stringify(data.Items) + '\n'); 152 | }; 153 | 154 | 155 | exports.markComplete = async (event) => { 156 | 157 | let item = JSON.parse(event.body); 158 | item.active = false; 159 | 160 | let params = { 161 | TableName: tableName, 162 | Item: item 163 | }; 164 | let data; 165 | 166 | try { 167 | data = await dynamo.put(params).promise(); 168 | } 169 | catch(err) { 170 | console.log(`MARK COMPLETE FAILED FOR todo_id = ${item.todo_id}, WITH ERROR: ${err}`); 171 | return createResponse(500, err); 172 | } 173 | 174 | console.log(`MARK COMPLETE SUCCEEDED FOR todo_id = ${item.todo_id}`); 175 | return createResponse(200, `TODO item marked complete with todo_id = ${item.todo_id}\n`); 176 | }; 177 | 178 | 179 | exports.deleteComplete = async (event) => { 180 | 181 | let params = { 182 | TableName: tableName, 183 | FilterExpression : 'active = :active', 184 | ExpressionAttributeValues : {':active' : false} 185 | }; 186 | let data; 187 | 188 | // there is no batch delete in the AWS SDK for DynamoDB, 189 | // so we must delete completed items one by one 190 | try { 191 | data = await dynamo.scan(params).promise(); 192 | } 193 | catch(err) { 194 | console.log(`GET ITEMS FOR DELETION FAILED, WITH ERROR: ${err}`); 195 | return createResponse(500, err); 196 | } 197 | 198 | if (!data.Items) { 199 | console.log('NO ITEMS FOUND FOR DELETION API CALL'); 200 | return createResponse(404, 'NO ITEMS FOUND FOR DELETION\n'); 201 | } 202 | 203 | console.log(`NUMBER OF ITEMS TO DELETE = ${data.Count}`); 204 | let ids = data.Items.map( (item) => { return item.todo_id; }); 205 | ids.forEach( (id) => deleteIndividualItem(id) ); 206 | return createResponse(200, `${data.Count} items submitted for deletion\n`); 207 | }; 208 | 209 | 210 | function deleteIndividualItem(todoId) { 211 | 212 | let params = { 213 | TableName: tableName, 214 | Key: { 215 | todo_id: todoId 216 | }, 217 | ReturnValues: 'ALL_OLD' 218 | }; 219 | 220 | let dbDelete = (params) => { return dynamo.delete(params).promise() }; 221 | 222 | dbDelete(params).then( (data) => { 223 | if (!data.Attributes) { 224 | console.log(`ITEM NOT FOUND FOR DELETION WITH ID = ${todoId}`); 225 | return; 226 | } 227 | console.log(`DELETED ITEM SUCCESSFULLY WITH id = ${todoId}`); 228 | }).catch( (err) => { 229 | console.log(`DELETE ITEM FAILED FOR id = ${todoId}, WITH ERROR: ${err}`); 230 | }); 231 | 232 | } 233 | 234 | 235 | 236 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DIGITS_RE='^[0-9]+$' 4 | TEMPLATE_FILE_NAME='serverless.cfn.yml' 5 | PACKAGE_FILE_NAME='serverless-xfm.cfn.yml' 6 | STACK_NAME='StartupKitServerlessWorkload' 7 | JSON_CONTENT='{"todo_id": "1001", "active": true, "description": "What TODO next?"}' 8 | 9 | # Check if the aws cli is installed 10 | if ! command -v aws > /dev/null; then 11 | echo "aws cli was not found. Please install before running this script." 12 | exit 1 13 | fi 14 | 15 | ACCOUNT_ID=`aws sts get-caller-identity --query 'Account' --output=text` 16 | REGION=`aws configure get region` 17 | BUCKET_NAME="${ACCOUNT_ID}-${REGION}-startup-kit-serverless-workload" 18 | 19 | # Check if the account id is valid 20 | if ! [[ ${ACCOUNT_ID} =~ ${DIGITS_RE} ]] ; then 21 | echo "Invalid account ID" >&2 22 | exit 1 23 | fi 24 | 25 | # Check if the bucket already exists 26 | BUCKETS_EXISTS=`aws s3 ls | grep ${BUCKET_NAME}` 27 | if [ ! -z "${BUCKETS_EXISTS}" -a "${BUCKETS_EXISTS}" != " " ]; then 28 | echo "Bucket ${BUCKET_NAME} already exists. You can remove it from the AWS S3 console" 29 | echo "https://console.aws.amazon.com/s3/home" 30 | exit 1 31 | fi 32 | 33 | # Try to create the bucket 34 | if aws s3 mb s3://${BUCKET_NAME}; then 35 | echo "Bucket s3://${BUCKET_NAME} created successfully" 36 | else 37 | echo "Failed creating bucket s3://${BUCKET_NAME}" 38 | exit 1 39 | fi 40 | 41 | # Try to create CloudFormation package 42 | if aws cloudformation package --template-file ${TEMPLATE_FILE_NAME} --output-template-file ${PACKAGE_FILE_NAME} --s3-bucket ${BUCKET_NAME}; then 43 | echo "CloudFormation successfully created the package ${PACKAGE_FILE_NAME}" 44 | else 45 | echo "Failed creating CloudFormation package" 46 | exit 1 47 | fi 48 | 49 | # Try to deploy the package 50 | if aws cloudformation deploy --template-file ${PACKAGE_FILE_NAME} --stack-name ${STACK_NAME} --capabilities CAPABILITY_IAM; then 51 | echo "CloudFormation successfully deployed the serverless app package" 52 | else 53 | echo "Failed deploying CloudFormation package" 54 | exit 1 55 | fi 56 | 57 | 58 | REST_API_ID=`aws cloudformation list-stack-resources --stack-name ${STACK_NAME} | grep -A2 'AWS::ApiGateway::RestApi' | grep 'PhysicalResourceId' | awk '{print $2}' | tr -d '"' | tr -d ","` 59 | REST_API_URL="https://${REST_API_ID}.execute-api.${REGION}.amazonaws.com/Stage" 60 | 61 | echo "The rest API url is ${REST_API_URL}" 62 | echo "You can try adding a new to do item by running the following command:" 63 | echo "curl -X POST -H 'Content-Type: application/json' -d '${JSON_CONTENT}' ${REST_API_URL}/todo/new" 64 | echo "" 65 | echo "To fetch the active TODO items you created, execute the following command:" 66 | echo "curl ${REST_API_URL}/todo/active" 67 | -------------------------------------------------------------------------------- /serverless.cfn.yml: -------------------------------------------------------------------------------- 1 | # To deploy for the first time, and for each update, 2 | # run both of the following commands in order: 3 | # 4 | # aws cloudformation package \ 5 | # --template-file serverless.cfn.yml \ 6 | # --output-template-file serverless-xfm.cfn.yml \ 7 | # --s3-bucket 8 | # 9 | # aws cloudformation deploy \ 10 | # --template-file \ 11 | # --stack-name StartupKitServerless \ 12 | # --capabilities CAPABILITY_IAM 13 | 14 | 15 | AWSTemplateFormatVersion: '2010-09-09' 16 | Transform: AWS::Serverless-2016-10-31 17 | Description: Startup Kit RESTful API backed by a SimpleTable (DynamoDB). 18 | 19 | 20 | Globals: 21 | 22 | Function: 23 | Runtime: nodejs14.x 24 | Environment: 25 | Variables: 26 | TABLE_NAME: !Ref Table 27 | 28 | Api: 29 | # enable CORS; to make more specific, change the origin wildcard 30 | # to a particular domain name, e.g. "'www.example.com'" 31 | Cors: 32 | AllowMethods: "'*'" 33 | AllowHeaders: "'*'" 34 | AllowOrigin: "'*'" 35 | 36 | 37 | Resources: 38 | 39 | CreateFunction: 40 | Type: AWS::Serverless::Function 41 | Properties: 42 | Handler: index.create 43 | FunctionName: StartupKitCreateFunction 44 | Policies: AmazonDynamoDBFullAccess 45 | Events: 46 | PostResource: 47 | Type: Api 48 | Properties: 49 | Path: /todo/new 50 | Method: post 51 | 52 | GetAllFunction: 53 | Type: AWS::Serverless::Function 54 | Properties: 55 | Handler: index.getAll 56 | FunctionName: StartupKitGetAllFunction 57 | Policies: AmazonDynamoDBReadOnlyAccess 58 | Events: 59 | GetResource: 60 | Type: Api 61 | Properties: 62 | Path: /todo/all 63 | Method: get 64 | 65 | # API functions related to active TODO items 66 | 67 | GetActiveFunction: 68 | Type: AWS::Serverless::Function 69 | Properties: 70 | Handler: index.getActive 71 | FunctionName: StartupKitGetActiveFunction 72 | Policies: AmazonDynamoDBReadOnlyAccess 73 | Events: 74 | GetResource: 75 | Type: Api 76 | Properties: 77 | Path: /todo/active 78 | Method: get 79 | 80 | UpdateActiveFunction: 81 | Type: AWS::Serverless::Function 82 | Properties: 83 | Handler: index.updateActive 84 | FunctionName: StartupKitUpdateActiveFunction 85 | Policies: AmazonDynamoDBFullAccess 86 | Events: 87 | PutResource: 88 | Type: Api 89 | Properties: 90 | Path: /todo/active 91 | Method: put 92 | 93 | # API functions related to completed TODO items 94 | 95 | GetCompleteFunction: 96 | Type: AWS::Serverless::Function 97 | Properties: 98 | Handler: index.getComplete 99 | FunctionName: StartupKitGetCompleteFunction 100 | Policies: AmazonDynamoDBReadOnlyAccess 101 | Events: 102 | GetResource: 103 | Type: Api 104 | Properties: 105 | Path: /todo/complete 106 | Method: get 107 | 108 | MarkCompleteFunction: 109 | Type: AWS::Serverless::Function 110 | Properties: 111 | Handler: index.markComplete 112 | FunctionName: StartupKitMarkCompleteFunction 113 | Policies: AmazonDynamoDBFullAccess 114 | Events: 115 | PutResource: 116 | Type: Api 117 | Properties: 118 | Path: /todo/complete 119 | Method: put 120 | 121 | DeleteCompleteFunction: 122 | Type: AWS::Serverless::Function 123 | Properties: 124 | Handler: index.deleteComplete 125 | FunctionName: StartupKitDeleteCompleteFunction 126 | Policies: AmazonDynamoDBFullAccess 127 | Events: 128 | DeleteResource: 129 | Type: Api 130 | Properties: 131 | Path: /todo/complete 132 | Method: delete 133 | 134 | Table: 135 | Type: AWS::Serverless::SimpleTable 136 | Properties: 137 | PrimaryKey: 138 | Name: todo_id 139 | Type: String 140 | ProvisionedThroughput: 141 | ReadCapacityUnits: 5 142 | WriteCapacityUnits: 5 143 | 144 | 145 | Outputs: 146 | 147 | ApiUrl: 148 | Description: URL of the Prod stage of the API endpoint 149 | Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod" 150 | --------------------------------------------------------------------------------