image

Pre-Req: Must have Docker for Mac installed

I wanted to play with AWS SAM to understand how it works and compare to other tech like serverless.

Install and Test SAM

Use brew to install the aws-sam-cli:

brew upgrade
brew update
brew tap aws/tap
brew install aws-sam-cli
sam --version
> SAM CLI, version 0.10.0

Now init a go SAM project:

cd $GOPATH/src/github.com/grahamjenson/
sam init --runtime go --name hello-sam
cd hello-sam

This creates a folder with:

hello-sam/
├── Makefile                    <-- Make to automate build
├── README.md                   <-- This instructions file
├── hello-world                 <-- Source code for a lambda
│   ├── main.go                 <-- Lambda function code
│   └── main_test.go            <-- Unit tests
└── template.yaml

Install the aws-lambda-go dependency and test:

go get github.com/aws/aws-lambda-go
go test ./...
> ok    github.com/grahamjenson/hello-sam/hello-world   1.041s

Local Server

Start a HTTP server:

GOOS=linux GOARCH=amd64 go build -o hello-world/hello-world ./hello-world
sam local start-api

In another terminal:

curl http://127.0.0.1:3000/hello
> Hello, 192.168.10.10

This will pull down a docker container to execute the lambda in. This can be very slow.

Build & Deploy

SAM build and deploy is basically a wrapper around CloudFormation package and deploy commands.

package uploads relative assets from template.yaml to S3 and outputs a new file replacing them with S3 references packaged.yaml.

For this we need a S3 bucket:

aws s3 mb s3://hello-sam

Now we can use the CLI:

sam package \
    --template-file template.yaml \
    --output-template-file packaged.yaml \
    --s3-bucket hello-sam

Specifically, sam package uploads hello-world/ to S3 and replaces its CodeUri parameter to S3 URI in packaged.yaml.

Now we can deploy:

sam deploy \
    --template-file packaged.yaml \
    --stack-name hello-sam \
    --capabilities CAPABILITY_IAM

deploy wraps and waits to complete create-stack and update-stack.

This does not give you a chance to review what will be deployed. If you use --no-execute-changeset argument then you get a change-set ARN to use with describe-change-set and execute-change-set.

First impressions

Though I do not like CloudFormation because of its limitations (especially when compared to terraform). Being used for this use-case is great. Not having to define all the finicky little resources required for an API gateway in terraform means much less work.

The SAM CLI being used to create a local HTTP server for an API gateway is a bit clunky but works well enough. I hope they add more serverless resources like Step Functions to increase what can be tested locally.

I am now looking at past projects I should migrate over to SAM (pwnbot being the first) and future projects where I can use more advanced features like canary deploys, nested applications and web-sockets.