AWS SAM Lambda

AWS SAM Lambda configuration and deployment.

AWS Lambda is a service from serverless compute group, allows running code without servers provisioning, cluster scaling, maintaining runtimes.

Template

Template for AWS Lambda is almost the same for officially supported languages, it varies more only in case of custom runtimes (custom runtimes are not covered here).

Example template for AWS Lambda in Golang.

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  app02
  
  SAM Template for lambda golang   

Parameters:
  Env:
    Type: String
    Description: "Logical environment like dev, test, prod etc"
    Default: dev

Globals:
  Function:
    Timeout: 3

Resources:
  FeatureOneFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: app02/featureone/
      Handler: handler
      Runtime: go1.x
      Tracing: Active
      Environment:
        Variables:
          PARAM1: VALUE

Outputs:
  FeatureOneFunction:
    Description: "Feature one function ARN"
    Value: !GetAtt FeatureOneFunction.Arn
  FeatureOneFunctionIamRole:
    Description: "IAM Role created for feature one function"
    Value: !GetAtt FeatureOneFunctionRole.Arn

Catalog structure

Code Uri and handler name must be matching to catalog structure and final lambda binary name

SAM catalog structure:

Golang lambda code

Probably the simplest lambda, returns stringified request back to caller.

import (
	"context"
	"fmt"

	"github.com/aws/aws-lambda-go/lambda"
)

func handler(ctx context.Context, request map[string]interface{}) (string, error) {
	// simply return string representation of the request
	return fmt.Sprintf("Response: %v", request), nil
}

func main() {
	lambda.Start(handler)
}

SAM Configuration

version = 0.1
[dev]
[dev.deploy]
[dev.deploy.parameters]
stack_name = "dev-app02"
s3_bucket = "basicappdeployment"
s3_prefix = "dev-app02"
region = "eu-west-1"
confirm_changeset = true
capabilities = "CAPABILITY_NAMED_IAM"
parameter_overrides = "Env=\"dev\""

[test]
[test.deploy]
[test.deploy.parameters]
stack_name = "test-app02"
s3_bucket = "basicappdeployment"
s3_prefix = "test-app02"
region = "eu-west-1"
confirm_changeset = true
capabilities = "CAPABILITY_NAMED_IAM"
parameter_overrides = "Env=\"test\""

Building

sam build

Deployment

sam deploy --profile default --config-env dev --no-fail-on-empty-changeset

Deployed cloudformation template

SAM deployed template:

Deployed resources

Resources are nicely prefixed with stack name and remain redable

SAM deployed resources:

Conclusions

Lambda building, packaging and deployment is done by SAM. Nice, easy to perform deployments.