Skip to content

Latest commit

 

History

History
926 lines (698 loc) · 44.9 KB

2016-10-31.md

File metadata and controls

926 lines (698 loc) · 44.9 KB

AWS Serverless Application Model (SAM)

Version 2016-10-31

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.

Table of contents

Introduction

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.

Specification

Format

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.

Example: AWS SAM template

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 Section

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

Resource types

AWS::Serverless::Function

Creates a Lambda function, IAM execution role, and event source mappings which trigger the function.

Properties
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 Either CodeUri or InlineCode must be specified. S3 Uri or location to the function code. The S3 object this Uri references MUST be a Lambda deployment package.
InlineCode string Either CodeUri or InlineCode must be specified. The inline code for the lambda.
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.
PermissionsBoundary string ARN of a permissions boundary to use for this function's execution role.
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.
Layers list of string List of LayerVersion ARNs that should be used by this function. The order specified here is the order that they will be imported when running the Lambda function.
AutoPublishAlias string Name of the Alias. Read AutoPublishAlias Guide for how it works
VersionDescription string A string that specifies the Description field which will be added on the new lambda version
ReservedConcurrentExecutions integer The maximum of concurrent executions you want to reserve for the function. For more information see AWS Documentation on managing concurrency
Return values
Ref

When the logical ID of this resource is provided to the Ref intrinsic function, it returns the resource name of the underlying Lambda function.

Fn::GetAtt

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.
Referencing Lambda Version & Alias resources

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.

Example: AWS::Serverless::Function
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 # bucket must be created in the same template
Tags:
  AppNameTag: ThumbnailApp
  DepartmentNameTag: ThumbnailDepartment
Layers:
  - !Sub arn:${AWS::Partition}:lambda:${AWS::Region}:123456789012:layer:MyLayer:1

AWS::Serverless::Api

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.

Properties
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. If neither DefinitionUri nor DefinitionBody are specified, SAM will generate a DefinitionBody for you based on your template configuration. Note Intrinsic functions are not supported in external Swagger files, instead use DefinitionBody to define Swagger definition.
DefinitionBody JSON or YAML Object Swagger specification that describes your API. If neither DefinitionUri nor DefinitionBody are specified, SAM will generate a DefinitionBody for you based on your template configuration.
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.
Tags Map of string to string A map (string to string) that specifies the tags to be added to this API Stage. Keys and values are limited to alphanumeric characters.
EndpointConfiguration string Specify the type of endpoint for API endpoint. Value is either REGIONAL, EDGE, or PRIVATE.
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).
MinimumCompressionSize int Allow compression of response bodies based on client's Accept-Encoding header. Compression is triggered when response body size is greater than or equal to your configured threshold. The maximum body size threshold is 10 MB (10,485,760 Bytes). The following compression types are supported: gzip, deflate, and identity.
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.
Auth API Auth Object Auth configuration for this API. Define Lambda and Cognito Authorizers and specify a DefaultAuthorizer for this API. Can specify default ApiKey restriction using ApiKeyRequired. Also define ResourcePolicy and specify CustomStatements which is a list of policy statements that will be added to the resource policies on the API.
GatewayResponses Map of Gateway Response Type to Gateway Response Object Configures Gateway Reponses for an API. Gateway Responses are responses returned by API Gateway, either directly or through the use of Lambda Authorizers. Keys for this object are passed through to Api Gateway, so any value supported by GatewayResponse.responseType is supported here.
AccessLogSetting CloudFormation AccessLogSetting property Configures Access Log Setting for a stage. This value is passed through to CloudFormation, so any value supported by AccessLogSetting is supported here.
CanarySetting CloudFormation CanarySetting property Configure a Canary Setting to a Stage of a regular deployment. This value is passed through to Cloudformation, so any value supported by CanarySetting is supported here.
TracingEnabled boolean Indicates whether active tracing with X-Ray is enabled for the stage.
Models List of JSON or YAML objects JSON schemas that describes the models to be used by API methods.
Return values
Ref

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.

Example: AWS::Serverless::Api
StageName: prod
DefinitionUri: swagger.yml
Referencing generated resources - Stage & Deployment

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 with the intrinsic function !Ref, 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.

AWS::Serverless::Application

Embeds a serverless application from the AWS Serverless Application Repository or from an Amazon S3 bucket as a nested application. Nested applications are deployed as nested stacks, which can contain multiple other resources, including other AWS::Serverless::Application resources.

