Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs(examples): add example for AWS SAM #674

Merged
merged 26 commits into from
May 7, 2022
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
01324a8
added example for AWS SAM
Mar 18, 2022
9c3d999
removed unnecessary hello-world folder
Apr 5, 2022
ed0abd2
tsconfig now in line with other tsconfigs in this repo
Apr 5, 2022
fd6acbc
added try/catch block + metric annotation + error logging for dynamod…
Apr 5, 2022
644a76a
Importing only DynamoDB instead of whole aws-sdk. Patching only the D…
Apr 5, 2022
58a3ca4
removed prettier; aligned dependency versions with others in this repo
Apr 5, 2022
ef8239a
Update examples/sam/README.md
bpauwels Apr 12, 2022
cf2f9c6
Update examples/sam/README.md
bpauwels Apr 12, 2022
8ce19c7
Merge branch 'awslabs:main' into examples-sam
bpauwels Apr 12, 2022
cb28daf
seperated lambda function code
Apr 12, 2022
5266452
Updated README.md
Apr 20, 2022
007c990
Updated README.md removed powertools example folder
Apr 20, 2022
f6bc21c
Updated README.md changed cleanup to sam delete
Apr 20, 2022
caf39e2
fixed eslint issues
Apr 20, 2022
b6953dc
added copied files to .gitignore
Apr 20, 2022
d5969b8
multiple changes to template.yaml
Apr 20, 2022
a35bb80
changed policy to DynamoDBReadPolicy for all get* Lambdas
Apr 20, 2022
7a355cf
fixed escaped DynamodDB description in template.yaml
Apr 20, 2022
5fd51c6
fixed README.md; changed try catch to capture missing env; import onl…
Apr 26, 2022
17831a3
fixed tracer.captureAWSClient to capture DocumentClient
Apr 26, 2022
3b68bdb
moved package.json to sam folder
Apr 27, 2022
de14ec6
changed author in package.json; various changes to README.md; changed…
Apr 27, 2022
48425c0
removed redundant comments
Apr 27, 2022
6b55f2d
added additional steps to readme.md
Apr 27, 2022
310c39f
removed null assertions
Apr 27, 2022
ae2dddf
removed manual copy step and created a symlink instead
May 6, 2022
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
208 changes: 208 additions & 0 deletions examples/sam/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@

# Created by https://www.toptal.com/developers/gitignore/api/osx,node,linux,windows,sam
# Edit at https://www.toptal.com/developers/gitignore?templates=osx,node,linux,windows,sam

### Linux ###
*~

# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*

# KDE directory preferences
.directory

# Linux trash folder which might appear on any partition or disk
.Trash-*

# .nfs files are created when an open file is removed but is still being accessed
.nfs*

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# 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
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://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/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variables file
.env
.env.test
.env*.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next

# Nuxt.js build / generate output
.nuxt
dist

# Storybook build outputs
.out
.storybook-out
storybook-static

# rollup.js default build output
dist/

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# Temporary folders
tmp/
temp/

### OSX ###
# General
.DS_Store
.AppleDouble
.LSOverride

# Icon must end with two \r
Icon


# Thumbnails
._*

# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent

# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

### SAM ###
# Ignore build directories for the AWS Serverless Application Model (SAM)
# Info: https://aws.amazon.com/serverless/sam/
# Docs: https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-reference.html

**/.aws-sam

### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db

# Dump file
*.stackdump

# Folder config file
[Dd]esktop.ini

# Recycle Bin used on file shares
$RECYCLE.BIN/

# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp

# Windows shortcuts
*.lnk

# End of https://www.toptal.com/developers/gitignore/api/osx,node,linux,windows,sam
127 changes: 127 additions & 0 deletions examples/sam/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
# powertools-example
bpauwels marked this conversation as resolved.
Show resolved Hide resolved

This project contains source code and supporting files for a serverless application that you can deploy with the SAM CLI. It includes the following files and folders.
bpauwels marked this conversation as resolved.
Show resolved Hide resolved

