AWS SAM Template
AWS SAM Template
AWS Serverless Application Model (AWS SAM) is an open-source framework for building
serverless applications. It extends AWS CloudFormation to simplify the definition of serverless
applications, including AWS Lambda functions, Amazon API Gateway APIs, and Amazon
DynamoDB tables.
SAM templates are written in JSON and follow a structure similar to AWS CloudFormation
templates. They consist of the following main sections:
AWSTemplateFormatVersion:
AWSTemplateFormatVersion: '2010-09-09'
Transform:
Transform: AWS::Serverless-2016-10-31
Description:
Globals:
Function:
Timeout: 30
Parameters:
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs14.x
Outputs:
Defines output values that can be retrieved after the stack creation.
Outputs:
MyOutput:
Value: !Ref MyFunction
AWS SAM Resource Types
AWS SAM introduces several resource types that simplify the definition of serverless resources:
AWS::Serverless::Function:
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs14.x
AWS::Serverless::Api:
Resources:
MyApi:
Type: AWS::Serverless::Api
AWS::Serverless::SimpleTable:
Resources:
MyTable:
Type: AWS::Serverless::SimpleTable
AWS::Serverless::StateMachine:
Resources:
MyStateMachine:
Type: AWS::Serverless::StateMachine
Properties:
DefinitionUri: s3://my-bucket/state-machine-definition.json
AWS SAM Policy Templates
AWS SAM includes predefined policy templates that simplify the definition of IAM policies:
AWSLambdaBasicExecutionRole:
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Policies: AWSLambdaBasicExecutionRole
AWSLambdaVPCAccessExecutionRole:
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Policies: AWSLambdaVPCAccessExecutionRole
AWSLambdaSQSQueueExecutionRole:
Allows Lambda to send messages to an SQS queue.
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Policies: AWSLambdaSQSQueueExecutionRole
SAM CLI Commands
The SAM CLI provides commands for building, testing, and deploying serverless applications.
sam init:
sam build
sam local invoke:
Conclusion:
AWS SAM simplifies the process of building and deploying serverless applications by extending
AWS CloudFormation with specific constructs tailored for serverless resources. It provides a
more concise and readable way to define serverless infrastructure, making it easier for
developers to manage and deploy their applications on AWS