Properties
Property Name Type Description
Location string or Application Location Object Required Template URL or location of nested application. If a template URL is given, it must follow the format specified in the CloudFormation TemplateUrl documentation and contain a valid CloudFormation or SAM template.
Parameters Map of string to string Application parameter values.
NotificationARNs List of string A list of existing Amazon SNS topics where notifications about stack events are sent.
Tags Map of string to string A map (string to string) that specifies the tags to be added to this application. When the stack is created, SAM will automatically add the following tags: lambda:createdBy:SAM, serverlessrepo:applicationId:<applicationId>, serverlessrepo:semanticVersion:<semanticVersion>.
TimeoutInMinutes integer The length of time, in minutes, that AWS CloudFormation waits for the nested stack to reach the CREATE_COMPLETE state. The default is no timeout. When AWS CloudFormation detects that the nested stack has reached the CREATE_COMPLETE state, it marks the nested stack resource as CREATE_COMPLETE in the parent stack and resumes creating the parent stack. If the timeout period expires before the nested stack reaches CREATE_COMPLETE, AWS CloudFormation marks the nested stack as failed and rolls back both the nested stack and parent stack.

Other provided top-level resource attributes, e.g., Condition, DependsOn, etc, are automatically passed through to the underlying AWS::CloudFormation::Stack resource.

Return values
Ref

When the logical ID of this resource is provided to the Ref intrinsic function, it returns the resource name of the underlying CloudFormation nested stack.

Fn::GetAtt

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
Outputs.ApplicationOutputName The value of the stack output with name ApplicationOutputName.
Example: AWS::Serverless::Application
Resources:
  MyApplication:
    Type: AWS::Serverless::Application
    Properties:
      Location:
        ApplicationId: 'arn:aws:serverlessrepo:us-east-1:012345678901:applications/my-application'
        SemanticVersion: 1.0.0
      Parameters:
        StringParameter: parameter-value
        IntegerParameter: 2
  MyOtherApplication:
    Type: AWS::Serverless::Application
    Properties:
      Location: https://s3.amazonaws.com/demo-bucket/template.yaml
Outputs:
  MyNestedApplicationOutput:
    Value: !GetAtt MyApplication.Outputs.ApplicationOutputName
    Description: Example nested application output

AWS::Serverless::SimpleTable

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.

Properties
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. If ProvisionedThroughput is not specified BillingMode will be specified as PAY_PER_REQUEST
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.
Return values
Ref

When the logical ID of this resource is provided to the Ref intrinsic function, it returns the resource name of the underlying DynamoDB table.

Example: AWS::Serverless::SimpleTable
Properties:
  TableName: my-table
  PrimaryKey:
    Name: id
    Type: String
  ProvisionedThroughput:
    ReadCapacityUnits: 5
    WriteCapacityUnits: 5
  Tags:
    Department: Engineering
    AppType: Serverless
  SSESpecification:
    SSEEnabled: true

AWS::Serverless::LayerVersion

Creates a Lambda LayerVersion that contains library or runtime code needed by a Lambda Function. When a Serverless LayerVersion is transformed, SAM also transforms the logical id of the resource so that old LayerVersions are not automatically deleted by CloudFormation when the resource is updated.

Property Name Type Description
LayerName string Name of this layer. If you don't specify a name, the logical id of the resource will be used as the name.
Description string Description of this layer.
ContentUri string | S3 Location Object Required. S3 Uri or location for the layer code.
CompatibleRuntimes List of string List of runtimes compatible with this LayerVersion.
LicenseInfo string Information about the license for this LayerVersion.
RetentionPolicy string Options are Retain and Delete. Defaults to Retain. When Retain is set, SAM adds DeletionPolicy: Retain to the transformed resource so CloudFormation does not delete old versions after an update.
Return values
Ref

When the logical ID of this resource is provided to the Ref intrinsic function, it returns the resource ARN of the underlying Lambda LayerVersion.

Example: AWS::Serverless::LayerVersion
Properties:
  LayerName: MyLayer
  Description: Layer description
  ContentUri: 's3://my-bucket/my-layer.zip'
  CompatibleRuntimes:
    - nodejs6.10
    - nodejs8.10
  LicenseInfo: 'Available under the MIT-0 license.'
  RetentionPolicy: Retain

Event source types

S3

The object describing an event source with type S3.

Properties
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.

Example: S3 event source object
Type: S3
Properties:
  Bucket: my-photo-bucket # bucket must be created in the same template
  Events: s3:ObjectCreated:*
  Filter:
    S3Key:
      Rules:
        - Name: prefix|suffix
          Value: my-prefix|my-suffix

SNS

The object describing an event source with type SNS.

