The key words "MUST", "MUST NOT", "REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT", "RECOMMENDED", "MAY", and "OPTIONAL" in this document are to be interpreted as described in RFC 2119.
The AWS Serverless Application Model (SAM) is licensed under The Apache License, Version 2.0.
AWS SAM is a model used to define serverless applications on AWS.
Serverless applications are applications composed of functions triggered by events. A typical serverless application consists of one or more AWS Lambda functions triggered by events such as object uploads to Amazon S3, Amazon SNS notifications, and API actions. Those functions can stand alone or leverage other resources such as Amazon DynamoDB tables or S3 buckets. The most basic serverless application is simply a function.
AWS SAM is based on AWS CloudFormation. A serverless application is defined in a CloudFormation template and deployed as a CloudFormation stack. An AWS SAM template is a CloudFormation template.
AWS SAM defines a set of objects which can be included in a CloudFormation template to describe common components of serverless applications easily.
The files describing a serverless application in accordance with AWS SAM are JSON or YAML formatted text files. These files are CloudFormation templates.
AWS SAM introduces several new resources and property types that can be embedded into the Resources section of the template. The templates may include all other template sections and use CloudFormation intrinsic functions to access properties available only at runtime.
In order to include objects defined by AWS SAM within a CloudFormation template, the template must include a Transform
section in the document root with a value of AWS::Serverless-2016-10-31
.
AWSTemplateFormatVersion: '2010-09-09'
Transform: 'AWS::Serverless-2016-10-31'
Resources:
MyFunction:
Type: 'AWS::Serverless::Function'
Properties:
Handler: index.handler
Runtime: nodejs6.10
CodeUri: 's3://my-bucket/function.zip'
All property names in AWS SAM are case sensitive.
Globals is a section in your SAM template to define properties common to all your Serverless Function and APIs. All the AWS::Serverless::Function
and
AWS::Serverless::Api
resources will inherit the properties defined here.
Read the Globals Guide for more detailed information.
Example:
Globals:
Function:
Runtime: nodejs6.10
Timeout: 180
Handler: index.handler
Environment:
Variables:
TABLE_NAME: data-table
Api:
EndpointConfiguration: REGIONAL
Cors: "'www.example.com'"
SimpleTable:
SSESpecification:
SSEEnabled: true
Creates a Lambda function, IAM execution role, and event source mappings which trigger the function.
Property Name | Type | Description |
---|---|---|
Handler | string |
Required. Function within your code that is called to begin execution. |
Runtime | string |
Required. The runtime environment. |
CodeUri | string | S3 Location Object |
Required. S3 Uri or location to the function code. The S3 object this Uri references MUST be a Lambda deployment package. |
FunctionName | string |
A name for the function. If you don't specify a name, a unique name will be generated for you. More Info |
Description | string |
Description of the function. |
MemorySize | integer |
Size of the memory allocated per invocation of the function in MB. Defaults to 128. |
Timeout | integer |
Maximum time that the function can run before it is killed in seconds. Defaults to 3. |
Role | string |
ARN of an IAM role to use as this function's execution role. If omitted, a default role is created for this function. |
Policies | string | List of string | IAM policy document object | List of IAM policy document object | List of SAM Policy Templates |
Names of AWS managed IAM policies or IAM policy documents or SAM Policy Templates that this function needs, which should be appended to the default role for this function. If the Role property is set, this property has no meaning. |
Environment | Function environment object | Configuration for the runtime environment. |
VpcConfig | VPC config object | Configuration to enable this function to access private resources within your VPC. |
Events | Map of string to Event source object |
A map (string to Event source object) that defines the events that trigger this function. Keys are limited to alphanumeric characters. |
Tags | Map of string to string |
A map (string to string) that specifies the tags to be added to this function. Keys and values are limited to alphanumeric characters. Keys can be 1 to 127 Unicode characters in length and cannot be prefixed with aws: . Values can be 1 to 255 Unicode characters in length. When the stack is created, SAM will automatically add a lambda:createdBy:SAM tag to this Lambda function. |
Tracing | string |
String that specifies the function's X-Ray tracing mode. Accepted values are Active and PassThrough |
KmsKeyArn | string |
The Amazon Resource Name (ARN) of an AWS Key Management Service (AWS KMS) key that Lambda uses to encrypt and decrypt your function's environment variables. |
DeadLetterQueue | map | DeadLetterQueue Object |
Configures SNS topic or SQS queue where Lambda sends events that it can't process. |
DeploymentPreference | DeploymentPreference Object | Settings to enable Safe Lambda Deployments. Read the usage guide for detailed information. |
AutoPublishAlias | string |
Name of the Alias. Read AutoPublishAlias Guide for how it works |
ReservedConcurrentExecutions | integer |
The maximum of concurrent executions you want to reserve for the function. For more information see AWS Documentation on managing concurrency |
When the logical ID of this resource is provided to the Ref intrinsic function, it returns the resource name of the underlying Lambda function.
When the logical ID of this resource is provided to the Fn::GetAtt intrinsic function, it returns a value for a specified attribute of this type. This section lists the available attributes.
Attribute Name | Description |
---|---|
Arn | The ARN of the Lambda function. |
When you use AutoPublishAlias
property, SAM will generate a Lambda Version and Alias resource for you. If you want to refer to these properties in an intrinsic function such as Ref or Fn::GetAtt, you can append .Version
or .Alias
suffix to the function's Logical ID. SAM will convert it to the correct Logical ID of the auto-generated Version or Alias resource respectively.
Example:
Assume the following Serverless Function
Resources:
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
...
AutoPublishAlias: live
...
Version can be referenced as:
"Ref": "MyLambdaFunction.Version"
Alias can be referenced as:
"Ref": "MyLambdaFunction.Alias"
This can be used with other intrinsic functions such as "Fn::GetAtt" or "Fn::Sub" or "Fn::Join" as well.
Handler: index.js
Runtime: nodejs6.10
CodeUri: 's3://my-code-bucket/my-function.zip'
Description: Creates thumbnails of uploaded images
MemorySize: 1024
Timeout: 15
Policies:
- AWSLambdaExecute # Managed Policy
- Version: '2012-10-17' # Policy Document
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectACL
Resource: 'arn:aws:s3:::my-bucket/*'
Environment:
Variables:
TABLE_NAME: my-table
Events:
PhotoUpload:
Type: S3
Properties:
Bucket: my-photo-bucket
Tags:
AppNameTag: ThumbnailApp
DepartmentNameTag: ThumbnailDepartment
Creates a collection of Amazon API Gateway resources and methods that can be invoked through HTTPS endpoints.
An AWS::Serverless::Api
resource need not be explicitly added to a AWS Serverless Application Definition template. A resource of this type is implicitly created from the union of Api events defined on AWS::Serverless::Function
resources defined in the template that do not refer to an AWS::Serverless::Api
resource. An AWS::Serverless::Api
resource should be used to define and document the API using Swagger, which provides more ability to configure the underlying Amazon API Gateway resources.
Property Name | Type | Description |
---|---|---|
Name | string |
A name for the API Gateway RestApi resource. |
StageName | string |
Required The name of the stage, which API Gateway uses as the first path segment in the invoke Uniform Resource Identifier (URI). |
DefinitionUri | string | S3 Location Object |
S3 URI or location to the Swagger document describing the API. Either one of DefinitionUri or DefinitionBody must be specified. |
DefinitionBody | JSON or YAML Object |
Swagger specification that describes your API. Either one of DefinitionUri or DefinitionBody must be specified. |
CacheClusterEnabled | boolean |
Indicates whether cache clustering is enabled for the stage. |
CacheClusterSize | string |
The stage's cache cluster size. |
Variables | Map of string to string |
A map (string to string map) that defines the stage variables, where the variable name is the key and the variable value is the value. Variable names are limited to alphanumeric characters. Values must match the following regular expression: [A-Za-z0-9._~:/?#&=,-]+ . |
MethodSettings | CloudFormation MethodSettings property | Configures all settings for API stage including Logging, Metrics, CacheTTL, Throttling. This value is passed through to CloudFormation. So any values supported by CloudFormation MethodSettings property can be used here. |
EndpointConfiguration | string |
Specify the type of endpoint for API endpoint. Value is either REGIONAL or EDGE . |
BinaryMediaTypes | List of string |
List of MIME types that your API could return. Use this to enable binary support for APIs. Use ~1 instead of / in the mime types (See examples in template.yaml). |
Cors | string or Cors Configuration |
Enable CORS for all your APIs. Specify the domain to allow as a string or specify a dictionary with additional Cors Configuration. NOTE: Cors requires SAM to modify your Swagger definition. Hence it works only inline swagger defined with DefinitionBody . |
When the logical ID of this resource is provided to the Ref intrinsic function, it returns the resource name of the underlying API Gateway RestApi.
StageName: prod
DefinitionUri: swagger.yml
SAM will generate an API Gateway Stage and API Gateway Deployment for every AWS::Serverless::Api
resource. If you want to refer to these properties in an intrinsic function such as Ref or Fn::GetAtt, you can append .Stage
and .Deployment
suffix to the API's Logical ID. SAM will convert it to the correct Logical ID of the auto-generated Stage or Deployment resource respectively.
The AWS::Serverless::SimpleTable
resource creates a DynamoDB table with a single attribute primary key. It is useful when data only needs to be accessed via a primary key. To use the more advanced functionality of DynamoDB, use an AWS::DynamoDB::Table resource instead.
Property Name | Type | Description |
---|---|---|
PrimaryKey | Primary Key Object | Attribute name and type to be used as the table's primary key. This cannot be modified without replacing the resource. Defaults to String attribute named ID. |
ProvisionedThroughput | Provisioned Throughput Object | Read and write throughput provisioning information. Defaults to 5 read and 5 write capacity units per second. |
Tags | Map of string to string |
A map (string to string) that specifies the tags to be added to this table. Keys and values are limited to alphanumeric characters. |
TableName | string |
Name for the DynamoDB Table |
SSESpecification | DynamoDB SSESpecification | Specifies the settings to enable server-side encryption. |
When the logical ID of this resource is provided to the Ref intrinsic function, it returns the resource name of the underlying DynamoDB table.
Properties:
TableName: my-table
PrimaryKey:
Name: id
Type: String
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
Tags:
Department: Engineering
AppType: Serverless
SSESpecification:
SSEEnabled: true
The object describing an event source with type S3
.
Property Name | Type | Description |
---|---|---|
Bucket | string |
Required. S3 bucket name. |
Events | string | List of string |
Required. See Amazon S3 supported event types for valid values. |
Filter | Amazon S3 notification filter | Rules to filter events on. |
NOTE: To specify an S3 bucket as an event source for a Lambda function, both resources have to be declared in the same template. AWS SAM does not support specifying an existing bucket as an event source.
Type: S3
Properties:
Bucket: my-photo-bucket
Events: s3:ObjectCreated:*
The object describing an event source with type SNS
.
Property Name | Type | Description |
---|---|---|
Topic | string |
Required. Topic ARN. |
Type: SNS
Properties:
Topic: arn:aws:sns:us-east-1:123456789012:my_topic
The object describing an event source with type Kinesis
.
Property Name | Type | Description |
---|---|---|
Stream | string |
Required. ARN of the Amazon Kinesis stream. |
StartingPosition | string |
Required. One of TRIM_HORIZON or LATEST . |
BatchSize | integer |
Maximum number of stream records to process per function invocation. |
Type: Kinesis
Properties:
Stream: arn:aws:kinesis:us-east-1:123456789012:stream/my-stream
StartingPosition: TRIM_HORIZON
BatchSize: 10
The object describing an event source with type DynamoDB
.
Property Name | Type | Description |
---|---|---|
Stream | string |
Required. ARN of the DynamoDB stream. |
StartingPosition | string |
Required. One of TRIM_HORIZON or LATEST . |
BatchSize | integer |
Maximum number of stream records to process per function invocation. |
Type: DynamoDB
Properties:
Stream: arn:aws:dynamodb:us-east-1:123456789012:table/TestTable/stream/2016-08-11T21:21:33.291
StartingPosition: TRIM_HORIZON
BatchSize: 10
The object describing an event source with type SQS
.
Property Name | Type | Description |
---|---|---|
Queue | string |
Required. ARN of the SQS queue. |
BatchSize | integer |
Maximum number of messages to process per function invocation. |
Type: SQS
Properties:
Queue: arn:aws:sqs:us-west-2:012345678901:my-queue # NOTE: FIFO SQS Queues are not yet supported
BatchSize: 10
The object describing an event source with type Api
.
If an AWS::Serverless::Api resource is defined, the path and method values MUST correspond to an operation in the Swagger definition of the API. If no AWS::Serverless::Api is defined, the function input and output are a representation of the HTTP request and HTTP response. For example, using the JavaScript API, the status code and body of the response can be controlled by returning an object with the keys statusCode
and body
.
Property Name | Type | Description |
---|---|---|
Path | string |
Required. Uri path for which this function is invoked. MUST start with / . |
Method | string |
Required. HTTP method for which this function is invoked. |
RestApiId | string |
Identifier of a RestApi resource which MUST contain an operation with the given path and method. Typically, this is set to reference an AWS::Serverless::Api resource defined in this template. If not defined, a default AWS::Serverless::Api resource is created using a generated Swagger document contains a union of all paths and methods defined by Api events defined in this template that do not specify a RestApiId. |
Type: Api
Properties:
Path: /photos
Method: post
The object describing an event source with type Schedule
.
Property Name | Type | Description |
---|---|---|
Schedule | string |
Required. Schedule expression, which MUST follow the schedule expression syntax rules. |
Input | string |
JSON-formatted string to pass to the function as the event body. |
Type: Schedule
Properties:
Schedule: rate(5 minutes)
The object describing an event source with type CloudWatchEvent
.
Property Name | Type | Description |
---|---|---|
Pattern | Event Pattern Object | Required. Pattern describing which CloudWatch events trigger the function. Only matching events trigger the function. |
Input | string |
JSON-formatted string to pass to the function as the event body. This value overrides the matched event. |
InputPath | string |
JSONPath describing the part of the event to pass to the function. |
Type: CloudWatchEvent
Properties:
Pattern:
detail:
state:
- terminated
The object describing an event source with type CloudWatchLogs
.
Property Name | Type | Description |
---|---|---|
LogGroupName | string |
Required. Name of the CloudWatch Log Group from which to process logs. |
FilterPattern | string |
Required. A CloudWatch Logs FilterPattern to specify which logs in the Log Group to process. |
Type: CloudWatchLogs
Properties:
LogGroupName: MyLogGroup
FilterPattern: Error
The object describing an event source with type IoTRule
.
Property Name | Type | Description |
---|---|---|
Sql | string |
Required. The SQL statement that queries the topic. For more information, see Rules for AWS IoT in the AWS IoT Developer Guide. |
AwsIotSqlVersion | string |
The version of the SQL rules engine to use when evaluating the rule. |
Type: IoTRule
Properties:
Sql: "SELECT * FROM 'iot/test'"
The object describing an event source with type AlexaSkill
.
Specifying AlexaSkill
event creates a resource policy that allows the Amazon Alexa service to call your Lambda function. To configure the Alexa service to work with your Lambda function, go to the Alexa Developer portal.
The object describing the environment properties of a function.
Property Name | Type | Description |
---|---|---|
Variables | Map of string to string |
A map (string to string map) that defines the environment variables, where the variable name is the key and the variable value is the value. Variable names are limited to alphanumeric characters and the first character must be a letter. Values are limited to alphanumeric characters and the following special characters _(){}[]$*+-\/"#',;.@!? . |
Variables:
TABLE_NAME: my-table
STAGE: prod
The object describing the source of events which trigger the function.
Property Name | Type | Description |
---|---|---|
Type | string |
Required. Event type. Event source types include 'S3, 'Api', 'SNS', 'Kinesis', 'DynamoDB'. For more information about all types, see Event source types. |
Properties | * | Required. Object describing properties of this event mapping. Must conform to the defined Type . For more information about all types, see Event source types. |
Type: S3
Properties:
Bucket: my-photo-bucket
Type: AlexaSkill
The object describing the properties of a primary key.
Property Name | Type | Description |
---|---|---|
Name | string |
Attribute name of the primary key. Defaults to id . |
Type | string |
Attribute type of the primary key. MUST be one of String , Number , or Binary . |
Properties:
PrimaryKey:
Name: id
Type: String
Specifies the location of an S3 object as a dictionary containing Bucket
, Key
, and optional Version
properties.
Example:
CodeUri:
Bucket: mybucket-name
Key: code.zip
Version: 121212
Specifies an SQS queue or SNS topic that AWS Lambda (Lambda) sends events to when it can't process them. For more information about DLQ functionality, refer to the officiall documentation at http://docs.aws.amazon.com/lambda/latest/dg/dlq.html. SAM will automatically add appropriate permission to your Lambda function execution role to give Lambda service access to the resource. sqs:SendMessage
will be added for SQS queues and sns:Publish
for SNS topics.
Syntax:
DeadLetterQueue:
Type: `SQS` or `SNS`
TargetArn: ARN of the SQS queue or SNS topic to use as DLQ.
Specifies the configurations to enable Safe Lambda Deployments. Read the usage guide for detailed information. The following shows all available properties of this object
DeploymentPreference:
Enabled: true
Type: Linear10PercentEvery10Minutes
Alarms:
# A list of alarms that you want to monitor
- !Ref AliasErrorMetricGreaterThanZeroAlarm
- !Ref LatestVersionErrorMetricGreaterThanZeroAlarm
Hooks:
# Validation Lambda functions that are run before & after traffic shifting
PreTraffic: !Ref PreTrafficLambdaFunction
PostTraffic: !Ref PostTrafficLambdaFunction
Enable and configure CORS for the APIs. Enabling CORS will allow your API to be called from other domains. Assume your API is served from 'www.example.com' and you want to allow.
Cors:
AllowMethods: Optional. String containing the HTTP methods to allow.
# For example, "'GET,POST,DELETE'". If you omit this property, then SAM will automatically allow all the methods configured for each API.
# Checkout [HTTP Spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods) more details on the value.
AllowHeaders: Optional. String of headers to allow.
# For example, "'X-Forwarded-For'". Checkout [HTTP Spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers) for more details on the value
AllowOrigin: Required. String of origin to allow.
# For example, "'www.example.com'". Checkout [HTTP Spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin) for more details on this value.
MaxAge: Optional. String containing the number of seconds to cache CORS Preflight request.
# For example, "'600'" will cache request for 600 seconds. Checkout [HTTP Spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age) for more details on this value
NOTE: HTTP spec requires the value of Allow properties to be a quoted string. So don't forget the additional quotes in the value. ie. "'www.example.com'" is correct whereas "www.example.com" is wrong