bpauwels marked this conversation as resolved.
Show resolved Hide resolved
- hello-world - Code for the application's Lambda function written in TypeScript.
bpauwels marked this conversation as resolved.
Show resolved Hide resolved
- events - Invocation events that you can use to invoke the function.
bpauwels marked this conversation as resolved.
Show resolved Hide resolved
- hello-world/tests - Unit tests for the application code.
- template.yaml - A template that defines the application's AWS resources.
bpauwels marked this conversation as resolved.
Show resolved Hide resolved

The application uses several AWS resources, including Lambda functions and an API Gateway API. These resources are defined in the `template.yaml` file in this project. You can update the template to add AWS resources through the same deployment process that updates your application code.

If you prefer to use an integrated development environment (IDE) to build and test your application, you can use the AWS Toolkit.
The AWS Toolkit is an open source plug-in for popular IDEs that uses the SAM CLI to build and deploy serverless applications on AWS. The AWS Toolkit also adds a simplified step-through debugging experience for Lambda function code. See the following links to get started.

* [CLion](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [GoLand](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [IntelliJ](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [WebStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [Rider](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [PhpStorm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [PyCharm](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [RubyMine](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [DataGrip](https://docs.aws.amazon.com/toolkit-for-jetbrains/latest/userguide/welcome.html)
* [VS Code](https://docs.aws.amazon.com/toolkit-for-vscode/latest/userguide/welcome.html)
* [Visual Studio](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/welcome.html)

## Deploy the sample application

The Serverless Application Model Command Line Interface (SAM CLI) is an extension of the AWS CLI that adds functionality for building and testing Lambda applications. It uses Docker to run your functions in an Amazon Linux environment that matches Lambda. It can also emulate your application's build environment and API.
bpauwels marked this conversation as resolved.
Show resolved Hide resolved

To use the SAM CLI, you need the following tools.
bpauwels marked this conversation as resolved.
Show resolved Hide resolved

* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
* Node.js - [Install Node.js 14](https://nodejs.org/en/), including the NPM package management tool.
* Docker - [Install Docker community edition](https://hub.docker.com/search/?type=edition&offering=community)

To build and deploy your application for the first time, run the following in your shell:

```bash
sam build
dreamorosi marked this conversation as resolved.
Show resolved Hide resolved
sam deploy --guided
```

The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts:

* **Stack Name**: The name of the stack to deploy to CloudFormation. This should be unique to your account and region, and a good starting point would be something matching your project name.
* **AWS Region**: The AWS region you want to deploy your app to.
* **Confirm changes before deploy**: If set to yes, any change sets will be shown to you before execution for manual review. If set to no, the AWS SAM CLI will automatically deploy application changes.
* **Allow SAM CLI IAM role creation**: Many AWS SAM templates, including this example, create AWS IAM roles required for the AWS Lambda function(s) included to access AWS services. By default, these are scoped down to minimum required permissions. To deploy an AWS CloudFormation stack which creates or modifies IAM roles, the `CAPABILITY_IAM` value for `capabilities` must be provided. If permission isn't provided through this prompt, to deploy this example you must explicitly pass `--capabilities CAPABILITY_IAM` to the `sam deploy` command.
* **Save arguments to samconfig.toml**: If set to yes, your choices will be saved to a configuration file inside the project, so that in the future you can just re-run `sam deploy` without parameters to deploy changes to your application.

You can find your API Gateway Endpoint URL in the output values displayed after deployment.
dreamorosi marked this conversation as resolved.
Show resolved Hide resolved

bpauwels marked this conversation as resolved.
Show resolved Hide resolved
## Use the SAM CLI to build and test locally

Build your application with the `sam build` command.

```bash
powertools-example$ sam build
bpauwels marked this conversation as resolved.
Show resolved Hide resolved
```

The SAM CLI installs dependencies defined in `hello-world/package.json`, compiles TypeScript with esbuild, creates a deployment package, and saves it in the `.aws-sam/build` folder.
bpauwels marked this conversation as resolved.
Show resolved Hide resolved

Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the `events` folder in this project.

Run functions locally and invoke them with the `sam local invoke` command.

```bash
powertools-example$ sam local invoke HelloWorldFunction --event events/event.json
bpauwels marked this conversation as resolved.
Show resolved Hide resolved
```

The SAM CLI can also emulate your application's API. Use the `sam local start-api` to run the API locally on port 3000.

```bash
powertools-example$ sam local start-api
bpauwels marked this conversation as resolved.
Show resolved Hide resolved
powertools-example$ curl http://localhost:3000/
bpauwels marked this conversation as resolved.
Show resolved Hide resolved
```

The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The `Events` property on each function's definition includes the route and method for each path.

```yaml
Events:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please check indentation in this code block.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indentation seems correct to me as in template.yaml

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it's correct if you look at it relative to the larger template, but since this is a decontextualised code snippet it's a bit odd that the first line starts with 6 spaces.

Either way it's really a minor / nitpicky comment, you can leave it if you think it makes sense.

HelloWorld:
Type: Api
Properties:
Path: /hello
Method: get
```

## Add a resource to your application
The application template uses AWS Serverless Application Model (AWS SAM) to define application resources. AWS SAM is an extension of AWS CloudFormation with a simpler syntax for configuring common serverless application resources such as functions, triggers, and APIs. For resources not included in [the SAM specification](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md), you can use standard [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html) resource types.
bpauwels marked this conversation as resolved.
Show resolved Hide resolved

## Fetch, tail, and filter Lambda function logs

To simplify troubleshooting, SAM CLI has a command called `sam logs`. `sam logs` lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.

`NOTE`: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.

```bash
powertools-example$ sam logs -n HelloWorldFunction --stack-name powertools-example --tail
bpauwels marked this conversation as resolved.
Show resolved Hide resolved
```

You can find more information and examples about filtering Lambda function logs in the [SAM CLI Documentation](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-logging.html).

## Unit tests

Tests are defined in the `hello-world/tests` folder in this project. Use NPM to install the [Jest test framework](https://jestjs.io/) and run unit tests.

```bash
powertools-example$ cd hello-world
hello-world$ npm install
hello-world$ npm run test
```

bpauwels marked this conversation as resolved.
Show resolved Hide resolved
## Cleanup

To delete the sample application that you created, use the AWS CLI. Assuming you used your project name for the stack name, you can run the following:
bpauwels marked this conversation as resolved.
Show resolved Hide resolved

```bash
aws cloudformation delete-stack --stack-name powertools-example
```

## Resources

See the [AWS SAM developer guide](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) for an introduction to SAM specification, the SAM CLI, and serverless application concepts.

Next, you can use AWS Serverless Application Repository to deploy ready to use Apps that go beyond hello world samples and learn how authors developed their applications: [AWS Serverless Application Repository main page](https://aws.amazon.com/serverless/serverlessrepo/)
3 changes: 3 additions & 0 deletions examples/sam/events/event-get-all-items.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"httpMethod": "GET"
}
6 changes: 6 additions & 0 deletions examples/sam/events/event-get-by-id.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"httpMethod": "GET",
"pathParameters": {
"id": "id1"
}
}
4 changes: 4 additions & 0 deletions examples/sam/events/event-post-item.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"httpMethod": "POST",
"body": "{\"id\": \"id1\",\"name\": \"name1\"}"
}
2 changes: 2 additions & 0 deletions examples/sam/src/handlers/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
dreamorosi marked this conversation as resolved.
Show resolved Hide resolved
.aws-sam
15 changes: 15 additions & 0 deletions examples/sam/src/handlers/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
module.exports = {
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features
sourceType: "module"
},
extends: [
"plugin:@typescript-eslint/recommended", // recommended rules from the @typescript-eslint/eslint-plugin
"plugin:prettier/recommended" // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
],
rules: {
// Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
// e.g. "@typescript-eslint/explicit-function-return-type": "off",
}
};
1 change: 1 addition & 0 deletions examples/sam/src/handlers/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
tests/*
7 changes: 7 additions & 0 deletions examples/sam/src/handlers/.prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
semi: true,
trailingComma: "all",
singleQuote: true,
printWidth: 120,
tabWidth: 4
};
Loading