Properties
Property Name Type Description
Topic string Required. Topic ARN.
Region string Region.
FilterPolicy Amazon SNS filter policy Policy assigned to the topic subscription in order to receive only a subset of the messages.
Example: SNS event source object
Type: SNS
Properties:
  Topic: arn:aws:sns:us-east-1:123456789012:my_topic
  FilterPolicy:
    store: 
      - example_corp
    price_usd: 
      - numeric: 
          - ">="
          - 100

Kinesis

The object describing an event source with type Kinesis.

Properties
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.
Enabled boolean Indicates whether Lambda begins polling the event source.
Example: Kinesis event source object
Type: Kinesis
Properties:
  Stream: arn:aws:kinesis:us-east-1:123456789012:stream/my-stream
  StartingPosition: TRIM_HORIZON
  BatchSize: 10
  Enabled: false

DynamoDB

The object describing an event source with type DynamoDB.

Properties
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.
Enabled boolean Indicates whether Lambda begins polling the event source.
Example: DynamoDB event source object
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
  Enabled: false

SQS

The object describing an event source with type SQS.

Properties
Property Name Type Description
Queue string Required. ARN of the SQS queue.
BatchSize integer Maximum number of messages to process per function invocation.
Enabled boolean Indicates whether Lambda begins polling the event source.
Example: SQS event source object
Type: SQS
Properties:
  Queue: arn:aws:sqs:us-west-2:012345678901:my-queue # NOTE: FIFO SQS Queues are not yet supported
  BatchSize: 10
  Enabled: false

Api

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.

Properties
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.
Auth Function Auth Object Auth configuration for this specific Api+Path+Method. Useful for overriding the API's DefaultAuthorizer setting auth config on an individual path when no DefaultAuthorizer is specified or overriding the default ApiKeyRequired setting.
RequestModel Function Request Model Object Request model configuration for this specific Api+Path+Method.
Example: Api event source object
Type: Api
Properties:
  Path: /photos
  Method: post

Schedule

The object describing an event source with type Schedule.

Properties
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.
Name string A name for the Schedule. If you don't specify a name, a unique name will be generated.
Description string Description of Schedule.
Enabled boolean Indicated whether the Schedule is enabled.
Example: Schedule event source object
Type: Schedule
Properties:
  Schedule: rate(5 minutes)
  Name: my-schedule
  Description: Example schedule
  Enabled: True

CloudWatchEvent

The object describing an event source with type CloudWatchEvent.

Properties
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.
Example: CloudWatchEvent event source object
Type: CloudWatchEvent
Properties:
  Pattern:
    detail:
      state:
        - terminated

CloudWatchLogs

The object describing an event source with type CloudWatchLogs.

Properties
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.
Example: CloudWatchLogs event source object
Type: CloudWatchLogs
Properties:
  LogGroupName: MyLogGroup
  FilterPattern: Error

IoTRule

The object describing an event source with type IoTRule.

Properties
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.
Example: IoTRule event source object
Type: IoTRule
Properties:
  Sql: "SELECT * FROM 'iot/test'"

AlexaSkill

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.

Property types

Environment object

The object describing the environment properties of a function.

Properties
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 _(){}[]$*+-\/"#',;.@!?.
Example: Environment object
Variables:
  TABLE_NAME: my-table
  STAGE: prod

Event source object

The object describing the source of events which trigger the function.

Properties
Property Name Type Description
Type string Required. Event type. Event source types include 'S3, 'SNS', 'Kinesis', 'DynamoDB', 'SQS', 'Api', 'Schedule', 'CloudWatchEvent', 'CloudWatchLogs', 'IoTRule', 'AlexaSkill'. For more information about the 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.
Example: Event source object
Type: S3
Properties:
  Bucket: my-photo-bucket # bucket must be created in the same template
Type: AlexaSkill

Primary key object

The object describing the properties of a primary key.

Properties
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.
Example: Primary key object
Properties:
  PrimaryKey:
    Name: id
    Type: String

Data Types

S3 Location Object

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

Application Location Object

Specifies the location of an application hosted in the AWS Serverless Application Repository as a dictionary containing ApplicationId and SemanticVersion properties.

Example:

Location: # Both parameters are required
  ApplicationId: 'arn:aws:serverlessrepo:us-east-1:012345678901:applications/my-application'
  SemanticVersion: 1.0.0

DeadLetterQueue Object

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 official 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. 

DeploymentPreference Object

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

Cors Configuration

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

  AllowCredentials: Optional. Boolean indicating whether request is allowed to contain credentials.
  # Header is omitted when false. Checkout [HTTP Spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials) 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

API Auth Object

Configure Auth on APIs.

Authorizers: Define Lambda and Cognito Authorizers and specify a DefaultAuthorizer. If you use IAM permission, only specify AWS_IAM to a DefaultAuthorizer. For more information, see the documentation on Lambda Authorizers and Amazon Cognito User Pool Authorizers and IAM Permissions.

Auth:
  ApiKeyRequired: true # OPTIONAL
  DefaultAuthorizer: MyCognitoAuth # OPTIONAL, if you use IAM permissions, specify AWS_IAM.
  # For AWS_IAM:
  # DefaultAuthorizer: AWS_IAM
  # InvokeRole: NONE # CALLER_CREDENTIALS by default unless overridden
  Authorizers:
    MyCognitoAuth:
      UserPoolArn: !GetAtt MyCognitoUserPool.Arn # Can also accept an array
      Identity: # OPTIONAL
        Header: MyAuthorizationHeader # OPTIONAL; Default: 'Authorization'
        ValidationExpression: myauthvalidationexpression # OPTIONAL

    MyLambdaTokenAuth:
      FunctionPayloadType: TOKEN # OPTIONAL; Defaults to 'TOKEN' when `FunctionArn` is specified
      FunctionArn: !GetAtt MyAuthFunction.Arn
      FunctionInvokeRole: arn:aws:iam::123456789012:role/S3Access # OPTIONAL
      Identity:
        Header: MyCustomAuthHeader # OPTIONAL; Default: 'Authorization'
        ValidationExpression: mycustomauthexpression # OPTIONAL
        ReauthorizeEvery: 20 # OPTIONAL; Service Default: 300

    MyLambdaRequestAuth:
      FunctionPayloadType: REQUEST
      FunctionArn: !GetAtt MyAuthFunction.Arn
      FunctionInvokeRole: arn:aws:iam::123456789012:role/S3Access # OPTIONAL
      Identity:
        # Must specify at least one of Headers, QueryStrings, StageVariables, or Context
        Headers: # OPTIONAL
          - Authorization1
        QueryStrings: # OPTIONAL
          - Authorization2
        StageVariables: # OPTIONAL
          - Authorization3
        Context: # OPTIONAL
          - Authorization4
        ReauthorizeEvery: 0 # OPTIONAL; Service Default: 300

ApiKey: Configure ApiKey restriction for all methods and paths on an API. This setting can be overriden on individual AWS::Serverless::Function using the Function Auth Object. Typically this would be used to require ApiKey on all methods and then override it on select methods that you want to be public.

Auth:
  ApiKeyRequired: true

ResourcePolicy: Configure Resource Policy for all methods and paths on an API. This setting can also be defined on individual AWS::Serverless::Function using the Function Auth Object. This is required for APIs with EndpointConfiguration: PRIVATE.

Auth:
  ResourcePolicy:
    CustomStatements: 
      - Effect: Allow
        Principal: *
        Action: execute-api:Invoke
        ...

Function Auth Object

Configure Auth for a specific Api+Path+Method.

Auth:
  Authorizer: MyCognitoAuth # OPTIONAL, if you use IAM permissions in each functions, specify AWS_IAM.

If you have specified a Global Authorizer on the API and want to make a specific Function public, override with the following:

Auth:
  Authorizer: 'NONE'

Require api keys for a specific Api+Path+Method.

Auth:
  ApiKeyRequired: true

If you have specified ApiKeyRequired: true globally on the API and want to make a specific Function public, override with the following:

Auth:
  ApiKeyRequired: false

Function Request Model Object

Configure Request Model for a specific Api+Path+Method.

RequestModel:
  Model: User # REQUIRED; must match the name of a model defined in the Models property of the AWS::Serverless::API
  Required: true # OPTIONAL; boolean

Gateway Response Object

Configure Gateway Responses on APIs. These are associated with the ID of a Gateway Response response type. For more information, see the documentation on AWS::ApiGateway::GatewayResponse.

GatewayResponses:
  UNAUTHORIZED:
    StatusCode: 401 # Even though this is the default value for UNAUTHORIZED.
    ResponseTemplates:
      "application/json": '{ "message": $context.error.messageString }'
    ResponseParameters:
      Paths:
        path-key: "'value'"
      QueryStrings:
        query-string-key: "'value'"
      Headers:
        Access-Control-Expose-Headers: "'WWW-Authenticate'"
        Access-Control-Allow-Origin: "'*'"
        WWW-Authenticate: >-
          'Bearer realm="admin"'

All properties of a Gateway Response object are optional. API Gateway has knowledge of default status codes to associate with Gateway Responses, so – for example – StatusCode is only used in order to override this value.

NOTE: API Gateway spec allows values under the ResponseParameters and ResponseTemplates properties to be templates. In order to send constant values, don't forget the additional quotes. ie. "'WWW-Authenticate'" is correct whereas "WWW-Authenticate" is wrong.