AWS Serverless Application Model
AWS Serverless Application Model
Application Model
Developer Guide
AWS Serverless Application Model Developer Guide
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not
Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or
discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may
or may not be affiliated with, connected to, or sponsored by Amazon.
AWS Serverless Application Model Developer Guide
Table of Contents
What Is AWS SAM? ............................................................................................................................. 1
Benefits of Using AWS SAM ........................................................................................................ 1
Next Step .................................................................................................................................. 2
Getting Started .................................................................................................................................. 3
Installing the AWS SAM CLI ......................................................................................................... 3
Linux ................................................................................................................................ 3
Windows ........................................................................................................................... 6
macOS .............................................................................................................................. 8
Tutorial: Deploying a Hello World Application .............................................................................. 10
Prerequisites .................................................................................................................... 11
Step 1: Download a Sample AWS SAM Application ............................................................... 11
Step 2: Build Your Application ........................................................................................... 12
Step 3: Deploy Your Application to the AWS Cloud ............................................................... 12
Step 4: Testing Your Application Locally (Optional) ............................................................... 15
Troubleshooting ............................................................................................................... 17
Clean Up ......................................................................................................................... 18
Conclusion ....................................................................................................................... 18
Next Steps ....................................................................................................................... 18
AWS SAM Specification ..................................................................................................................... 19
Template Anatomy ................................................................................................................... 19
YAML .............................................................................................................................. 20
Template Sections ............................................................................................................ 20
Globals ............................................................................................................................ 21
Resource and Property Reference ............................................................................................... 25
AWS::Serverless::Api .......................................................................................................... 25
AWS::Serverless::Application ............................................................................................... 45
AWS::Serverless::Function .................................................................................................. 48
AWS::Serverless::LayerVersion ............................................................................................. 83
AWS::Serverless::SimpleTable ............................................................................................. 86
Resource Attributes .................................................................................................................. 89
Intrinsic Functions .................................................................................................................... 90
API Gateway Extensions ............................................................................................................ 90
Authoring ........................................................................................................................................ 92
Validating AWS SAM Template Files ............................................................................................ 92
Building Applications with Dependencies ..................................................................................... 92
Working with Layers ................................................................................................................. 93
Using Nested Applications ......................................................................................................... 94
Defining a Nested Application from the AWS Serverless Application Repository ........................ 95
Defining a Nested Application from the Local File System ...................................................... 96
Deploying Nested Applications ........................................................................................... 96
Controlling Access to APIs ......................................................................................................... 97
Choosing a Mechanism to Control Access ............................................................................ 97
Example: Defining Lambda Token Authorizers ...................................................................... 98
Example: Defining Lambda Request Authorizers ................................................................... 98
Example: Defining Amazon Cognito User Pools .................................................................... 99
Example: Defining IAM Permissions ................................................................................... 100
Example: Defining API Keys ............................................................................................. 101
Example: Defining Resource Policies .................................................................................. 101
Example: Defining Customized Responses .......................................................................... 102
Testing and Debugging ................................................................................................................... 104
Invoking Functions Locally ....................................................................................................... 104
Environment Variable File ................................................................................................ 105
Layers ........................................................................................................................... 106
Running API Gateway Locally ................................................................................................... 106
iii
AWS Serverless Application Model Developer Guide
iv
AWS Serverless Application Model Developer Guide
v
AWS Serverless Application Model Developer Guide
Benefits of Using AWS SAM
A serverless application is a combination of Lambda functions, event sources, and other resources that
work together to perform tasks. Note that a serverless application is more than just a Lambda function—
it can include additional resources such as APIs, databases, and event source mappings.
You can use AWS SAM to define your serverless applications. AWS SAM consists of the following
components:
• AWS SAM template specification. You use this specification to define your serverless application.
It provides you with a simple and clean syntax to describe the functions, APIs, permissions,
configurations, and events that make up a serverless application. You use an AWS SAM template file
to operate on a single, deployable, versioned entity that's your serverless application. For the full AWS
SAM template specification, see AWS Serverless Application Model (AWS SAM) Specification (p. 19).
• AWS SAM command line interface (AWS SAM CLI). You use this tool to build serverless applications
that are defined by AWS SAM templates. The CLI provides commands that enable you to verify that
AWS SAM template files are written according to the specification, invoke Lambda functions locally,
step-through debug Lambda functions, package and deploy serverless applications to the AWS Cloud,
and so on. For details about how to use the AWS SAM CLI, including the full AWS SAM CLI Command
Reference, see AWS SAM CLI Command Reference (p. 134).
This guide shows you how to use AWS SAM to define, test, and deploy a simple serverless application.
It also provides an example application (p. 10) that you can download, test locally, and deploy to the
AWS Cloud. You can use this example application as a starting point for developing your own serverless
applications.
• Single-deployment configuration. AWS SAM makes it easy to organize related components and
resources, and operate on a single stack. You can use AWS SAM to share configuration (such as
memory and timeouts) between resources, and deploy all related resources together as a single,
versioned entity.
• Extension of AWS CloudFormation. Because AWS SAM is an extension of AWS CloudFormation, you
get the reliable deployment capabilities of AWS CloudFormation. You can define resources by using
AWS CloudFormation in your AWS SAM template. Also, you can use the full suite of resources, intrinsic
functions, and other template features that are available in AWS CloudFormation.
1
AWS Serverless Application Model Developer Guide
Next Step
• Built-in best practices. You can use AWS SAM to define and deploy your infrastructure as config. This
makes it possible for you to use and enforce best practices such as code reviews. Also, with a few lines
of configuration, you can enable safe deployments through CodeDeploy, and can enable tracing by
using AWS X-Ray.
• Local debugging and testing. The AWS SAM CLI lets you locally build, test, and debug serverless
applications that are defined by AWS SAM templates. The CLI provides a Lambda-like execution
environment locally. It helps you catch issues upfront by providing parity with the actual Lambda
execution environment. To step through and debug your code to understand what the code is doing,
you can use AWS SAM with AWS toolkits like the AWS Toolkit for JetBrains, AWS Toolkit for PyCharm,
AWS Toolkit for IntelliJ, and AWS Toolkit for Visual Studio Code. This tightens the feedback loop by
making it possible for you to find and troubleshoot issues that you might run into in the cloud.
• Deep integration with development tools. You can use AWS SAM with a suite of AWS tools for
building serverless applications. You can discover new applications in the AWS Serverless Application
Repository. For authoring, testing, and debugging AWS SAM–based serverless applications, you can
use the AWS Cloud9 IDE. To build a deployment pipeline for your serverless applications, you can
use CodeBuild, CodeDeploy, and CodePipeline. You can also use AWS CodeStar to get started with
a project structure, code repository, and a CI/CD pipeline that's automatically configured for you. To
deploy your serverless application, you can use the Jenkins plugin. You can use the Stackery.io toolkit
to build production-ready applications.
Next Step
Getting Started with AWS SAM (p. 3)
2
AWS Serverless Application Model Developer Guide
Installing the AWS SAM CLI
To install the AWS SAM CLI, including everything that needs to be installed or configured to use the
AWS SAM CLI, see Installing the AWS SAM CLI (p. 3). After the AWS SAM CLI is installed, you can run
through the following tutorial.
Topics
• Installing the AWS SAM CLI (p. 3)
• Tutorial: Deploying a Hello World Application (p. 10)
To install the AWS SAM CLI, see the following instructions for your development host:
Topics
• Installing the AWS SAM CLI on Linux (p. 3)
• Installing the AWS SAM CLI on Windows (p. 6)
• Installing the AWS SAM CLI on macOS (p. 8)
3
AWS Serverless Application Model Developer Guide
Linux
Docker is an application that runs containers on your Linux machines. AWS SAM provides a local
environment that's similar to AWS Lambda to use as a Docker container. You can use this container to
build, test, and debug your serverless applications.
You must have Docker installed and working to be able to run serverless projects and functions locally
with the AWS SAM CLI. The AWS SAM CLI uses the DOCKER_HOST environment variable to contact the
Docker daemon. The following steps describe how to install, configure, and verify a Docker installation to
work with the AWS SAM CLI.
Docker is available on many different operating systems, including most modern Linux distributions,
like CentOS, Debian, Ubuntu, etc. For more information about how to install Docker on your particular
operating system, go to the Docker installation guide.
If you are using Amazon Linux 2, follow these steps to install Docker:
4. Add the ec2-user to the docker group so you can execute Docker commands without using sudo.
5. Log out and log back in again to pick up the new docker group permissions. You can accomplish
this by closing your current SSH terminal window and reconnecting to your instance in a new one.
Your new SSH session will have the appropriate docker group permissions.
6. Verify that the ec2-user can run Docker commands without sudo.
docker ps
You should see the following output, showing Docker is installed and running:
Note
In some cases, you may need to reboot your instance to provide permissions for the ec2-
user to access the Docker daemon. Try rebooting your instance if you see the following
error:
4
AWS Serverless Application Model Developer Guide
Linux
Cannot connect to the Docker daemon. Is the docker daemon running on this host?
If you run into issues installing Docker, see the Troubleshooting (p. 6) section later in this guide, or
the Docker installation guide for additional troubleshooting tips.
Next, add Homebrew to your PATH by running the following commands. These commands work on
all major flavors of Linux by adding either ~/.profile on Debian/Ubuntu or ~/.bash_profile on
CentOS/Fedora/RedHat:
brew --version
You should see output like the following on successful installation of Homebrew:
Homebrew 2.1.6
Homebrew/homebrew-core (git revision ef21; last commit 2019-06-19)
sam --version
You should see output like the following after successful installation of the AWS SAM CLI:
5
AWS Serverless Application Model Developer Guide
Windows
Troubleshooting
Docker Error: "Cannot connect to the Docker daemon. Is the docker daemon
running on this host?"
In some cases, you may need to reboot your instance to provide permissions for the ec2-user to access
the Docker daemon. If you receive this error, try rebooting your instance.
For example, if you used the instructions in this topic to both 1) Install Homebrew, and 2) Use Homebrew
to install the AWS SAM CLI, then the AWS SAM CLI executable will be installed to the following location:
/home/homebrew/.homebrew/bin/sam
Next Steps
You're now ready to begin building your own serverless applications using AWS SAM! If you want to start
with sample serverless applications, choose one of the following links:
• Tutorial: Deploying a Hello World Application (p. 10) – Step-by-step instructions to download, build,
and deploy a simple serverless application.
• AWS SAM example applications in GitHub – Sample applications in the AWS SAM GitHub repository
that you can further experiment with.
6
AWS Serverless Application Model Developer Guide
Windows
Docker is an application that runs containers on your Linux machines. AWS SAM provides a local
environment that's similar to AWS Lambda to use as a Docker container. You can use this container to
build, test, and debug your serverless applications.
You must have Docker installed and working to be able to run serverless projects and functions locally
with the AWS SAM CLI. The AWS SAM CLI uses the DOCKER_HOST environment variable to contact the
Docker daemon. The following steps describe how to install, configure, and verify a Docker installation to
work with the AWS SAM CLI.
1. Install Docker.
Docker Desktop supports the most recent Windows operating system. For legacy versions of
Windows, the Docker Toolbox is available. Choose your version of Windows for the correct Docker
installation steps:
• To install Docker for Windows 10, see Install Docker Desktop for Windows.
• To install Docker for older versions of Windows, see Install Docker Toolbox on Windows.
2. Configure your shared drives.
The AWS SAM CLI requires that the project directory, or any parent directory, is listed in a shared
drive. Choose your version of Windows below for the correct shared drive instructions:
After Docker is installed, verify that it's working. Also confirm that you can run Docker commands
from the AWS SAM CLI (for example, docker ps). You don't need to install, fetch, or pull any
containers—the AWS SAM CLI does this automatically as required.
If you run into issues installing Docker, see the Docker installation guide for troubleshooting tips.
Follow these steps to install the AWS SAM CLI using the MSI file.
After completing the installation, verify it by opening a new command prompt or PowerShell
prompt. You should be able to invoke sam from the command line.
sam --version
7
AWS Serverless Application Model Developer Guide
macOS
You should see output like the following after successful installation of the AWS SAM CLI:
Next Steps
You're now ready to begin building your own serverless applications using AWS SAM! If you want to start
with sample serverless applications, choose one of the following links:
• Tutorial: Deploying a Hello World Application (p. 10) – Step-by-step instructions to download, build,
and deploy a simple serverless application.
• AWS SAM example applications in GitHub – Sample applications in the AWS SAM GitHub repository
that you can further experiment with.
Docker is an application that runs containers on your macOS machines. AWS SAM provides a local
environment that's similar to AWS Lambda to use as a Docker container. You can use this container to
build, test, and debug your serverless applications.
You must have Docker installed and working to be able to run serverless projects and functions locally
with the AWS SAM CLI. The AWS SAM CLI uses the DOCKER_HOST environment variable to contact the
8
AWS Serverless Application Model Developer Guide
macOS
Docker daemon. The following steps describe how to install, configure, and verify a Docker installation to
work with the AWS SAM CLI.
1. Install Docker
The AWS SAM CLI supports Docker running on macOS Sierra 10.12 or above. To install Docker see
Install Docker Desktop for Mac.
2. Configure your shared drives
The AWS SAM CLI requires that the project directory, or any parent directory, is listed in a shared
drive. To share drives on macOS, see File sharing.
3. Verify the installation
After Docker is installed, verify that it's working. Also confirm that you can run Docker commands
from the AWS SAM CLI (for example, docker ps). You don't need to install, fetch, or pull any
containers––the AWS SAM CLI does this automatically as required.
If you run into issues installing Docker, see the Docker installation guide for troubleshooting tips.
brew --version
You should see output like the following on successful installation of Homebrew:
Homebrew 2.1.6
Homebrew/homebrew-core (git revision ef21; last commit 2019-06-19)
sam --version
You should see output like the following after successful installation of the AWS SAM CLI:
9
AWS Serverless Application Model Developer Guide
Tutorial: Deploying a Hello World Application
Next Steps
You're now ready to begin building your own serverless applications using AWS SAM! If you want to start
with sample serverless applications, choose one of the following links:
• Tutorial: Deploying a Hello World Application (p. 10) – Step-by-step instructions to download, build,
and deploy a simple serverless application.
• AWS SAM example applications in GitHub – Sample applications in the AWS SAM GitHub repository
that you can further experiment with.
This application implements a simple API backend. It consists of an API Gateway endpoint and a Lambda
function. When you send a GET request to the API Gateway endpoint, the Lambda function is invoked.
This function returns a hello world message.
The following is a preview of commands that you run to create your Hello World application. For more
details about each of these commands, see the sections later in this page
10
AWS Serverless Application Model Developer Guide
Prerequisites
Prerequisites
This guide assumes that you've completed the steps in the Installing the AWS SAM CLI (p. 3) for your
OS. It assumes that you've done the following:
sam init
Follow the on-screen prompts. For this tutorial we recommend you choose AWS Quick Start Templates,
the runtime of your choice, and the Hello World Example.
Example output:
-----------------------
Generating application:
-----------------------
Name: sam-app
Runtime: python3.7
Dependency Manager: pip
Application Template: hello-world
Output Directory: .
This command creates a directory with the name you provided as the project name. The contents of
the project directory are similar to the following (these contents are created when one of the Python
runtimes and the Hello World Example are chose):
sam-app/
### README.md
### events/
# ### event.json
### hello_world/
# ### __init__.py
# ### app.py #Contains your AWS Lambda handler logic.
# ### requirements.txt #Contains any Python dependencies the application requires,
used for sam build
### template.yaml #Contains the AWS SAM template defining your application's AWS
resources.
### tests/
### unit/
11
AWS Serverless Application Model Developer Guide
Step 2: Build Your Application
### __init__.py
### test_handler.py
• template.yaml: Contains the AWS SAM template that defines your application's AWS resources.
• hello_world/app.py: Contains your actual Lambda handler logic.
• hello_world/requirements.txt: Contains any Python dependencies that the application requires,
and is used for sam build.
First change into the project directory (that is, the directory where the template.yaml file for the
sample application is located; by default is sam-app), then run this command:
sam build
Example output:
Build Succeeded
The AWS SAM CLI comes with abstractions for a number of Lambda runtimes to build your
dependencies, and copies the source code into staging folders so that everything is ready to be packaged
and deployed. The sam build command builds any dependencies that your application has, and copies
your application source code to folders under aws-sam/build to be zipped and uploaded to Lambda.
.aws_sam/
### build/
### HelloWorldFunction/
### template.yaml
HelloWorldFunction is a directory that contains your app.py file, as well as third-party dependencies
that your application uses.
12
AWS Serverless Application Model Developer Guide
Step 3: Deploy Your Application to the AWS Cloud
Follow the on-screen prompts. You can just respond with Enter to accept the default options provided
in the interactive experience.
Example output:
Initiating deployment
=====================
13
AWS Serverless Application Model Developer Guide
Step 3: Deploy Your Application to the AWS Cloud
f9d
CREATE_IN_PROGRESS AWS::Lambda::Permission
HelloWorldFunctionHelloWorldPermis Resource creation Initiated
sionProd
CREATE_IN_PROGRESS AWS::Lambda::Permission
HelloWorldFunctionHelloWorldPermis -
sionProd
CREATE_IN_PROGRESS AWS::ApiGateway::Deployment
ServerlessRestApiDeployment47fc2d5 -
f9d
CREATE_COMPLETE AWS::ApiGateway::Deployment
ServerlessRestApiDeployment47fc2d5 -
f9d
CREATE_IN_PROGRESS AWS::ApiGateway::Stage
ServerlessRestApiProdStage -
CREATE_IN_PROGRESS AWS::ApiGateway::Stage
ServerlessRestApiProdStage Resource creation Initiated
CREATE_COMPLETE AWS::ApiGateway::Stage
ServerlessRestApiProdStage -
CREATE_COMPLETE AWS::Lambda::Permission
HelloWorldFunctionHelloWorldPermis -
sionProd
UPDATE_COMPLETE_CLEANUP_IN_PROGRES AWS::CloudFormation::Stack sam-app
-
S
UPDATE_COMPLETE AWS::CloudFormation::Stack sam-app
-
------------------------------------------------------------------------------------------------------
HelloWorldFunction-1TY92MJX0BXU5
------------------------------------------------------------------------------------------------------
This command deploys your application to the AWS cloud. It take the deployment artifacts you build
with the sam build command, packages and uploads them to an Amazon S3 bucket created by AWS
SAM CLI, and deploys the application using AWS CloudFormation. In the output of the deploy command
you can see the changes being made to your AWS CloudFormation stack.
If your application created a HTTP endpoint, the Outputs generated by sam deploy also show you the
endpoint URL for your test application. You can use curl to send a request to your application using
that endpoint URL. For example:
curl https://<restapiid>.execute-api.us-east-1.amazonaws.com/Prod/hello/
You should see output like the following after successfully deploying your application:
14
AWS Serverless Application Model Developer Guide
Step 4: Testing Your Application Locally (Optional)
If you see {"message": "hello world"} after executing the curl command, it means that you've
successfully deployed your serverless application to AWS, and are calling your live Lambda function.
Otherwise, see the Troubleshooting (p. 17) section later in this tutorial.
Example output:
It might take a while for the Docker image to load. After it's loaded, you can use curl to send a request
to your application that's running on your local host:
curl http://127.0.0.1:3000/hello
Example output:
15
AWS Serverless Application Model Developer Guide
Step 4: Testing Your Application Locally (Optional)
The start-api command starts up a local endpoint that replicates your REST API endpoint. It
downloads an execution container that you can run your function locally in. The end result is the same
output that you saw when you called your function in the AWS Cloud.
Example output:
The invoke command directly invokes your Lambda functions, and can pass input event payloads that
you provide. With this command, you pass the event payload in the file event.json that's provided by
the sample application.
Your initialized application came with a default aws-proxy event for API Gateway. A number of values
are prepopulated for you. In this case, the HelloWorldFunction doesn't care about the particular
values, so a stubbed request is OK. You can specify a number of values to be substituted in to the request
to simulate what you would expect from an actual request. This following is an example of generating
your own input event and comparing the output with the default event.json object:
sam local generate-event apigateway aws-proxy --body "" --path "hello" --method GET > api-
event.json
$ diff api-event.json event.json
Example output:
16
AWS Serverless Application Model Developer Guide
Troubleshooting
Troubleshooting
SAM CLI error: "no such option: --app-template"
When executing sam init, you see the following error:
This means that you are using an older version of the AWS SAM CLI that does not support the --app-
template parameter. To fix this, you can either update your version of AWS SAM CLI to 0.30.0 or later,
or omit the --app-template parameter from the sam init command.
This means that you've attempted to send a request to the correct domain, but the URI isn't
recognizable. To fix this, verify the full URL, and update the curl command with the correct URL.
curl: (6) Could not resolve: endpointdomain (Domain name not found)
17
AWS Serverless Application Model Developer Guide
Clean Up
This means that you've attempted to send a request to an invalid domain. This can happen if your
serverless application failed to deploy successfully, or if you have a typo in your curl command. Verify
that the application was deployed successfully by using the AWS CloudFormation console or AWS CLI,
and that your curl command is correct.
Clean Up
If you no longer need the AWS resources you created by running this tutorial, you can remove them by
deleting the AWS CloudFormation stack that you deployed.
To delete the AWS CloudFormation stack created with this tutorial using the AWS Management Console,
follow these steps:
1. Sign in to the AWS Management Console and open the AWS CloudFormation console at https://
console.aws.amazon.com/cloudformation.
2. In the left navigation pane, choose Stacks.
3. In the list of stacks, choose aws-sam-getting-started.
4. Choose Delete.
When done, the status of the of the stack will change to DELETE_COMPLETE.
Alternatively, you can delete the AWS CloudFormation stack by executing the following AWS CLI
command:
Conclusion
In this tutorial, you've done the following:
1. Created, built, and deployed a serverless application to AWS with AWS SAM.
2. Tested your application locally by using the AWS SAM CLI and Docker.
3. Deleted the AWS resources that you no longer need.
Next Steps
You're now ready to start building your own applications using the AWS SAM CLI.
To help you get started, you can download any of the example applications from the AWS SAM GitHub
repository. To access this repository, see AWS SAM example applications.
18
AWS Serverless Application Model Developer Guide
Template Anatomy
AWS SAM templates are an extension of AWS CloudFormation templates, with some additional
components that make them easier to work with. For the full reference for AWS CloudFormation
templates, see AWS CloudFormation Template Reference in the AWS CloudFormation User Guide.
Topics
• AWS SAM Template Anatomy (p. 19)
• AWS SAM Resource and Property Reference (p. 25)
• Resource Attributes (p. 89)
• Intrinsic Functions (p. 90)
• API Gateway Extensions (p. 90)
The primary differences between AWS SAM templates and AWS CloudFormation templates are the
following:
• Globals section. The Globals section is unique to AWS SAM. It defines properties that are
common to all your serverless functions and APIs. All the AWS::Serverless::Function,
AWS::Serverless::Api, and AWS::Serverless::SimpleTable resources inherit the properties
that are defined in the Globals section. For more information about the Globals section, see Globals
Section of the Template (p. 21) in the AWS Serverless Application Model Developer Guide.
• Resources section. In AWS SAM templates the Resources section can contain a combination of AWS
CloudFormation resources and AWS SAM resources. For more information about AWS CloudFormation
resources, see AWS Resource and Property Types Reference in the AWS CloudFormation User Guide. For
more information about AWS SAM resources see AWS SAM Resource and Property Reference (p. 25)
in the AWS Serverless Application Model Developer Guide.
All other sections of an AWS SAM template correspond to the AWS CloudFormation template section of
the same name.
19
AWS Serverless Application Model Developer Guide
YAML
YAML
The following example shows a YAML-formatted template fragment.
Transform: AWS::Serverless-2016-10-31
Globals:
set of globals
Description:
String
Metadata:
template metadata
Parameters:
set of parameters
Mappings:
set of mappings
Conditions:
set of conditions
Resources:
set of resources
Outputs:
set of outputs
Template Sections
Templates include several major sections. Transform and Resources are the only required sections.
The sections in a template can be in any order. However, as you build your template, it can be helpful to
use the logical order that's shown in the following list. This is because the values in one section might
refer to values from a previous section.
Transform (required)
For AWS SAM templates, you must include this section with a value of
AWS::Serverless-2016-10-31.
Additional transforms are optional. For more information about transforms, see Transform in the
AWS CloudFormation User Guide.
Globals (optional) (p. 21)
A section in your AWS SAM template to define properties that are common to all your
serverless functions, APIs, and simple tables. All the AWS::Serverless::Function,
AWS::Serverless::Api, and AWS::Serverless::SimpleTable resources inherit the properties
that are defined in the Globals section.
This section is unique to AWS SAM. There isn't a corresponding section in AWS CloudFormation
templates.
Description (optional)
This section corresponds directly with the Description section of AWS CloudFormation templates.
20
AWS Serverless Application Model Developer Guide
Globals
Metadata (optional)
This section corresponds directly with the Metadata section of AWS CloudFormation templates.
Parameters (optional)
Values to pass to your template at runtime (when you create or update a stack). You can refer to
parameters from the Resources and Outputs sections of the template.
This section corresponds directly with the Parameters section of AWS CloudFormation templates.
Mappings (optional)
A mapping of keys and associated values that you can use to specify conditional parameter values,
similar to a lookup table. You can match a key to a corresponding value by using the Fn::FindInMap
intrinsic function in the Resources and Outputs sections.
This section corresponds directly with the Mappings section of AWS CloudFormation templates.
Conditions (optional)
Conditions that control whether certain resources are created or whether certain resource properties
are assigned a value during stack creation or update. For example, you could conditionally create a
resource that depends on whether the stack is for a production or test environment.
This section corresponds directly with the Conditions section of AWS CloudFormation templates.
Resources (required)
Specifies the stack resources and their properties, such as an Amazon EC2 instance or an Amazon S3
bucket. You can refer to resources in the Resources and Outputs sections of the template.
This section is similar to the Resources section of AWS CloudFormation templates. In AWS SAM
templates, this section can contain AWS SAM resources in addition to AWS CloudFormation
resources.
Outputs (optional)
Describes the values that are returned whenever you view your stack's properties. For example, you
can declare an output for an S3 bucket name, and then call the aws cloudformation describe-
stacks AWS CLI command to view the name.
This section corresponds directly with the Outputs section of AWS CloudFormation templates.
Example:
Globals:
Function:
Runtime: nodejs6.10
Timeout: 180
Handler: index.handler
21
AWS Serverless Application Model Developer Guide
Globals
Environment:
Variables:
TABLE_NAME: data-table
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
Environment:
Variables:
MESSAGE: "Hello From SAM"
ThumbnailFunction:
Type: AWS::Serverless::Function
Properties:
Events:
Thumbnail:
Type: Api
Properties:
Path: /thumbnail
Method: POST
In this example, both HelloWorldFunction and ThumbnailFunction use "nodejs6.10" for Runtime,
"180" seconds for Timeout, and "index.handler" for Handler. HelloWorldFunction adds the
MESSAGE environment variable, in addition to the inherited TABLE_NAME. ThumbnailFunction
inherits all the Globals properties and adds an API event source.
Globals:
Function:
# Properties of AWS::Serverless::Function
Handler:
Runtime:
CodeUri:
DeadLetterQueue:
Description:
MemorySize:
Timeout:
VpcConfig:
Environment:
Tags:
Tracing:
KmsKeyArn:
Layers:
AutoPublishAlias:
DeploymentPreference:
PermissionsBoundary:
ReservedConcurrentExecutions:
Api:
# Properties of AWS::Serverless::Api
# Also works with Implicit APIs
Auth:
Name:
DefinitionUri:
CacheClusterEnabled:
CacheClusterSize:
Variables:
EndpointConfiguration:
MethodSettings:
22
AWS Serverless Application Model Developer Guide
Globals
BinaryMediaTypes:
MinimumCompressionSize:
Cors:
GatewayResponses:
AccessLogSetting:
CanarySetting:
TracingEnabled:
OpenApiVersion:
SimpleTable:
# Properties of AWS::Serverless::SimpleTable
SSESpecification:
Implicit APIs
Implicit APIs are APIs that are created by AWS SAM when you declare an API in the Events section. You
can use Globals to override all the properties of implicit APIs.
Unsupported Properties
The following properties are not supported in the Globals section. We made the explicit call to not
support them because it either made the template hard to understand, or opened a scope for potential
security issues.
Function:
Role:
Policies:
FunctionName:
Events:
Api:
StageName:
DefinitionBody:
Overridable Properties
Properties that are declared in the Globals section can be overridden by the resource. For example, you
can add new variables to an environment variable map, or you can override globally declared variables.
But the resource cannot remove a property that's specified in the Globals environment variables map.
More generally, the Globals section declares properties that are shared by all your resources. Some
resources can provide new values for globally declared properties, but they can't completely remove
them. If some resources use a property but others don't, then you must not declare them in the Globals
section.
The following sections describe how overriding works for different data types.
The value specified in the Resources section replaces the value in the Globals section.
Example:
Globals:
Function:
Runtime: nodejs4.3
23
AWS Serverless Application Model Developer Guide
Globals
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.6
Map entries in the resource are merged with global map entries. If there are duplicates, the resource
entry overrides the global entry.
Example:
Globals:
Function:
Environment:
Variables:
STAGE: Production
TABLE_NAME: global-table
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Environment:
Variables:
TABLE_NAME: resource-table
NEW_VAR: hello
{
"STAGE": "Production",
"TABLE_NAME": "resource-table",
"NEW_VAR": "hello"
}
Entries in the Globals section are prepended to the list in the Resource section.
Example:
Globals:
Function:
VpcConfig:
SecurityGroupIds:
- sg-123
- sg-456
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
24
AWS Serverless Application Model Developer Guide
Resource and Property Reference
VpcConfig:
SecurityGroupIds:
- sg-first
Topics
• AWS::Serverless::Api (p. 25)
• AWS::Serverless::Application (p. 45)
• AWS::Serverless::Function (p. 48)
• AWS::Serverless::LayerVersion (p. 83)
• AWS::Serverless::SimpleTable (p. 86)
AWS::Serverless::Api
Creates a collection of Amazon API Gateway resources and methods that can be invoked through HTTPS
endpoints.
An AWS::Serverless::Api (p. 25) 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 (p. 48) resources defined in the template that do not refer to an
AWS::Serverless::Api (p. 25) resource.
An AWS::Serverless::Api (p. 25) resource should be used to define and document the API using
OpenApi, which provides more ability to configure the underlying Amazon API Gateway resources.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Type: AWS::Serverless::Api
Properties:
AccessLogSetting: AccessLogSetting
Auth: ApiAuth (p. 31)
BinaryMediaTypes: List
CacheClusterEnabled: Boolean
CacheClusterSize: String
CanarySetting: CanarySetting
Cors: String | CorsConfiguration (p. 43)
DefinitionBody: String
DefinitionUri: String
EndpointConfiguration: String
GatewayResponses: Map
MethodSettings: MethodSettings
MinimumCompressionSize: Integer
25
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Models: Map
OpenApiVersion: String
StageName: String
Tags: Map
TracingEnabled: Boolean
Variables: Map
Properties
AccessLogSetting
Type: AccessLogSetting
Required: No
For more information about configuring access using AWS SAM see Controlling Access to API
Gateway APIs (p. 97) in the AWS Serverless Application Model Developer Guide.
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
BinaryMediaTypes
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.
Type: List
Required: No
Type: Boolean
Required: No
26
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Type: String
Required: No
Type: CanarySetting
Required: No
Manage Cross-origin resource sharing (CORS) for all your API Gateway APIs. Specify the domain to
allow as a string or specify a dictionary with additional Cors configuration. NOTE: Cors requires SAM
to modify your OpenAPI definition. So, it works only inline OpenApi defined with DefinitionBody.
For more information about CORS, see Enable CORS for an API Gateway REST API Resource in the
Amazon API Gateway Developer Guide..
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
DefinitionBody
OpenAPI specification that describes your API. If neither DefinitionUri nor DefinitionBody are
specified, SAM will generate a DefinitionBody for you based on your template configuration.
Type: String
Required: No
AWS S3 Uri, local file path, or location object of the the OpenAPI document defining the API. The
AWS S3 object this property references must be a valid OpenAPI file. If neither DefinitionUri
nor DefinitionBody are specified, SAM will generate a DefinitionBody for you based on your
template configuration.
If a local file path is provided, the template must go through the workflow that includes the sam
deploy or sam package command, in order for the definition to be transformed properly.
Intrinsic functions are not supported in external OpenApi files. Use instead the DefinitionBody
property with the Include Transform to define OpenApi definition.
Type: String
27
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Required: No
Type: String
Required: No
Configures Gateway Reponses for an API. Gateway Responses are responses returned by API
Gateway, either directly or through the use of Lambda Authorizers. For more information, see the
documentation for the Api Gateway OpenApi extension for Gateway Responses.
Type: Map
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
MethodSettings
Configures all settings for API stage including Logging, Metrics, CacheTTL, Throttling.
Type: MethodSettings
Required: No
Type: Integer
Required: No
The schemas to be used by your API methods. These schemas can be described using JSON or YAML.
See the Examples section at the bottom of this page for example models.
Type: Map
Required: No
28
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
OpenApiVersion
Version of OpenApi to use. This can either be 2.0 for the Swagger specification, or one of
the OpenApi 3.0 versions, like 3.0.1. For more information about OpenAPI, see the OpenAPI
Specification.
Note: Setting this property to any valid value will also remove the stage Stage that SAM creates.
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
StageName
The name of the stage, which API Gateway uses as the first path segment in the invoke Uniform
Resource Identifier (URI).
Type: String
Required: Yes
A map (string to string) that specifies the tags to be added to this API Gateway stage. 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.
Type: Map
Required: No
Indicates whether active tracing with X-Ray is enabled for the stage.
Type: Boolean
Required: No
A map (string to string) 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._~:/?#&=,-]+.
Type: Map
29
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Required: No
Examples
SimpleApiExample
A simple API definition
YAML
AWSTemplateFormatVersion: '2010-09-09'
Description: AWS SAM template with a simple API definition
Resources:
ApiFunction:
Properties:
Events:
ApiEvent:
Properties:
Method: get
Path: /
RestApiId:
Ref: ApiGatewayApi
Type: Api
Handler: index.handler
InlineCode: "def handler(event, context):\n return {'body': 'Hello World!',\
\ 'statusCode': 200}\n"
Runtime: python3.7
Type: AWS::Serverless::Function
ApiGatewayApi:
Properties:
StageName: prod
Type: AWS::Serverless::Api
Transform: AWS::Serverless-2016-10-31
ApiCorsExample
AWS SAM template with API defined in an external Swagger file along with Lambda integrations and
CORS configurations. See GitHub for the full example.
YAML
Properties:
Cors: '''www.example.com'''
DefinitionBody:
Fn::Transform:
Name: AWS::Include
Parameters:
Location: s3://bucket/swagger.yaml
StageName: Prod
Type: AWS::Serverless::Api
ApiCognitoAuthExample
AWS SAM template with an API that uses AWS Cognito to authorize requests against the API. See GitHub
for the full example.
30
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
YAML
Properties:
Auth:
Authorizers:
MyCognitoAuthorizer:
UserPoolArn:
Fn::GetAtt:
- MyCognitoUserPool
- Arn
DefaultAuthorizer: MyCognitoAuthorizer
Cors: '''*'''
StageName: Prod
Type: AWS::Serverless::Api
ApiAuth
Configure authorization to control access to your API Gateway API.
For more information and examples for configuring access using AWS SAM see Controlling Access to API
Gateway APIs (p. 97) in the AWS Serverless Application Model Developer Guide.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
AddDefaultAuthorizerToCorsPreflight: Boolean
ApiKeyRequired: Boolean
Authorizers: CognitoAuthorizer (p. 33) | LambdaTokenAuthorizer (p. 38)
| LambdaRequestAuthorizer (p. 35)
DefaultAuthorizer: String
InvokeRole: String
ResourcePolicy: ResourcePolicyStatement (p. 41)
Properties
AddDefaultAuthorizerToCorsPreflight
Type: Boolean
Required: No
Default: True
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
ApiKeyRequired
If set to true then an API key is required for all API events. For more information about API keys see
Create and Use Usage Plans with API Keys in the API Gateway Developer Guide.
31
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Type: Boolean
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Authorizers
For more information, see Controlling Access to API Gateway APIs (p. 97) in the AWS Serverless
Application Model Developer Guide.
Required: No
Default: None
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Additional Notes: SAM adds the Authorizers to the OpenApi definition of an Api.
DefaultAuthorizer
Specify a default authorizer for an API Gateway API, which will be used for authorizing API calls by
default.
Note: If the Api EventSource for the function associated with this Api is configured to use IAM
Permissions, then this property must be set to AWS_IAM, otherwise an error will result.
Type: String
Required: No
Default: None
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
InvokeRole
Sets integration credentials for all resources and methods to this value.
Type: String
Required: No
Default: CALLER_CREDENTIALS
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
ResourcePolicy
32
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
CognitoAuth
YAML
Auth:
AddDefaultAuthorizerToCorsPreflight: false
ApiKeyRequired: false
Authorizers:
MyCognitoAuth:
AuthType: COGNITO_USER_POOLS
UserPoolArn:
Fn::GetAtt:
- MyUserPool
- Arn
DefaultAuthorizer: MyCognitoAuth
InvokeRole: CALLER_CREDENTIALS
ResourcePolicy:
CustomStatements:
- Action: execute-api:Invoke
Condition:
IpAddress:
aws:SourceIp: 1.2.3.4
Effect: Allow
Principal: '*'
Resource: execute-api:/Prod/PUT/get
IpRangeBlacklist:
- 10.20.30.40
CognitoAuthorizer
Define a Amazon Cognito User Pool authorizer.
For more information and examples, see Controlling Access to API Gateway APIs (p. 97) in the AWS
Serverless Application Model Developer Guide.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
33
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Properties
Identity
This property can be used to specify an IdentitySource in an incoming request for an authorizer
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
UserPoolArn
Can refer to a user pool/specify a userpool arn to which you want to add this cognito authorizer
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
CognitoAuth
YAML
Auth:
Authorizers:
MyCognitoAuth:
Identity:
Header: MyAuthorizationHeader
ValidationExpression: myauthvalidationexpression
UserPoolArn:
Fn::GetAtt:
- MyCognitoUserPool
- Arn
CognitoAuthorizationIdentity
This property can be used to specify an IdentitySource in an incoming request for an authorizer. For more
information about IdentitySource see the ApiGateway Authorizer OpenApi extension.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Header: String
ReauthorizeEvery: Integer
ValidationExpression: String
34
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Properties
Header
Type: String
Required: No
Default: Authorization
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
ReauthorizeEvery
The time-to-live (TTL) period, in seconds, that specifies how long API Gateway caches authorizer
results. If you specify a value greater than 0, API Gateway caches the authorizer responses. By
default, API Gateway sets this property to 300. The maximum value is 3600, or 1 hour.
Type: Integer
Required: No
Default: 300
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
ValidationExpression
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
CognitoAuthIdentity
YAML
Identity:
Header: MyCustomAuthHeader
ReauthorizeEvery: 30
ValidationExpression: Bearer.*
LambdaRequestAuthorizer
Configure a Lambda Authorizer to control access to your Api with a Lambda function.
For more information and examples, see Controlling Access to API Gateway APIs (p. 97) in the AWS
Serverless Application Model Developer Guide.
35
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
FunctionArn: String
FunctionInvokeRole: String
FunctionPayloadType: String
Identity: LambdaRequestAuthorizationIdentity (p. 37)
Properties
FunctionArn
Specify the function arn of the Lambda function which gives the authorization to Api
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
FunctionInvokeRole
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
FunctionPayloadType
This property can be used to define the type of Lambda Authorizer for an Api.
Type: String
Required: No
Default: TOKEN
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Identity
This property can be used to specify an IdentitySource in an incoming request for an authorizer
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
36
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Examples
LambdaRequestAuth
YAML
Authorizer:
MyLambdaRequestAuth:
FunctionArn:
Fn::GetAtt:
- MyAuthFunction
- Arn
FunctionInvokeRole:
Fn::GetAtt:
- LambdaAuthInvokeRole
- Arn
FunctionPayloadType: REQUEST
Identity:
Headers:
- Authorization1
LambdaRequestAuthorizationIdentity
This property can be used to specify an IdentitySource in an incoming request for an authorizer. For more
information about IdentitySource see the ApiGateway Authorizer OpenApi extension.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Context: List
Headers: List
QueryStrings: List
ReauthorizeEvery: Integer
StageVariables: List
Properties
Context
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Headers
Type: List
Required: No
37
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
QueryStrings
Converts the given query strings to comma-separated string of mapping expressions of format
method.request.querystring.queryString.
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
ReauthorizeEvery
The time-to-live (TTL) period, in seconds, that specifies how long API Gateway caches authorizer
results. If you specify a value greater than 0, API Gateway caches the authorizer responses. By
default, API Gateway sets this property to 300. The maximum value is 3600, or 1 hour.
Type: Integer
Required: No
Default: 300
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
StageVariables
Converts the given stage variables to comma-separated string of mapping expressions of format
stageVariables.stageVariable.
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
LambdaRequestIdentity
YAML
Identity:
Context:
- authcontext
Headers:
- Authorization
QueryStrings:
- auth
ReauthorizeEvery: 100
StageVariables:
- VARIABLE
LambdaTokenAuthorizer
Configure a Lambda Authorizer to control access to your Api with a Lambda function.
38
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
For more information and examples, see Controlling Access to API Gateway APIs (p. 97) in the AWS
Serverless Application Model Developer Guide.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
FunctionArn: String
FunctionInvokeRole: String
FunctionPayloadType: String
Identity: LambdaTokenAuthorizationIdentity (p. 40)
Properties
FunctionArn
Specify the function arn of the Lambda function which gives the authorization to Api
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
FunctionInvokeRole
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
FunctionPayloadType
This property can be used to define the type of Lambda Authorizer for an Api.
Type: String
Required: No
Default: TOKEN
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Identity
This property can be used to specify an IdentitySource in an incoming request for an authorizer.
Required: No
39
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
LambdaTokenAuth
YAML
Authorizers:
MyLambdaTokenAuth:
FunctionArn:
Fn::GetAtt:
- MyAuthFunction
- Arn
Identity:
Header: MyCustomAuthHeader
ReauthorizeEvery: 20
ValidationExpression: mycustomauthexpression
BasicLambdaTokenAuth
YAML
Authorizers:
MyLambdaTokenAuth:
FunctionArn:
Fn::GetAtt:
- MyAuthFunction
- Arn
LambdaTokenAuthorizationIdentity
This property can be used to specify an IdentitySource in an incoming request for an authorizer. For more
information about IdentitySource see the ApiGateway Authorizer OpenApi extension.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
ReauthorizeEvery: Integer
ValidationExpression: String
Properties
ReauthorizeEvery
The time-to-live (TTL) period, in seconds, that specifies how long API Gateway caches authorizer
results. If you specify a value greater than 0, API Gateway caches the authorizer responses. By
default, API Gateway sets this property to 300. The maximum value is 3600, or 1 hour.
Type: Integer
Required: No
40
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Default: 300
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
ValidationExpression
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
LambdaTokenIdentity
YAML
Identity:
Header: Auth
ReauthorizeEvery: 30
ValidationExpression: Bearer.*
ResourcePolicyStatement
Configure Resource Policy for all methods and paths on an API.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
AwsAccountBlacklist: List
AwsAccountWhitelist: List
CustomStatements: List
IpRangeBlacklist: List
IpRangeWhitelist: List
SourceVpcBlacklist: List
SourceVpcWhitelist: List
Properties
AwsAccountBlacklist
Resource Policy statements will be generated and attached to the Api for blacklisting the given list
of Aws accounts
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
41
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
AwsAccountWhitelist
Resource Policy statements will be generated and attached to the Api for whitelisting the given list
of Aws accounts
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
CustomStatements
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
IpRangeBlacklist
Resource Policy statements will be generated and attached to the Api for blacklisting the given list
of Ip addresses or ranges
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
IpRangeWhitelist
Resource Policy statements will be generated and attached to the Api for whitelisting the given list
of Ip addresses or ranges
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
SourceVpcBlacklist
Resource Policy statements will be generated and attached to the Api for blacklisting the given list
of Source Vpcs or Vpc endpoints
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
SourceVpcWhitelist
Resource Policy statements will be generated and attached to the Api for whitelisting the given list
of Source Vpcs or Vpc endpoints
Type: List
42
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
SourceVpcBlacklist
YAML
Auth:
ResourcePolicy:
AwsAccountWhitelist:
- '123456789101'
CustomStatements:
- Action: execute-api:Invoke
Condition:
IpAddress:
aws:SourceIp: 1.2.3.4
Effect: Allow
Principal: '*'
Resource: execute-api:/Prod/PUT/get
IpRangeBlacklist:
- 10.20.30.40
- 1.2.3.4
SourceVpcBlacklist:
- vpce-1a2b3c4d
CorsConfiguration
Manage cross-origin resource sharing (CORS) for your API Gateway APIs. Specify the domain to allow as a
string or specify a dictionary with additional Cors configuration. NOTE: Cors requires SAM to modify your
OpenAPI definition. So, it works with inline OpenApi defined with DefinitionBody.
For more information about CORS, see Enable CORS for an API Gateway REST API Resource in the
Amazon API Gateway Developer Guide.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
AllowCredentials: String
AllowHeaders: String
AllowMethods: String
AllowOrigin: String
MaxAge: String
Properties
AllowCredentials
43
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
AllowHeaders
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
AllowMethods
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
AllowOrigin
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
MaxAge
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
CorsConfiguration
YAML
Cors:
AllowCredentials: true
AllowHeaders: X-Forwarded-For
AllowMethods: POST, GET
44
AWS Serverless Application Model Developer Guide
AWS::Serverless::Application
AllowOrigin: www.example.com
MaxAge: 600
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
AWS::CloudFormation::Stack resources, which can contain multiple other resources including other
AWS::Serverless::Application (p. 45) resources.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Type: AWS::Serverless::Application
Properties:
Location: String | ApplicationLocationObject (p. 47)
NotificationARNs: List
Parameters: Map
Tags: Map
TimeoutInMinutes: Integer
Properties
Location
If a template URL is provided, it must follow the format specified in the CloudFormation
TemplateUrl documentation and contain a valid CloudFormation or SAM template. An
ApplicationLocationObject (p. 47) can be used to specify an application that has been published
to the AWS Serverless Application Repository.
If a local file path is provided, the template must go through the workflow that includes the sam
deploy or sam package command, in order for the application to be transformed properly.
Required: Yes
A list of existing Amazon SNS topics where notifications about stack events are sent.
Type: List
Required: No
45
AWS Serverless Application Model Developer Guide
AWS::Serverless::Application
Parameters
Type: Map
Required: No
A map (string to string) that specifies the tags to be added to this application. 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.
Type: Map
Required: No
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.
Type: Integer
Required: No
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 AWS::CloudFormation::Stack resource.
For more information about using the Ref function, see Ref.
Fn::GetAtt
Fn::GetAtt returns a value for a specified attribute of this type. The following are the available attributes
and sample return values.
46
AWS Serverless Application Model Developer Guide
AWS::Serverless::Application
GetAtt
Outputs.ApplicationOutputName
Examples
SAR Application
Application that uses a template from the Serverless Application Repository
YAML
Properties:
Location:
ApplicationId: arn:aws:serverlessrepo:us-east-1:012345678901:applications/my-
application
SemanticVersion: 1.0.0
Parameters:
IntegerParameter: 2
StringParameter: parameter-value
Type: AWS::Serverless::Application
Normal-Application
Application from an S3 url
YAML
Properties:
Location: https://s3.amazonaws.com/demo-bucket/template.yaml
Type: AWS::Serverless::Application
ApplicationLocationObject
An application that has been published to the AWS Serverless Application Repository.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
ApplicationId: String
SemanticVersion: String
Properties
ApplicationId
Type: String
47
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
SemanticVersion
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
my-application
YAML
Location:
ApplicationId: arn:aws:serverlessrepo:us-east-1:012345678901:applications/my-application
SemanticVersion: 1.0.0
AWS::Serverless::Function
Creates a Lambda function, IAM execution role, and event source mappings which trigger the function.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Type: AWS::Serverless::Function
Properties:
AutoPublishAlias: String
CodeUri: String | FunctionCode (p. 82)
DeadLetterQueue: Map | DeadLetterQueue (p. 55)
DeploymentPreference: DeploymentPreference (p. 56)
Description: String
Environment: Environment
Events: EventSource (p. 58)
FunctionName: String
Handler: String
InlineCode: String
KmsKeyArn: String
Layers: List
MemorySize: Integer
PermissionsBoundary: String
Policies: String | List | Map
ReservedConcurrentExecutions: Integer
Role: String
Runtime: String
Tags: Map
48
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Timeout: Integer
Tracing: String
VersionDescription: String
VpcConfig: VpcConfig
Properties
AutoPublishAlias
Name of the Lambda alias. For more information about Lambda aliases, see AWS Lambda Function
Aliases.
This AWS SAM property generates two additional resources: an AWS::Lambda::Version resource and
an AWS::Lambda::Alias resource.
For examples that use this property, see Deploying Serverless Applications Gradually (p. 118).
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
CodeUri
AWS S3 Uri, local file path, or FunctionCode (p. 82) object of the function code.
If an AWS S3 Uri or FunctionCode (p. 82) object is provided, the AWS S3 object referenced must
be a valid Lambda deployment package.
If a local file path is provided, the template must go through the workflow that includes the sam
deploy or sam package command, in order for the code to be transformed properly.
Required: Conditional
Configures SNS topic or SQS queue where Lambda sends events that it can't process. For more
information about dead letter queue functionality, see AWS Lambda Function Dead Letter Queues.
Required: No
49
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
See Also: See the Deploying Serverless Applications Gradually (p. 118) documentation for more
information about this property.
Description
Type: String
Required: No
Type: Environment
Required: No
Specifies the events that trigger this function. Events consist of a type and a set of properties that
depend on the type.
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
FunctionName
A name for the function. If you don't specify a name, a unique name will be generated for you.
Type: String
Required: No
50
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: String
Required: Yes
Type: String
Required: Conditional
CloudFormation Compatibility: This property is passed directly to the ZipFile property of the
AWS::Lambda::Function Code data type.
KmsKeyArn
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.
Type: String
Required: No
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.
Type: List
Required: No
Type: Integer
Required: No
ARN of a permissions boundary to use for this function's execution role. This property only works if
the Role is generated for you.
51
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: String
Required: No
One or more policies that this function needs, which will be appended to the default role for this
function.
This property accepts a single string or a list of strings, and can be the name of AWS managed IAM
policies or SAM Policy Templates, or inline IAM policy document(s) formatted in YAML. If the Role
property is set, this property has no meaning.
For more information about AWS managed IAM policies, see AWS Managed Policies. For more
informationa about AWS SAM Policy Templates, see AWS SAM Policy Templates (p. 150). For more
information about inline policies, see Inline Policies.
Required: No
The maximum of concurrent executions you want to reserve for the function.
For more information about this property see AWS Lambda Function Scaling in the AWS Lambda
Developer Guide.
Type: Integer
Required: No
Type: String
Required: No
Type: String
Required: Yes
52
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Tags
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.
Type: Map
Required: No
Maximum time that the function can run before it is killed in seconds.
Type: Integer
Required: No
Default: 3
String that specifies the function's X-Ray tracing mode. For more information about X-Ray, see Using
AWS X-Ray in the AWS Lambda Developer Guide.
Type: String
Required: No
A string that specifies the Description field which will be added on the new lambda version resource.
Type: String
Required: No
Configuration to enable this function to access private resources within your VPC.
Type: VpcConfig
Required: No
53
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
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.
For more information about using the Ref function, see Ref.
Fn::GetAtt
Fn::GetAtt returns a value for a specified attribute of this type. The following are the available attributes
and sample return values.
GetAtt
Arn
Examples
Simple Function
Base case example of an AWS::Serverless::Function resource.
YAML
Properties:
CodeUri: s3://bucket/key
Handler: index.handler
Runtime: python3.6
Type: AWS::Serverless::Function
YAML
Properties:
Handler: index.handler
InlineCode: "def handler(event, context):\n print(\"Hello, world!\")\n"
Layers:
- Ref: MyLayer
Policies:
- AWSLambdaExecute
- Statement:
- Action:
- s3:GetObject
- s3:GetObjectACL
Effect: Allow
Resource: arn:aws:s3:::my-bucket/*
Version: '2012-10-17'
ReservedConcurrentExecutions: 30
Runtime: python3.6
Timeout: 120
54
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Tracing: active
Type: AWS::Serverless::Function
DeadLetterQueue
Specifies an SQS queue or SNS topic that AWS Lambda (Lambda) sends events to when it can't process
them. For more information about dead letter queue functionality, see AWS Lambda Function Dead
Letter Queues.
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
To declare this entity in your AWS SAM template, use the following syntax:
YAML
TargetArn: String
Type: String
Properties
TargetArn
The Amazon Resource Name (ARN) of an Amazon SQS queue or Amazon SNS topic.
Type: String
Required: No
CloudFormation Compatibility: This property is passed directly to the TargetArn property of the
AWS::Lambda::Function DeadLetterConfig data type.
Type
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
DeadLetterQueue
YAML
DeadLetterQueue:
55
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
TargetArn: arn:aws:sns:us-east-2:123456789012:my-topic
Type: SNS
DeploymentPreference
Specifies the configurations to enable gradual Lambda deployments. For more information about
configuring gradual Lambda deployments, see Deploying Serverless Applications Gradually (p. 118).
Note: You must specify an AutoPublishAlias in your AWS::Serverless::Function (p. 48) to use a
DeploymentPreference object, otherwise an error will result.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Alarms: List
Enabled: Boolean
Hooks: Hooks (p. 57)
Role: String
Type: String
Properties
Alarms
A list of CloudWatch alarms that you want to be triggered by any errors raised by the deployment.
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Enabled
Type: Boolean
Required: No
Default: True
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Hooks
Validation Lambda functions that are run before and after traffic shifting.
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
56
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Role
An IAM role ARN that CodeDeploy will use for traffic shifting. An IAM role will not be created if this is
provided.
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Type
There are two categories of deployment types at the moment: Linear and Canary. For
more information about available deployment types see Deploying Serverless Applications
Gradually (p. 118).
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
DeploymentPreference
Example deployment preference
YAML
DeploymentPreference:
Alarms:
- Ref: AliasErrorMetricGreaterThanZeroAlarm
- Ref: LatestVersionErrorMetricGreaterThanZeroAlarm
Enabled: true
Hooks:
PostTraffic:
Ref: PostTrafficLambdaFunction
PreTraffic:
Ref: PreTrafficLambdaFunction
Type: Canary10Percent10Minutes
Hooks
Validation Lambda functions that are run before and after traffic shifting.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
PostTraffic: String
PreTraffic: String
57
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Properties
PostTraffic
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
PreTraffic
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
Hooks
YAML
Hooks:
PostTraffic:
Ref: PostTrafficLambdaFunction
PreTraffic:
Ref: PreTrafficLambdaFunction
EventSource
The object describing the source of events which trigger the function. Each event consists of a type and
a set of properties that depend on that type. For more information about the properties of each event
source, see the topic corresponding to that type.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Properties: S3 (p. 76) | SNS (p. 79) | Kinesis (p. 74) | DynamoDB (p. 71)
| SQS (p. 81) | Api (p. 60) | Schedule (p. 78) | CloudWatchEvent (p. 67)
| CloudWatchLogs (p. 69) | IoTRule (p. 73) | AlexaSkill (p. 59) | Cognito (p. 70)
Type: String
58
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Properties
Properties
Object describing properties of this event mapping. The set of properties must conform to the
defined Type.
Type: S3 (p. 76) | SNS (p. 79) | Kinesis (p. 74) | DynamoDB (p. 71) | SQS (p. 81) |
Api (p. 60) | Schedule (p. 78) | CloudWatchEvent (p. 67) | CloudWatchLogs (p. 69) |
IoTRule (p. 73) | AlexaSkill (p. 59) | Cognito (p. 70)
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Type
Supported values: S3, SNS, Kinesis, DynamoDB, SQS, Api, Schedule, CloudWatchEvent,
CloudWatchLogs, IoTRule, AlexaSkill, Cognito.
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
API-Event
YAML
ApiEvent:
Properties:
Method: get
Path: /group/{user}
RestApiId:
Ref: MyApi
Type: Api
AlexaSkill
Adds an Alexa Skills Kit Trigger.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
SkillId: String
59
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Properties
SkillId
The Alexa Skill ID for your Alexa Skill. For more information about Skill ID see Configure the trigger
for a Lambda function in the Alexa Skills Kit documentation.
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
AlexaSkillTrigger
YAML
AlexaSkillEvent:
Type: AlexaSkill
Api
The object describing an event source with type Api. If an AWS::Serverless::Api (p. 25) resource is
defined, the path and method values must correspond to an operation in the OpenApi definition of the
API.
If no AWS::Serverless::Api (p. 25) 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.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Properties
Auth
60
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
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.
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Method
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Path
Uri path for which this function is invoked. Must start with /.
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
RequestModel
Request model to use for this specific Api+Path+Method. This should reference the name of a model
specified in the Models section of an AWS::Serverless::Api (p. 25) resource.
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
RequestParameters
Request parameters configuration for this specific Api+Path+Method. All parameter names
must start with method.request and must be limited to method.request.header,
method.request.querystring, or method.request.path.
If a parameter is a string and not a Function Request Parameter Object, then Required and
Caching will default to False.
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
RestApiId
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 (p. 25) resource defined in this template.
61
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
If not defined, a default AWS::Serverless::Api (p. 25) resource is created using a generated
OpenApi document contains a union of all paths and methods defined by Api events defined in this
template that do not specify a RestApiId.
This cannot reference an AWS::Serverless::Api (p. 25) resource defined in another template.
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Stage
Type: String
Required: No
Default: Prod
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
ApiEvent
YAML
ApiEvent:
Properties:
Method: get
Path: /path
RequestParameters:
- method.request.header.Authorization
Type: Api
FunctionAuth
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
ApiKeyRequired: Boolean
Authorizer: String
InvokeRole: String
ResourcePolicy: ResourcePolicyStatement (p. 64)
62
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Properties
ApiKeyRequired
Type: Boolean
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Authorizer
If you have specified a Global Authorizer on the API and want to make a specific Function public,
override by setting Authorizer to NONE.
Type: String
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
InvokeRole
Type: String
Required: No
Default: CALLER_CREDENTIALS
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
Function-Auth
Specifing Authorization at Function level
YAML
Auth:
ApiKeyRequired: true
63
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Authorizer: NONE
ResourcePolicyStatement
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
AwsAccountBlacklist: List
AwsAccountWhitelist: List
CustomStatements: List
IpRangeBlacklist: List
IpRangeWhitelist: List
SourceVpcBlacklist: List
SourceVpcWhitelist: List
Properties
AwsAccountBlacklist
Resource Policy statements will be generated and attached to the Api for blacklisting the given list
of Aws accounts
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
AwsAccountWhitelist
Resource Policy statements will be generated and attached to the Api for whitelisting the given list
of Aws accounts
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
CustomStatements
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
IpRangeBlacklist
Resource Policy statements will be generated and attached to the Api for blacklisting the given list
of Ip addresses or ranges
64
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
IpRangeWhitelist
Resource Policy statements will be generated and attached to the Api for whitelisting the given list
of Ip addresses or ranges
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
SourceVpcBlacklist
Resource Policy statements will be generated and attached to the Api for blacklisting the given list
of Source Vpcs or Vpc endpoints
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
SourceVpcWhitelist
Resource Policy statements will be generated and attached to the Api for whitelisting the given list
of Source Vpcs or Vpc endpoints
Type: List
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
SourceVpcBlacklist
Blacklisting source VPC or VPC endpoint
YAML
Auth:
ResourcePolicy:
AwsAccountWhitelist:
- '123456789101'
CustomStatements:
- Action: execute-api:Invoke
Condition:
IpAddress:
aws:SourceIp: 1.2.3.4
Effect: Allow
Principal: '*'
Resource: execute-api:/Prod/PUT/get
IpRangeBlacklist:
65
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
- 10.20.30.40
- 1.2.3.4
SourceVpcBlacklist:
- vpce-1a2b3c4d
RequestModel
Configure Request Model for a specific Api+Path+Method.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Model: String
Required: Boolean
Properties
Model
Name of a model defined in the Models property of the AWS::Serverless::Api (p. 25).
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Required
adds a required property in the parameters section of Open Api definition for given Api endpoint
Type: Boolean
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
Request Model
Request Model Example
YAML
RequestModel:
Model: User
Required: true
RequestParameter
Configure Request Parameter for a specific Api+Path+Method.
66
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Caching: Boolean
Required: Boolean
Properties
Caching
Type: Boolean
Required: Conditional
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Required
Type: Boolean
Required: Conditional
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
Request Parameter
Example of setting Requuest Parameters
YAML
RequestParameters:
- method.request.header.Authorization:
Caching: true
Required: true
CloudWatchEvent
The object describing an event source with type CloudWatchEvent
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
EventBusName: String
67
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Input: String
InputPath: String
Pattern: EventPattern
Properties
EventBusName
The event bus to associate with this rule. If you omit this, the default event bus is used.
Type: String
Required: No
Default: default
Valid JSON text passed to the target. If you use this property, nothing from the event text itself is
passed to the target.
Type: String
Required: No
When you don't want to pass the entire matched event, InputPath describes which part of the event
to pass to the target.
Type: String
Required: No
Describes which events are routed to the specified target. For more information, see Events and
Event Patterns in EventBridge in the Amazon EventBridge User Guide
Type: EventPattern
Required: Yes
Examples
CloudWatchEvent
68
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
YAML
CWEvent:
Properties:
Input: '{"Key": "Value"}'
Pattern:
detail:
state:
- terminated
Type: CloudWatchEvent
CloudWatchLogs
This event generates a AWS::Logs::SubscriptionFilter resource and specifies a subscription filter and
associates it with the specified log group.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
FilterPattern: String
LogGroupName: String
Properties
FilterPattern
The filtering expressions that restrict what gets delivered to the destination AWS resource. For more
information about the filter pattern syntax, see Filter and Pattern Syntax.
Type: String
Required: Yes
The log group to associate with the subscription filter. All log events that are uploaded to this log
group are filtered and delivered to the specified AWS resource if the filter pattern matches the log
events.
Type: String
Required: Yes
Examples
69
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
YAML
CWLog:
Properties:
FilterPattern: My pattern
LogGroupName:
Ref: CloudWatchLambdaLogsGroup
Type: CloudWatchLogs
Cognito
The object describing an event source with type Cognito.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Trigger: List
UserPool: String
Properties
Trigger
The Lambda trigger configuration information for the new user pool.
Type: List
Required: Yes
Type: String
Required: Yes
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Examples
Cognito Event
YAML
CognitoUserPoolPreSignup:
Properties:
Trigger: PreSignUp
70
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
UserPool:
Ref: MyCognitoUserPool
Type: Cognito
DynamoDB
DynamoDB streaming event source type.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
BatchSize: Integer
BisectBatchOnFunctionError: Boolean
DestinationConfig: DestinationConfig
Enabled: Boolean
MaximumBatchingWindowInSeconds: Integer
MaximumRecordAgeInSeconds: Integer
MaximumRetryAttempts: Integer
ParallelizationFactor: Integer
StartingPosition: String
Stream: String
Properties
BatchSize
Type: Integer
Required: No
Default: 100
Minimum: 1
Maximum: 1000
BisectBatchOnFunctionError
If the function returns an error, split the batch in two and retry.
Type: Boolean
Required: No
An Amazon SQS queue or Amazon SNS topic destination for discarded records.
71
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: DestinationConfig
Required: No
Type: Boolean
Required: No
The maximum amount of time to gather records before invoking the function, in seconds.
Type: Integer
Required: No
The maximum age of a record that Lambda sends to a function for processing.
Type: Integer
Required: No
The maximum number of times to retry when the function returns an error.
Type: Integer
Required: No
Type: Integer
Required: No
72
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: String
Required: Yes
Type: String
Required: Yes
Examples
DynamoDB Event
DynamoDB Event
YAML
Properties:
BatchSize: 10
Enabled: false
StartingPosition: TRIM_HORIZON
Stream: arn:aws:dynamodb:us-east-1:123456789012:table/TestTable/
stream/2016-08-11T21:21:33.291
IoTRule
Creates an AWS::IoT::TopicRule resource to declare an AWS IoT rule. For more information see AWS
CloudFormation documentation
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
AwsIotSqlVersion: String
Sql: String
Properties
AwsIotSqlVersion
The version of the SQL rules engine to use when evaluating the rule.
Type: String
Required: No
73
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
The SQL statement used to query the topic. For more information, see AWS IoT SQL Reference in the
AWS IoT Developer Guide.
Type: String
Required: Yes
Examples
IOT Rule
YAML
IoTRule:
Properties:
Sql: SELECT * FROM 'topic/test'
Type: IoTRule
Kinesis
Kinesis event source configuration.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
BatchSize: Integer
BisectBatchOnFunctionError: Boolean
DestinationConfig: DestinationConfig
Enabled: Boolean
MaximumBatchingWindowInSeconds: Integer
MaximumRecordAgeInSeconds: Integer
MaximumRetryAttempts: Integer
ParallelizationFactor: Integer
StartingPosition: String
Stream: String
Properties
BatchSize
Type: Integer
74
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required: No
Default: 100
Minimum: 1
Maximum: 10000
BisectBatchOnFunctionError
If the function returns an error, split the batch in two and retry.
Type: Boolean
Required: No
An Amazon SQS queue or Amazon SNS topic destination for discarded records.
Type: DestinationConfig
Required: No
Type: Boolean
Required: No
The maximum amount of time to gather records before invoking the function, in seconds.
Type: Integer
Required: No
The maximum age of a record that Lambda sends to a function for processing.
Type: Integer
Required: No
75
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
MaximumRetryAttempts
The maximum number of times to retry when the function returns an error.
Type: Integer
Required: No
Type: Integer
Required: No
Type: String
Required: Yes
Type: String
Required: Yes
Examples
YAML
Properties:
BatchSize: 10
Enabled: false
StartingPosition: TRIM_HORIZON
Stream: arn:aws:kinesis:us-east-1:123456789012:stream/my-stream
S3
S3 event source type.
76
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Bucket: String
Events: String | List
Filter: S3NotificationFilter
Properties
Bucket
Type: String
Required: Yes
The Amazon S3 bucket event for which to invoke the AWS Lambda function. See Amazon S3
supported event types for valid values.
Required: Yes
CloudFormation Compatibility: This property is passed directly to the Event property of the
AWS::S3::Bucket LambdaConfiguration data type.
Filter
The filtering rules that determine which objects invoke the AWS Lambda function.
Type: S3NotificationFilter
Required: No
Examples
S3-Event
Example of an S3 Event
YAML
ImagesBucket:
Type: AWS::S3::Bucket
S3Event:
Properties:
77
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Bucket:
Ref: ImagesBucket
Events: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: name
Value: value
Type: S3
Schedule
This object describes an event source with type Schedule
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Description: String
Enabled: Boolean
Input: String
Name: String
Schedule: String
Properties
Description
Type: String
Required: No
Type: Boolean
Required: No
Valid JSON text passed to the target. If you use this property, nothing from the event text itself is
passed to the target.
Type: String
78
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required: No
The name of the rule. If you don't specify a name, AWS CloudFormation generates a unique physical
ID and uses that ID for the rule name.
Type: String
Required: No
The scheduling expression that determines when and how often the rule runs. For more information,
see Schedule Expressions for Rules.
Type: String
Required: Yes
Examples
YAML
CWSchedule:
Properties:
Description: test schedule
Enabled: false
Name: TestSchedule
Schedule: rate(1 minute)
Type: Schedule
SNS
SNS event source configuration.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
FilterPolicy: SnsFilterPolicy
Region: String
SqsSubscription: Boolean
Topic: String
79
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Properties
FilterPolicy
The filter policy JSON assigned to the subscription. For more information, see
GetSubscriptionAttributes in the Amazon Simple Notification Service API Reference.
Type: SnsFilterPolicy
Required: No
If no region is specified, CloudFormation uses the region of the caller as the default.
Type: String
Required: No
Set this property to true to enable batching SNS topic notifications in an SQS queue.
Type: Boolean
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Topic
Type: String
Required: Yes
Examples
YAML
Properties:
FilterPolicy:
80
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
price_usd:
- numeric:
- '>='
- 100
store:
- example_corp
Topic: arn:aws:sns:us-east-1:123456789012:my_topic
SQS
SQS event source type.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
BatchSize: Integer
Enabled: Boolean
Queue: String
Properties
BatchSize
Type: Integer
Required: No
Default: 10
Minimum: 1
Maximum: 10
Enabled
Type: Boolean
Required: No
Type: String
Required: Yes
81
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Examples
SQS Event
SQS Event
YAML
Properties:
BatchSize: 10
Enabled: false
Queue: arn:aws:sqs:us-west-2:012345678901:my-queue
Type: SQS
FunctionCode
The deployment package for a Lambda function.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Bucket: String
Key: String
Version: String
Properties
Bucket
Type: String
Required: Yes
CloudFormation Compatibility: This property is passed directly to the S3Bucket property of the
AWS::Lambda::Function Code data type.
Key
Type: String
Required: Yes
CloudFormation Compatibility: This property is passed directly to the S3Key property of the
AWS::Lambda::Function Code data type.
Version
For versioned objects, the version of the deployment package object to use.
82
AWS Serverless Application Model Developer Guide
AWS::Serverless::LayerVersion
Type: String
Required: No
Examples
FunctionCode
YAML
FunctionCode:
Bucket: mybucket-name
Key: mykey-name
Version: 121212
AWS::Serverless::LayerVersion
Creates a Lambda LayerVersion that contains library or runtime code needed by a Lambda Function.
Important Note: Since the release of the UpdateReplacePolicy resource attribute in AWS
CloudFormation, AWS::Lambda::LayerVersion (recommended) offers the same benefits as
AWS::Serverless::LayerVersion (p. 83).
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.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Type: AWS::Serverless::LayerVersion
Properties:
CompatibleRuntimes: List
ContentUri: String | LayerContent (p. 85)
Description: String
LayerName: String
LicenseInfo: String
RetentionPolicy: String
Properties
CompatibleRuntimes
Type: List
Required: No
83
AWS Serverless Application Model Developer Guide
AWS::Serverless::LayerVersion
AWS S3 Uri, local file path, or LayerContent object of the layer code.
If an AWS S3 Uri or LayerContent object is provided, The AWS S3 object referenced must be a valid
ZIP archive that contaions the contents of an AWS Lambda layer.
If a local file path is provided, the template must go through the workflow that includes the sam
deploy or sam package command, in order for the content to be transformed properly.
Required: Yes
Type: String
Required: No
Type: String
Required: No
Type: String
Required: No
Specifies whether old versions of your LayerVersion are retained or deleted after an update.
Type: String
84
AWS Serverless Application Model Developer Guide
AWS::Serverless::LayerVersion
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
Additional Notes: When you specify Retain, AWS SAM adds a Resource Attribute of
DeletionPolicy: Retain to the transformed AWS::Lambda::LayerVersion resource.
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.
For more information about using the Ref function, see Ref.
Examples
LayerVersionExample
Example of a LayerVersion
YAML
Properties:
CompatibleRuntimes:
- nodejs6.10
- nodejs8.10
ContentUri: s3://my-bucket/my-layer.zip
Description: Layer description
LayerName: MyLayer
LicenseInfo: Available under the MIT-0 license.
RetentionPolicy: Retain
LayerContent
A ZIP archive that contains the contents of an AWS Lambda layer.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Bucket: String
Key: String
Version: String
Properties
Bucket
85
AWS Serverless Application Model Developer Guide
AWS::Serverless::SimpleTable
Type: String
Required: Yes
CloudFormation Compatibility: This property is passed directly to the S3Bucket property of the
AWS::Lambda::LayerVersion Content data type.
Key
Type: String
Required: Yes
CloudFormation Compatibility: This property is passed directly to the S3Key property of the
AWS::Lambda::LayerVersion Content data type.
Version
For versioned objects, the version of the layer archive object to use.
Type: String
Required: No
Examples
LayerContent
YAML
LayerContent:
Bucket: mybucket-name
Key: mykey-name
Version: 121212
AWS::Serverless::SimpleTable
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.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Type: AWS::Serverless::SimpleTable
Properties:
PrimaryKey: PrimaryKeyObject (p. 88)
ProvisionedThroughput: ProvisionedThroughput
86
AWS Serverless Application Model Developer Guide
AWS::Serverless::SimpleTable
SSESpecification: SSESpecification
TableName: String
Tags: Map
Properties
PrimaryKey
Attribute name and type to be used as the table's primary key. If not provided, the primary key will
be a String with a value of id.
Note: The value of this property cannot be modified after this resource is created.
Required: No
CloudFormation Compatibility: This property is unique to AWS SAM and does not have an AWS
CloudFormation equivalent.
ProvisionedThroughput
Type: ProvisionedThroughput
Required: No
Type: SSESpecification
Required: No
Type: String
Required: No
A map (string to string) that specifies the tags to be added to this SimpleTable. 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.
Type: Map
87
AWS Serverless Application Model Developer Guide
AWS::Serverless::SimpleTable
Required: No
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.
For more information about using the Ref function, see Ref.
Examples
SimpleTableExample
Example of a SimpleTable
YAML
Properties:
PrimaryKey:
Name: id
Type: String
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
SSESpecification:
SSEEnabled: true
TableName: my-table
Tags:
AppType: Serverless
Department: Engineering
PrimaryKeyObject
The object describing the properties of a primary key.
Syntax
To declare this entity in your AWS SAM template, use the following syntax:
YAML
Name: String
Type: String
Properties
Name
88
AWS Serverless Application Model Developer Guide
Resource Attributes
Type: String
Required: Yes
Type: String
Required: Yes
Examples
PrimaryKey
YAML
Properties:
PrimaryKey:
Name: MyPrimaryKey
Type: String
For reference information for all the AWS resource and property types that are supported by
AWS CloudFormation and AWS SAM, see AWS Resource and Property Types Reference in the AWS
CloudFormation User Guide.
Resource Attributes
Resource attributes are attributes that you can add to a resource to control additional behaviors and
relationships. For more information about resource attributes, see Resource Attribute Reference in the
AWS CloudFormation User Guide.
AWS SAM resources support a subset of resource attributes that are supported by AWS CloudFormation
resources. To see which AWS SAM resources support which resource attributes, see the following table.
89
AWS Serverless Application Model Developer Guide
Intrinsic Functions
Intrinsic Functions
Intrinsic functions are built-in functions that enable you to assign values to properties that are only
available at runtime. For more information about intrinsic functions, see Intrinsic Function Reference in
the AWS CloudFormation User Guide.
AWS SAM supports a subset of API Gateway extensions. To see which API Gateway extensions are
supported by AWS SAM, see the following table.
x-amazon-apigateway-api-key-source Property No
x-amazon-apigateway-documentation Object No
x-amazon-apigateway-endpoint-configuration Object No
x-amazon-apigateway-integration.requestParameters Object No
90
AWS Serverless Application Model Developer Guide
API Gateway Extensions
x-amazon-apigateway-request-validator Property No
x-amazon-apigateway-request-validators Object No
x-amazon-apigateway-request-validators.requestValidator Object No
91
AWS Serverless Application Model Developer Guide
Validating AWS SAM Template Files
This section contains topics about how to validate your AWS SAM template, and how to build your
application with dependencies. It also contains topics for how to use AWS SAM for certain use cases like
working with Lambda layers, using nested applications, and controlling access to API Gateway APIs.
Topics
• Validating AWS SAM Template Files (p. 92)
• Building Applications with Dependencies (p. 92)
• Working with Layers (p. 93)
• Using Nested Applications (p. 94)
• Controlling Access to API Gateway APIs (p. 97)
Example:
sam validate
<path-to-file>/template.yml is a valid SAM Template
Note
The sam validate command requires AWS credentials to be configured. For more information,
see Configuration and Credential Files.
The sam build command iterates through the functions in your application, looks for a manifest file
(such as requirements.txt) that contain the dependencies, and automatically creates deployment
artifacts that you can deploy to Lambda using the sam package and sam deploy commands.
If your Lambda function depends on packages that have natively compiled programs, you can use
the --use-container flag. The --use-container flag compiles your functions in a Lambda-like
environment locally, so they are in the right format when you deploy them to the AWS Cloud.
Examples:
92
AWS Serverless Application Model Developer Guide
Working with Layers
The following is an example AWS SAM template with a Lambda function that includes a layer:
ServerlessFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: my_handler
Runtime: Python3.7
Layers:
- <LayerVersion ARN>
For more information about including layers in your application, see either AWS::Serverless::Function in
the AWS SAM GitHub repository, or AWS::Lambda::Function in the AWS CloudFormation User Guide.
When you invoke your function using one of the sam local CLI subcommands, the layers package of
your function is downloaded and cached on your local host. See the following chart for default cache
directory locations. After the package is cached, the AWS SAM CLI overlays the layers onto a Docker
image that's used to invoke your function. The AWS SAM CLI generates the names of the images it builds,
as well as the LayerVersions that are held in the cache. You can find more details about the schema in the
following sections.
To inspect the overlaid layers, execute the following command to start a bash session in the image that
you want to inspect:
Given a LayerVersionArn that's defined in your template, the AWS SAM CLI extracts the LayerName and
Version from the ARN. It creates a directory to place the layer contents in named LayerName-Version-
<first 10 characters of sha256 of ARN>.
Example:
ARN = arn:aws:lambda:us-west-2:111111111111:layer:myLayer:1
93
AWS Serverless Application Model Developer Guide
Using Nested Applications
To compute the unique layers hash, combine all unique layer names with a delimiter of '-', take the
SHA256 hash, and then take the first 25 characters.
Example:
ServerlessFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: my_handler
Runtime: Python3.7
Layers:
- arn:aws:lambda:us-west-2:111111111111:layer:myLayer:1
- arn:aws:lambda:us-west-2:111111111111:layer:mySecondLayer:1
Unique names are computed the same as the Layer Caching Directory name schema:
arn:aws:lambda:us-west-2:111111111111:layer:myLayer:1 = myLayer-1-926eeb5ff1
arn:aws:lambda:us-west-2:111111111111:layer:mySecondLayer:1 = mySecondLayer-1-6bc1022bdf
To compute the unique layers hash, combine all unique layer names with a delimiter of '-', take the
sha256 hash, and then take the first 25 characters:
myLayer-1-926eeb5ff1-mySecondLayer-1-6bc1022bdf = 2dd7ac5ffb30d515926aef
Then combine this value with the function's runtime, with a delimiter of '-':
python3.7-2dd7ac5ffb30d515926aefffd
OS Location
macOS ~/.aws-sam/layers-pkg
Unix ~/.aws-sam/layers-pkg
As serverless architectures grow, common patterns emerge in which the same components are defined in
multiple application templates. You can now separate out common patterns as dedicated applications,
94
AWS Serverless Application Model Developer Guide
Defining a Nested Application from the
AWS Serverless Application Repository
and then nest them as part of new or existing application templates. With nested applications, you can
stay more focused on the business logic that's unique to your application.
You can define nested applications from the following two sources:
• An AWS Serverless Application Repository application – You can define nested applications by
using applications that are available to your account in the AWS Serverless Application Repository.
These can be private applications in your account, applications that are privately shared with your
account, or applications that are publicly shared in the AWS Serverless Application Repository. For
more information about the different deployment permissions levels, see Application Deployment
Permissions and Publishing Applications in the AWS Serverless Application Repository Developer Guide.
• A local application – You can define nested applications by using applications that are stored on your
local file system.
See the following sections for details on how to use AWS SAM to define both of these types of nested
applications in your serverless application.
Note
The maximum number of applications that can be nested in a serverless application is 200.
The maximum number of parameters a nested application can have is 60.
To define an application that's hosted in the AWS Serverless Application Repository in your serverless
application's AWS SAM template, use the Copy as SAM Resource button on the detail page of every AWS
Serverless Application Repository application. To do this, follow these steps:
The following is an example SAM template section for a nested application that's hosted in the AWS
Serverless Application Repository:
Transform: AWS::Serverless-2016-10-31
Resources:
applicationaliasname:
Type: AWS::Serverless::Application
Properties:
Location:
95
AWS Serverless Application Model Developer Guide
Defining a Nested Application from the Local File System
ApplicationId: arn:aws:serverlessrepo:us-
east-1:123456789012:applications/application-alias-name
SemanticVersion: 1.0.0
Parameters:
# Optional parameter that can have default value overridden
# ParameterName1: 15 # Uncomment to override default value
# Required parameter that needs value to be provided
ParameterName2: YOUR_VALUE
If there are no required parameter settings, you can omit the Parameters: section of the template.
Important
Applications that contain nested applications hosted in the AWS Serverless Application
Repository inherit the nested applications' sharing restrictions.
For example, suppose an application is publicly shared, but it contains a nested application
that's only privately shared with the AWS account that created the parent application. In this
case, if your AWS account doesn't have permission to deploy the nested application, you aren't
able to deploy the parent application. For more information about permissions to deploy
applications, see Application Deployment Permissions and Publishing Applications in the AWS
Serverless Application Repository Developer Guide.
The following is an example SAM template section for a nested local application:
Transform: AWS::Serverless-2016-10-31
Resources:
applicationaliasname:
Type: AWS::Serverless::Application
Properties:
Location: ../my-other-app/template.yaml
Parameters:
# Optional parameter that can have default value overridden
# ParameterName1: 15 # Uncomment to override default value
# Required parameter that needs value to be provided
ParameterName2: YOUR_VALUE
If there are no parameter settings, you can omit the Parameters: section of the template.
96
AWS Serverless Application Model Developer Guide
Controlling Access to APIs
AWS SAM supports several mechanisms for controlling access to your API Gateway APIs:
• Amazon Cognito user pools. Amazon Cognito user pools are user directories in Amazon Cognito. A
client of your API must first sign a user in to the user pool, and obtain an identity or access token for
the user. Then your API is called with one of the returned tokens. The API call succeeds only if the
required token is valid. For more information about Amazon Cognito user pools, see Control Access to
REST API Using Amazon Cognito User Pools as Authorizer in the API Gateway Developer Guide. For an
example of Amazon Cognito user pools, see Example: Defining Amazon Cognito User Pools (p. 99)
later in this topic.
• IAM permissions. You can control who can invoke your API using IAM permissions. Users calling your
API must be authenticated with IAM credentials. Calls to your API only succeed if there is an IAM policy
attached to the IAM user that represents the API caller, an IAM group that contains the user, or an IAM
role that is assumed by the user. For more information about IAM permissions, see Control Access to an
API with IAM Permissions in the API Gateway Developer Guide. For an example of IAM permissions, see
Example: Defining IAM Permissions (p. 100) later in this topic.
• API keys. API keys are alphanumeric string values that you distribute to application developer
customers to grant access to your API. For more information about API keys, see Create and Use Usage
Plans with API Keys in the API Gateway Developer Guide. For an example of API keys, see Example:
Defining API Keys (p. 101) later in this topic.
• Resource policies. Resource policies are JSON policy documents that you can attach to an API Gateway
API to control whether a specified principal (typically an IAM user or role) can invoke the API. For more
information about resource policies, see Control Access to an API with Amazon API Gateway Resource
Policies in the API Gateway Developer Guide. For an example of resource policies, see Example: Defining
Resource Policies (p. 101) later in this topic.
In addition, you can use AWS SAM to customize the content of some API Gateway error responses. For
more information about customizing API Gateway error responses, see Set Up Gateway Responses to
Customize Error Responses. For an example of customized responses, see Example: Defining Customized
Responses (p. 102) later in this topic.
97
AWS Serverless Application Model Developer Guide
Example: Defining Lambda Token Authorizers
up yet, then Amazon Cognito user pools might be your best option. This is because when you set up user
pools, you also set up both authentication and access control automatically.
However, if your application already has authentication set up, then using Lambda authorizers might
be the best option. This is because you can call your existing authentication service and return a policy
document based on the response. Also, if your application requires custom authentication or access
control logic that user pools don't support, then Lambda authorizers might be your best option.
After you've decided which mechanism to use, see the corresponding section in this topic to see how to
use AWS SAM to configure your application to use that mechanism.
The following is an example AWS SAM template section for a Lambda Token authorizer:
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
DefaultAuthorizer: MyLambdaTokenAuthorizer
Authorizers:
MyLambdaTokenAuthorizer:
FunctionArn: !GetAtt MyAuthFunction.Arn
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: index.handler
Runtime: nodejs8.10
Events:
GetRoot:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: get
MyAuthFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: authorizer.handler
Runtime: nodejs8.10
For more information about API Gateway Lambda authorizers, see Use API Gateway Lambda Authorizers
in the API Gateway Developer Guide.
For a full sample application that includes a Lambda Token authorizer, see API Gateway + Lambda
TOKEN Authorizer Example.
98
AWS Serverless Application Model Developer Guide
Example: Defining Amazon Cognito User Pools
The following is an example AWS SAM template section for a Lambda Request authorizer:
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
DefaultAuthorizer: MyLambdaRequestAuthorizer
Authorizers:
MyLambdaRequestAuthorizer:
FunctionPayloadType: REQUEST
FunctionArn: !GetAtt MyAuthFunction.Arn
Identity:
QueryStrings:
- auth
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: index.handler
Runtime: nodejs8.10
Events:
GetRoot:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: get
MyAuthFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: authorizer.handler
Runtime: nodejs8.10
For more information about API Gateway Lambda authorizers, see Use API Gateway Lambda Authorizers
in the API Gateway Developer Guide.
For a full sample application that includes a Lambda Request authorizer, see API Gateway + Lambda
REQUEST Authorizer Example.
The following is an example AWS SAM template section for a user pool:
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Cors: "'*'"
Auth:
DefaultAuthorizer: MyCognitoAuthorizer
Authorizers:
MyCognitoAuthorizer:
UserPoolArn: !GetAtt MyCognitoUserPool.Arn
99
AWS Serverless Application Model Developer Guide
Example: Defining IAM Permissions
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: lambda.handler
Runtime: nodejs8.10
Events:
Root:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: GET
MyCognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
UserPoolName: !Ref CognitoUserPoolName
Policies:
PasswordPolicy:
MinimumLength: 8
UsernameAttributes:
- email
Schema:
- AttributeDataType: String
Name: email
Required: false
MyCognitoUserPoolClient:
Type: AWS::Cognito::UserPoolClient
Properties:
UserPoolId: !Ref MyCognitoUserPool
ClientName: !Ref CognitoUserPoolClientName
GenerateSecret: false
For more information about Amazon Cognito user pools, see Control Access to a REST API Using Amazon
Cognito User Pools as Authorizer in the API Gateway Developer Guide.
For a full sample application that includes a user pool as an authorizer, see API Gateway + Cognito Auth
+ Cognito Hosted Auth Example.
The following is an example AWS SAM template section for IAM permissions:
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
DefaultAuthorizer: AWS_IAM
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: index.handler
Runtime: nodejs8.10
100
AWS Serverless Application Model Developer Guide
Example: Defining API Keys
Events:
GetRoot:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: get
For more information about IAM permissions, see Control Access to an API Using IAM Permissions in the
API Gateway Developer Guide.
For a full sample application that includes a user pool as an authorizer, see API Gateway + IAM
Permissions Example.
The following is an example AWS SAM template section for API keys:
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Auth:
ApiKeyRequired: true # sets for all methods
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: index.handler
Runtime: nodejs8.10
Events:
ApiKey:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: get
Auth:
ApiKeyRequired: true
For more information about API keys, see Create and Use Usage Plans with API Keys in the API Gateway
Developer Guide.
The following is an example AWS SAM template section for resource policies:
Resources:
ExplicitApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
EndpointConfiguration: PRIVATE
101
AWS Serverless Application Model Developer Guide
Example: Defining Customized Responses
Auth:
ResourcePolicy:
CustomStatements: {
Effect: 'Allow',
Action: 'execute-api:Invoke',
Resource: ['execute-api:/*/*/*'],
Principal: '*'
}
MinimalFunction:
Type: 'AWS::Serverless::Function'
Properties:
CodeUri: s3://sam-demo-bucket/hello.zip
Handler: hello.handler
Runtime: python2.7
Events:
AddItem:
Type: Api
Properties:
RestApiId:
Ref: ExplicitApi
Path: /add
Method: post
For more information about resource policies, see Control Access to an API with Amazon API Gateway
Resource Policies in the API Gateway Developer Guide.
The following is an example AWS SAM template section for API Gateway responses:
Resources:
MyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
GatewayResponses:
DEFAULT_4xx:
ResponseParameters:
Headers:
Access-Control-Expose-Headers: "'WWW-Authenticate'"
Access-Control-Allow-Origin: "'*'"
GetFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.get
Runtime: nodejs6.10
InlineCode: module.exports = async () => throw new Error('Check out the response
headers!')
Events:
GetResource:
Type: Api
Properties:
Path: /error
Method: get
RestApiId: !Ref MyApi
For more information about customizing API Gateway messages, see Set Up Gateway Responses to
Customize Error Responses in the API Gateway Developer Guide.
102
AWS Serverless Application Model Developer Guide
Example: Defining Customized Responses
For a full sample application that includes a customized error response, see API Gateway +
GatewayResponse Example.
103
AWS Serverless Application Model Developer Guide
Invoking Functions Locally
When you locally invoke a Lambda function in debug mode within the AWS SAM CLI, you can then
attach a debugger to it. With the debugger, you can step through your code line by line, see the values of
various variables, and fix issues the same way you would for any other application.
Topics
• Invoking Functions Locally (p. 104)
• Running API Gateway Locally (p. 106)
• Running Automated Tests (p. 108)
• Generating Sample Event Payloads (p. 110)
• Step-Through Debugging Lambda Functions Locally (p. 110)
• Passing Additional Runtime Debug Arguments (p. 116)
You must execute sam local invoke in the project directory containing the function you want to
invoke.
Examples:
This animation shows invoking a Lambda function locally using Microsoft Visual Studio Code:
104
AWS Serverless Application Model Developer Guide
Environment Variable File
105
AWS Serverless Application Model Developer Guide
Layers
{
"MyFunction1": {
"TABLE_NAME": "localtable",
"BUCKET_NAME": "testBucket"
},
"MyFunction2": {
"TABLE_NAME": "localtable",
"STAGE": "dev"
},
}
For example, if you save this content in a file named env.json, then the following command uses this
file to override the included environment variables:
Layers
If your application includes layers, see Working with Layers (p. 93) for more information about how to
debug layers issues on your local host.
You must execute sam local invoke in the project directory containing the function you want to
invoke.
Example:
AWS SAM automatically finds any functions within your AWS SAM template that have Api event sources
defined. Then, it mounts them at the defined HTTP paths.
This animation shows running API Gateway locally using Microsoft Visual Studio Code:
106
AWS Serverless Application Model Developer Guide
Running API Gateway Locally
In the following example, the Ratings function mounts ratings.py:handler() at /ratings for
GET requests:
Ratings:
Type: AWS::Serverless::Function
Properties:
Handler: ratings.handler
107
AWS Serverless Application Model Developer Guide
Layers
Runtime: python3.6
Events:
Api:
Type: Api
Properties:
Path: /ratings
Method: get
By default, AWS SAM uses Proxy Integration and expects the response from your Lambda function to
include one or more of the following: statusCode, headers, or body.
For example:
You can use the --env-vars argument with the invoke or start-api commands to provide a JSON
file that contains values to override the environment variables already defined in your function template.
Structure the file as follows:
{
"MyFunction1": {
"TABLE_NAME": "localtable",
"BUCKET_NAME": "testBucket"
},
"MyFunction2": {
"TABLE_NAME": "localtable",
"STAGE": "dev"
},
}
For example, if you save this content in a file named env.json, then the following command uses this
file to override the included environment variables:
Layers
If your application includes layers, see Working with Layers (p. 93) for more information about how to
debug layers issues on your local host.
108
AWS Serverless Application Model Developer Guide
Running Automated Tests
The sam local start-lambda command starts a local endpoint that emulates the AWS Lambda
invoke endpoint. You can invoke it from your automated tests. Because this endpoint emulates the
AWS Lambda invoke endpoint, you can write tests once, and then run them (without any modifications)
against the local Lambda function, or against a deployed Lambda function. You can also run the same
tests against a deployed AWS SAM stack in your CI/CD pipeline.
Start the local Lambda endpoint by running the following command in the directory that contains
your AWS SAM template:
This command starts a local endpoint at http://127.0.0.1:3001 that emulates AWS Lambda.
You can run your automated tests against this local Lambda endpoint. When you invoke this
endpoint using the AWS CLI or SDK, it locally executes the Lambda function that's specified in the
request, and returns a response.
2. Run an integration test against the local Lambda endpoint.
In your integration test, you can use the AWS SDK to invoke your Lambda function with test data,
wait for response, and verify that the response is what you expect. To run the integration test locally,
you should configure the AWS SDK to send a Lambda Invoke API call to invoke the local Lambda
endpoint that you started in previous step.
The following is a Python example (the AWS SDKs for other languages have similar configurations):
import boto3
import botocore
# Set "running_locally" flag if you are running the integration test locally
running_locally = True
if running_locally:
# Invoke your Lambda function as you normally usually do. The function will run
# locally if it is configured to do so
response = lambda_client.invoke(FunctionName="HelloWorldFunction")
109
AWS Serverless Application Model Developer Guide
Generating Sample Event Payloads
You can use this code to test deployed Lambda functions by setting running_locally to False.
This sets up the AWS SDK to connect to AWS Lambda in the AWS Cloud.
For the full list of services that you can generate sample event payloads for, use this command:
For the list of options you can use for a particular service, use this command:
Examples:
For example, you can perform step-through debugging of your Lambda functions. Step-through
debugging makes it easier to understand what the code is doing. It tightens the feedback loop by making
it possible for you to find and troubleshoot issues that you might run into in the cloud.
For more information about AWS toolkits that you can use with AWS SAM, see the following:
110
AWS Serverless Application Model Developer Guide
Running AWS SAM Locally
Note
If you're using sam local start-api, the local API Gateway instance exposes all of your
Lambda functions. However, because you can specify a single debug port, you can only debug
one function at a time. You need to call your API before the AWS SAM CLI binds to the port,
which allows the debugger to connect.
Topics
The following topics provide examples of how to set up your environment to test and debug your
serverless applications locally.
111
AWS Serverless Application Model Developer Guide
Node.js
To set up Microsoft Visual Studio Code for step-through debugging Node.js functions with the AWS
SAM CLI, use the following launch configuration. Before you do this, set the directory where the
template.yaml file is located as the workspace root in Microsoft Visual Studio Code:
{
"version": "0.2.0",
"configurations": [
112
AWS Serverless Application Model Developer Guide
Python
{
"name": "Attach to SAM CLI",
"type": "node",
"request": "attach",
"address": "localhost",
"port": 5858,
// From the sam init example, it would be "${workspaceRoot}/hello-world"
"localRoot": "${workspaceRoot}/{directory of node app}",
"remoteRoot": "/var/task",
"protocol": "inspector",
"stopOnEntry": false
}
]
}
Note
The localRoot is set based on what the CodeUri points at in the template.yaml file. If there
are nested directories within the CodeUri, that needs to be reflected in the localRoot.
Note
Node.js versions earlier than 7 (for example, Node.js 4.3 and Node.js 6.10) use the legacy
protocol, while Node.js versions including and later than 7 (for example, Node.js 8.10) use the
inspector protocol. Be sure to specify the corresponding protocol in the protocol entry of
your launch configuration. This was tested with Microsoft Visual Studio Code versions 1.26, 1.27,
and 1.28 for the legacy and inspector protocols.
Because this might be your first time using the AWS SAM CLI, start with a boilerplate Python application,
and install both the application's dependencies and ptvsd:
cp hello_world/app.py hello_world/build/
Ptvsd Configuration
Next, you need to enable ptvsd within your code. To do this, open hello_world/build/app.py, and
add the following ptvsd specifics:
import ptvsd
# Enable ptvsd on 0.0.0.0 address and on port 5890 that we'll connect later with our IDE
ptvsd.enable_attach(address=('0.0.0.0', 5890), redirect_output=True)
ptvsd.wait_for_attach()
113
AWS Serverless Application Model Developer Guide
Python
Use 0.0.0.0 instead of localhost for listening across all network interfaces. 5890 is the debugging
port that you want to use.
code .
Note
If you don't have code in your path, open a new instance of Microsoft Visual Studio Code from
the python-debugging/ folder that you created earlier.
To set up Microsoft Visual Studio Code for debugging with the AWS SAM CLI, use the following launch
configuration:
{
"version": "0.2.0",
"configurations": [
{
"name": "SAM CLI Python Hello World",
"type": "python",
"request": "attach",
"port": 5890,
"host": "localhost",
"pathMappings": [
{
"localRoot": "${workspaceFolder}/hello_world/build",
"remoteRoot": "/var/task"
}
]
}
]
}
For Microsoft Visual Studio Code, the property localRoot under the pathMappings key is important.
There are two reasons that help explain this setup:
• localRoot: This path is to be mounted in the Docker container, and needs to have both the application
and dependencies at the root level.
• workspaceFolder: This path is the absolute path where the Microsoft Visual Studio Code instance was
opened.
If you opened Microsoft Visual Studio Code in a different location other than python-debugging/, you
need to replace it with the absolute path where python-debugging/ is located.
After the Microsoft Visual Studio Code debugger configuration is complete, make sure to add a
breakpoint anywhere you want to in hello_world/build/app.py, and then proceed as follows:
# Remember to hit the URL before starting the debugger in Microsoft Visual Studio Code
114
AWS Serverless Application Model Developer Guide
Golang
# OR
When you're debugging, you must compile your function in debug mode:
GOARCH=amd64 GOOS=linux go build -gcflags='-N -l' -o <output path> <path to code directory>
Delve Debugger
You must compile Delve to run in the container and provide its local path with the --debugger-path
argument.
Example:
Example
Invoke AWS SAM with the Delve debugger in API version 2 mode:
sam local start-api -d 5986 --debugger-path <delve folder path> --debug-args "-delveAPI=2"
115
AWS Serverless Application Model Developer Guide
Passing Additional Runtime Debug Arguments
Example
The following is an example launch configuration for Microsoft Visual Studio Code to attach to a debug
session.
{
"version": "0.2.0",
"configurations": [
{
"name": "Connect to Lambda container",
"type": "go",
"request": "launch",
"mode": "remote",
"remotePath": "",
"port": <debug port>,
"host": "127.0.0.1",
"program": "${workspaceRoot}",
"env": {},
"args": [],
},
]
}
For example, if you want to load a debugger like iKPdb at the runtime of your Python function,
you could pass the following as DEBUGGER_ARGS: -m ikpdb --ikpdb-port=5858 --ikpdb-
working-directory=/var/task/ --ikpdb-client-working-directory=/myApp --ikpdb-
address=0.0.0.0. This would load iKPdb at runtime with the other arguments you’ve specified.
In this case, your full AWS SAM CLI command would be:
116
AWS Serverless Application Model Developer Guide
Packaging and Deploying Using the AWS SAM CLI
You can deploy your application by using AWS SAM command line interface (CLI) commands. You can
also use other AWS services that integrate with AWS SAM to automate your deployments.
The sam package command zips your code artifacts, uploads them to Amazon S3, and produces a
packaged AWS SAM template file that's ready to be used. The sam deploy command uses this file to
deploy your application. For example, the following command generates a packaged.yaml file:
The following sam deploy command takes the packaged AWS SAM template file that was created
earlier, and deploys your serverless application:
Note
To deploy an application that contains one or more nested applications, you must include the
CAPABILITY_AUTO_EXPAND capability in the sam deploy command.
Automating Deployments
You can use AWS SAM with a number of other AWS services to automate the deployment process of your
serverless application.
• CodeBuild: You use CodeBuild to build, locally test, and package your serverless application. For more
information, see What Is CodeBuild?.
117
AWS Serverless Application Model Developer Guide
Deploying Gradually
• CodeDeploy: You use CodeDeploy to gradually deploy updates to your serverless applications. For
more information on how to do this, see Deploying Serverless Applications Gradually (p. 118).
• CodePipeline: You use CodePipeline to model, visualize, and automate the steps that are required to
release your serverless application. For more information, see What Is CodePipeline?.
Topics
• Deploys new versions of your Lambda function, and automatically creates aliases that point to the new
version.
• Gradually shifts customer traffic to the new version until you're satisfied that it's working as expected,
or you roll back the update.
• Defines pre-traffic and post-traffic test functions to verify that the newly deployed code is configured
correctly and your application operates as expected.
• Rolls back the deployment if CloudWatch alarms are triggered.
Note
If you enable gradual deployments through your AWS SAM template, a CodeDeploy resource is
automatically created for you. You can view the CodeDeploy resource directly through the AWS
Management Console.
Example
The following example demonstrates a simple version of using CodeDeploy to gradually shift customers
to your newly deployed version:
Resources:
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs4.3
CodeUri: s3://bucket/code.zip
AutoPublishAlias: live
DeploymentPreference:
Type: Canary10Percent10Minutes
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
118
AWS Serverless Application Model Developer Guide
Deploying Gradually
• AutoPublishAlias: By adding this property and specifying an alias name, AWS SAM:
• Detects when new code is being deployed, based on changes to the Lambda function's Amazon S3
URI.
• Creates and publishes an updated version of that function with the latest code.
• Creates an alias with a name that you provide (unless an alias already exists), and points to the
updated version of the Lambda function. Function invocations should use the alias qualifier to
take advantage of this. If you aren't familiar with Lambda function versioning and aliases, see AWS
Lambda Function Versioning and Aliases .
• Deployment Preference Type: In the previous example, 10 percent of your customer traffic is
immediately shifted to your new version. After 10 minutes, all traffic is shifted to the new version.
However, if your pre-hook/post-hook tests fail, or if a CloudWatch alarm is triggered, CodeDeploy rolls
back your deployment. The following table outlines other traffic-shifting options that are available
beyond the one used earlier. Note the following:
• Canary: Traffic is shifted in two increments. You can choose from predefined canary options. The
options specify the percentage of traffic that's shifted to your updated Lambda function version in
the first increment, and the interval, in minutes, before the remaining traffic is shifted in the second
increment.
• Linear: Traffic is shifted in equal increments with an equal number of minutes between each
increment. You can choose from predefined linear options that specify the percentage of traffic
that's shifted in each increment and the number of minutes between each increment.
• All-at-once: All traffic is shifted from the original Lambda function to the updated Lambda function
version at once.
Canary10Percent30Minutes
Canary10Percent5Minutes
Canary10Percent10Minutes
Canary10Percent15Minutes
Linear10PercentEvery10Minutes
Linear10PercentEvery1Minute
Linear10PercentEvery2Minutes
Linear10PercentEvery3Minutes
AllAtOnce
• Alarms: These are CloudWatch alarms that are triggered by any errors raised by the deployment.
They automatically roll back your deployment. An example is if the updated code you're deploying is
creating errors within the application. Another example is if any AWS Lambda or custom CloudWatch
metrics that you specified have breached the alarm threshold.
• Hooks: These are pre-traffic and post-traffic test functions that run sanity checks before traffic shifting
starts to the new version, and after traffic shifting completes.
• PreTraffic: Before traffic shifting starts, CodeDeploy invokes the pre-traffic hook Lambda function.
This Lambda function must call back to CodeDeploy and indicate success or failure. If the function
fails, it aborts and reports a failure back to AWS CloudFormation. If the function succeeds,
CodeDeploy proceeds to traffic shifting.
• PostTraffic: After traffic shifting completes, CodeDeploy invokes the post-traffic hook Lambda
function. This is similar to the pre-traffic hook, where the function must call back to CodeDeploy to
report a success or failure. Use post-traffic hooks to run integration tests or other validation actions.
119
AWS Serverless Application Model Developer Guide
Deploying Gradually
120
AWS Serverless Application Model Developer Guide
Working with Logs
Topics
• Working with Logs (p. 121)
Tailing Logs
Add the --tail option to wait for new logs and see them as they arrive. This is helpful during
deployment or when you're troubleshooting a production issue.
Filtering Logs
Use the --filter option to quickly find logs that match terms, phrases, or values in your log events:
121
AWS Serverless Application Model Developer Guide
Error Highlighting
In the output, the AWS SAM CLI underlines all occurrences of the word "error" so you can easily locate
the filter keyword within the log output.
Error Highlighting
When your Lambda function crashes or times out, the AWS SAM CLI highlights the timeout message
in red. This helps you easily locate specific executions that are timing out within a giant stream of log
output.
122
AWS Serverless Application Model Developer Guide
Prerequisites
The application you want to publish must be one that you've defined using AWS SAM, and that you've
tested locally and/or in the AWS Cloud. The application's deployment package and AWS SAM template
are the inputs to the steps below.
The following instructions either create a new application, create a new version of an existing
application, or update the metadata of an existing application. This depends on whether the application
already exists in the AWS Serverless Application Repository, and whether any application metadata is
changing. For more information about application metadata that's used to publish applications, see AWS
SAM Template Metadata Section Properties (p. 125).
Prerequisites
Before you publish an application to the AWS Serverless Application Repository, you need the following:
• A valid AWS account with an IAM user that has administrator permissions. See Set Up an AWS Account.
• Version 1.16.77 or later of the AWS CLI installed. See Installing the AWS Command Line Interface. If
you have the AWS CLI installed, you can get the version by running the following command:
aws --version
• The AWS SAM CLI (command line interface) installed. See Installing the AWS SAM CLI. You can
determine whether the AWS SAM CLI is installed by running the following command:
sam --version
123
AWS Serverless Application Model Developer Guide
Step 1: Add a Metadata Section to the AWS SAM Template
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "serverlessrepo.amazonaws.com"
},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::<your-bucket-name>/*"
}
]
}
Metadata:
AWS::ServerlessRepo::Application:
Name: my-app
Description: hello world
Author: user1
SpdxLicenseId: Apache-2.0
LicenseUrl: LICENSE.txt
ReadmeUrl: README.md
Labels: ['tests']
HomePageUrl: https://github.com/user1/my-app-project
SemanticVersion: 0.0.1
SourceCodeUrl: https://github.com/user1/my-app-project
Resources:
HelloWorldFunction:
Type: AWS::Lambda::Function
Properties:
...
CodeUri: source-code1
...
For more information about the properties of the Metadata section in the AWS SAM template, see AWS
SAM Template Metadata Section Properties (p. 125).
124
AWS Serverless Application Model Developer Guide
Step 3: Publish the Application
sam package \
--template-file template.yaml \
--output-template-file packaged.yaml \
--s3-bucket <your-bucket-name>
The command uploads the application artifacts to Amazon S3 and outputs a new template file called
packaged.yaml. You use this file in the next step to publish the application to the AWS Serverless
Application Repository. The packaged.yaml template file is similar to the original template file
(template.yaml), but has a key difference—the CodeUri, LicenseUrl, and ReadmeUrl properties
point to the Amazon S3 bucket and objects that contain the respective artifacts.
The following snippet from an example packaged.yaml template file shows the CodeUri property:
MySampleFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: s3://bucketname/fbd77a3647a4f47a352fcObjectGUID
...
sam publish \
--template packaged.yaml \
--region us-east-1
The output of the sam publish command includes a link to the AWS Serverless Application Repository
directly to your application. You can also go to the AWS Serverless Application Repository landing page
directly and search for your application.
Your application is set to private by default, so it isn't visible to other AWS accounts. In order to share
your application with others, you must either make it public or grant permission to a specific list of AWS
accounts. For information on sharing your application by using the AWS CLI, see Using Resource-based
Policies for the AWS Serverless Application Repository. For information on sharing your application using
the console, see Sharing an Application Through the Console.
Additional Topics
• AWS SAM Template Metadata Section Properties (p. 125)
125
AWS Serverless Application Model Developer Guide
Properties
Properties
This table provides information about the properties of the Metadata section of the AWS SAM template.
This section is required to publish applications to the AWS Serverless Application Repository using the
AWS SAM CLI.
Pattern: "[a-zA-Z0-9\\-]+";
Author String TRUE The name of the author publishing the application.
Pattern "^[a-z0-9](([a-z0-9]|-(?!-))*[a-z0-9])?$";
126
AWS Serverless Application Model Developer Guide
Use Cases
Pattern: "^[a-zA-Z0-9+\\-_:\\/@]+$";
HomePageUrl String FALSE A URL with more information about the application—
for example, the location of your GitHub repository for
the application.
SourceCodeUrl String FALSE A link to a public repository for the source code of your
application.
Use Cases
This section lists the use cases for publishing applications, along with the Metadata properties that are
processed for that use case. Properties that are not listed for a given use case are ignored.
• Creating a new application – A new application is created if there is no application in the AWS
Serverless Application Repository with a matching name for an account.
• Name
• SpdxLicenseId
• LicenseUrl
• Description
• Author
• ReadmeUrl
• Labels
• HomePageUrl
• SourceCodeUrl
• SemanticVersion
• The content of the AWS SAM template (for example, any event sources, resources, and Lambda
function code)
• Creating an application version – An application version is created if there is already an application
in the AWS Serverless Application Repository with a matching name for an account and the
SemanticVersion is changing.
• Description
• Author
• ReadmeUrl
• Labels
• HomePageUrl
127
AWS Serverless Application Model Developer Guide
Example
• SourceCodeUrl
• SemanticVersion
• The content of the AWS SAM template (for example, any event sources, resources, and Lambda
function code)
• Updating an application – An application is updated if there is already an application in the AWS
Serverless Application Repository with a matching name for an account and the SemanticVersion is not
changing.
• Description
• Author
• ReadmeUrl
• Labels
• HomePageUrl
Example
The following is an example Metadata section:
Metadata:
AWS::ServerlessRepo::Application:
Name: my-app
Description: hello world
Author: user1
SpdxLicenseId: Apache-2.0
LicenseUrl: LICENSE.txt
ReadmeUrl: README.md
Labels: ['tests']
HomePageUrl: https://github.com/user1/my-app-project
SemanticVersion: 0.0.1
SourceCodeUrl: https://github.com/user1/my-app-project
128
AWS Serverless Application Model Developer Guide
Process DynamoDB Events
Topics
• Process DynamoDB Events (p. 129)
• Process Amazon S3 Events (p. 131)
This exercise shows you how to mimic event source messages that are passed to Lambda functions when
they're invoked.
sam init \
--location gh:aws-samples/cookiecutter-aws-sam-dynamodb-python \
--no-input
2. Review the contents of the directory that the command created (dynamodb_event_reader/):
• template.yaml – Defines two AWS resources that the Read DynamoDB application needs: a
Lambda function and a DynamoDB table. The template also defines mapping between the two
resources.
• read_dynamodb_event/ directory – Contains the DynamoDB application code.
129
AWS Serverless Application Model Developer Guide
Step 3: Package the Application
The generate-event command creates a test event source message like the messages that are created
when all components are deployed to the AWS Cloud. This event source message is piped to the Lambda
function ReadDynamoDBEvent.
Verify that the expected messages are printed to the console, based on the source code in app.py.
1. Create an S3 bucket in the location where you want to save the packaged code. If you want to use an
existing S3 bucket, skip this step.
aws s3 mb s3://bucketname
2. Create the deployment package by running the following package CLI command at the command
prompt.
sam package \
--template-file template.yaml \
--output-template-file packaged.yaml \
--s3-bucket bucketname
You specify the new template file, packaged.yaml, when you deploy the application in the next
step.
• In the AWS SAM CLI, use the deploy CLI command to deploy all of the resources that you defined in
the template.
sam deploy \
--template-file packaged.yaml \
--stack-name sam-app \
--capabilities CAPABILITY_IAM \
--region us-east-1
In the command, the --capabilities parameter allows AWS CloudFormation to create an IAM
role.
AWS CloudFormation creates the AWS resources that are defined in the template. You can access the
names of these resources in the AWS CloudFormation console.
130
AWS Serverless Application Model Developer Guide
Process Amazon S3 Events
3. Go to the Metrics tab of the table, and choose View all CloudWatch metrics. In the CloudWatch
console, choose Logs to be able to view the log output.
This sample serverless application processes object-creation events in Amazon S3. For each image that's
uploaded to a bucket, Amazon S3 detects the object-created event and invokes a Lambda function.
The Lambda function invokes Amazon Rekognition to detect text that's in the image. It then stores the
results returned by Amazon Rekognition in a DynamoDB table.
Note
With this example application, you perform steps in a slightly different order than in previous
examples. The reason for this is that this example requires that AWS resources are created and
IAM permissions are configured before you can test the Lambda function locally. We're going to
leverage AWS CloudFormation to create the resources and configure the permissions for you.
Otherwise, you would need to do this manually before you can test the Lambda function locally.
Because this example is more complicated, be sure that you're familiar with installing the
previous example applications before executing this one.
sam init \
--location https://github.com/aws-samples/cookiecutter-aws-sam-s3-rekognition-dynamodb-
python \
--no-input
2. Review the contents of the directory that the command created (aws_sam_ocr/):
• template.yaml – Defines three AWS resources that the Amazon S3 application needs: a Lambda
function, an Amazon S3 bucket, and a DynamoDB table. The template also defines the mappings
and permissions between these resources.
• src/ directory – Contains the Amazon S3 application code.
• SampleEvent.json – The sample event source, which is used for local testing.
131
AWS Serverless Application Model Developer Guide
Step 3: Deploy the Application
1. Create an S3 bucket in the location where you want to save the packaged code. If you want to use an
existing S3 bucket, skip this step.
aws s3 mb s3://bucketname
2. Create the deployment package by running the following package CLI command at the command
prompt.
sam package \
--template-file template.yaml \
--output-template-file packaged.yaml \
--s3-bucket bucketname
You specify the new template file, packaged.yaml, when you deploy the application in the next
step.
• In the AWS SAM CLI, use the deploy command to deploy all of the resources that you defined in the
template.
sam deploy \
--template-file packaged.yaml \
--stack-name aws-sam-ocr \
--capabilities CAPABILITY_IAM \
--region us-east-1
In the command, the --capabilities parameter allows AWS CloudFormation to create an IAM
role.
AWS CloudFormation creates the AWS resources that are defined in the template. You can access the
names of these resources in the AWS CloudFormation console.
1. Upload an image to the Amazon S3 bucket that you created for this sample application.
2. Open the DynamoDB console and find the table that was created. See the table for results returned
by Amazon Rekognition.
3. Verify that the DynamoDB table contains new records that contain text that Amazon Rekognition
found in the uploaded image.
132
AWS Serverless Application Model Developer Guide
Step 4: Test the Application Locally
• Retrieve the Amazon S3 key name and bucket name from AWS CloudFormation. Modify the
SampleEvent.json file by replacing the values for the object key, bucket name, and bucket ARN.
• Retrieve the DynamoDB table name. This name is used for the following sam local invoke
command.
Use the AWS SAM CLI to generate a sample Amazon S3 event and invoke the Lambda function:
TABLE_NAME=Table name obtained from AWS CloudFormation console sam local invoke --event
SampleEvent.json
The TABLE_NAME= portion sets the DynamoDB table name. The --event parameter specifies the file
that contains the test event message to pass to the Lambda function.
You can now verify that the expected DynamoDB records were created, based on the results returned by
Amazon Rekognition.
133
AWS Serverless Application Model Developer Guide
AWS SAM Specification
AWS SAM templates are an extension of AWS CloudFormation templates. For the full reference for AWS
CloudFormation templates, see AWS CloudFormation Template Reference.
You can use the AWS SAM CLI commands to develop, test, and deploy your serverless applications to the
AWS Cloud. The following are some examples of AWS SAM CLI commands:
• sam init – If you're a first-time AWS SAM CLI user, you can run the sam init command without any
parameters to create a Hello World application. The command generates a preconfigured AWS SAM
template and example application code in the language that you choose.
• sam local invoke and sam local start-api – Use these commands to test your application
code locally, before deploying it to the AWS Cloud.
• sam logs – Use this command to fetch logs generated by your Lambda function. This can help you
with testing and debugging your application after you've deployed it to the AWS Cloud.
• sam package – Use this command to bundle your application code and dependencies into a
"deployment package". The deployment package is needed to upload your application to the AWS
Cloud.
• sam deploy – Use this command to deploy your serverless application to the AWS Cloud. It creates
the AWS resources and sets permissions and other configurations that are defined in the AWS SAM
template.
Topics
134
AWS Serverless Application Model Developer Guide
AWS SAM CLI Command Reference
Topics
• sam build (p. 135)
• sam deploy (p. 136)
• sam init (p. 138)
• sam local generate-event (p. 140)
• sam local invoke (p. 141)
• sam local start-api (p. 142)
• sam local start-lambda (p. 144)
• sam logs (p. 145)
• sam package (p. 146)
• sam publish (p. 147)
• sam validate (p. 148)
sam build
Use this command to build your Lambda source code and generate deployment artifacts that target
Lambda's execution environment. By doing this, the functions that you build locally run in a similar
environment in the AWS Cloud.
The sam build command iterates through the functions in your application, looks for a manifest file
(such as requirements.txt) that contains the dependencies, and automatically creates deployment
artifacts that you can deploy to Lambda using the sam package and sam deploy commands. You that
can also use sam build in combination with other commands like sam local invoke to test your
application locally.
To use this command, update your AWS SAM template to specify the path to your function's source code
in the resource's Code or CodeUri property.
Usage:
Examples:
135
AWS Serverless Application Model Developer Guide
sam deploy
Options:
Option Description
-b, --build-dir DIRECTORY The path to a folder where the built artifacts are stored.
-s, --base-dir DIRECTORY Resolves relative paths to the function's source code with respect to this
folder. Use this if the AWS SAM template and your source code aren't in
the same enclosing folder. By default, relative paths are resolved with
respect to the template's location.
-u, --use-container If your functions depend on packages that have natively compiled
dependencies, use this flag to build your function inside an AWS
Lambda-like Docker container.
-m, --manifest PATH The path to a custom dependency manifest (ex: package.json) to use
instead of the default one.
-t, --template PATH The AWS SAM template file [default: template.[yaml|yml]].
--skip-pull-image Specifies whether the command should skip pulling down the latest
Docker image for Lambda runtime.
--profile TEXT Selects a specific profile from your credential file to get AWS credentials.
--region TEXT Sets the AWS Region of the service (for example, us-east-1).
--debug Turns on debug logging to print debug message generated by the AWS
SAM CLI.
sam deploy
Deploys an AWS SAM application.
This command now comes with a guided interactive mode, which you can enable by specifying the --
guided parameter. The interactive mode walks you through the parameters required for deployment,
provides default options, and saves these options in a configuration file in your project folder. You can
execute subsequent deployments of your application by simply executing sam deploy and the needed
parameters will be retrieved from the AWS SAM CLI configuration file.
Deploying Lambda functions through AWS CloudFormation requires an Amazon S3 bucket for the
Lambda deployment package. AWS SAM CLI now creates and manages this Amazon S3 bucket for you.
136
AWS Serverless Application Model Developer Guide
sam deploy
Usage:
Options:
Option Description
-g, --guided Specify this flag to allow AWS SAM to guide you through the
deployment using guided prompts.
For more information about settings that optionally get stored when
specifying this parameter, see AWS SAM CLI Config (p. 149)
--template-file PATH The path where your AWS SAM template is located. Default: template.
[yaml|yml].
--stack-name TEXT The name of the AWS CloudFormation stack you're deploying to. If you
specify an existing stack, the command updates the stack. If you specify
a new stack, the command creates it. Required.
--s3-bucket TEXT The name of the Amazon S3 bucket where artifacts that are referenced
in your template. This is required the deployments of templates sized
greater than 51,200 bytes.
--s3-prefix TEXT Prefix added to the artifacts name that are uploaded to the Amazon S3
bucket. The prefix name is a path name (folder name) for the Amazon S3
bucket.
--capabilities LIST A list of capabilities that you must specify to allow AWS CloudFormation
to create certain stacks. Some stack templates might include resources
that can affect permissions in your AWS account, for example, by
creating new AWS Identity and Access Management (IAM) users. For
those stacks, you must explicitly acknowledge their capabilities by
specifying this parameter. The only valid values are CAPABILITY_IAM
and CAPABILITY_NAMED_IAM. If you have IAM resources, you can
specify either capability. If you have IAM resources with custom names,
you must specify CAPABILITY_NAMED_IAM. If you don't specify this
parameter, this action returns an InsufficientCapabilities error.
--profile TEXT Select a specific profile from your credential file to get AWS credentials.
--kms-key-id TEXT The ID of an AWS KMS key used to encrypt artifacts that are at rest in
the Amazon S3 bucket.
--force-upload Override existing files in the Amazon S3 bucket. Specify this flag to
upload artifacts even if they match existing artifacts in the Amazon S3
bucket.
--no-execute-changeset Indicates whether to execute the change set. Specify this flag if you
want to view your stack changes before executing the change set. This
command creates an AWS CloudFormation change set and then exits
without executing the change set. If you want to execute the changeset,
the stack changes can be made by running the same command without
this flag.
137
AWS Serverless Application Model Developer Guide
sam init
Option Description
--role-arn TEXT The Amazon Resource Name (ARN) of an AWS Identity and Access
Management (IAM) role that AWS CloudFormation assumes when
executing the change set.
--fail-on-empty-changeset Return a non-zero exit code if there are no changes to be made to the
stack. The default behavior is to return a non-zero exit code.
--use-json Output JSON for the AWS CloudFormation template. YAML is used by
default.
--metadata A map of metadata to attach to all artifacts that are referenced in your
template. Optional.
--notification-arns LIST Amazon Simple Notification Service topic Amazon Resource Names
(ARNs) that AWS CloudFormation associates with the stack.
--tags A list of tags to associate with the stack that is created or updated. AWS
CloudFormation also propagates these tags to resources in the stack if
the resource supports it.
sam init
Initializes a serverless application with an AWS SAM template. The template provides a folder structure
for your Lambda functions, and is connected to an event source such as APIs, S3 buckets, or DynamoDB
tables. This application includes everything you need to get started and to eventually extend it into a
production-scale application.
Usage:
Note
With AWS SAM version 0.30.0 or later, you can initialize your application using one of two
modes: 1) Interactive workflow, or 2) Providing all required parameters.
• Interactive Workflow: Through the interactive initialize workflow you can input either 1) your
project name, preferred runtime, and template file, or 2) the location of a custom template.
• Providing Parameters: Provide all required parameters.
If you provide a subset of required parameters, you will be prompted for the additional required
information.
138
AWS Serverless Application Model Developer Guide
sam init
Examples:
Options:
Option Description
--no-interactive Disable interactive prompting for init parameters, and fail if any required
values are missing.
-l, --location TEXT The template or application location (Git, Mercurial, HTTP/HTTPS, ZIP,
path).
For Git repositories, you must use location of the root of the repository.
-o, --output-dir PATH The location where the initialized application is output.
139
AWS Serverless Application Model Developer Guide
sam local generate-event
Option Description
--app-template TEXT Identifier of the managed application template you want to use. If not
sure, call 'sam init' without options for an interactive workflow.
--no-input Disables Cookiecutter prompting and accept default values that are
defined in the template configuration.
Usage:
Examples:
Generate the event that S3 sends to your Lambda function when a new object is uploaded
sam local generate-event s3 [put/delete]
# You can even customize the event by adding parameter flags. To find which flags apply to
your command,
run:
# Then you can add in those flags that you wish to customize using
# After you generate a sample event, you can use it to test your Lambda function locally
sam local generate-event s3 [put/delete] --bucket <bucket> --key <key> | sam local invoke
<function logical id>
Options:
Option Description
Commands:
• alexa-skills-kit
140
AWS Serverless Application Model Developer Guide
sam local invoke
• alexa-smart-home
• apigateway
• batch
• cloudformation
• cloudfront
• cloudwatch
• codecommit
• codepipeline
• cognito
• config
• dynamodb
• kinesis
• lex
• rekognition
• s3
• ses
• sns
• sqs
• stepfunctions
This is useful for developing serverless functions that handle asynchronous events (such as Amazon
S3 or Amazon Kinesis events). It can also be useful if you want to compose a script of test cases. The
event body can be passed in either by stdin (default), or by using the --event parameter. The runtime
output (logs etc) is output to stderr, and the Lambda function result is output to stdout.
Usage:
Options:
Option Description
-e, --event PATH The JSON file that contains event data that's passed to the Lambda
function when it's invoked. If you don't specify this option, the default is
reading the JSON from stdin.
-t, --template PATH The AWS SAM template file [default: template.[yaml|yml]].
-n, --env-vars PATH The JSON file that contains values for the Lambda function's
environment variables. For more information about environment
variables files, see Environment Variable File (p. 105).
141
AWS Serverless Application Model Developer Guide
sam local start-api
Option Description
CLI—for example, 'ParameterKey=KeyPairName, ParameterValue=MyKey
ParameterKey=InstanceType,ParameterValue=t1.micro'.
-d, --debug-port TEXT When specified, starts the Lambda function container in debug mode
and exposes this port on the local host.
--debugger-path TEXT The host path to a debugger that will be mounted into the Lambda
container.
-v, --docker-volume-basedir The location of the base directory where the AWS SAM file exists. If
TEXT Docker is running on a remote machine, you must mount the path where
the AWS SAM file exists on the Docker machine, and modify this value to
match the remote machine.
--docker-network TEXT The name or ID of an existing Docker network that Lambda Docker
containers should connect to, along with the default bridge network. If
this isn't specified, the Lambda containers only connect to the default
bridge Docker network.
-l, --log-file TEXT The log file to send runtime logs to.
--layer-cache-basedir Specifies the location basedir where the layers your template uses are
DIRECTORY downloaded to.
--skip-pull-image Specifies whether the CLI should skip pulling down the latest Docker
image for the Lambda runtime.
--force-image-build Specifies whether the CLI should rebuild the image used for invoking
functions with layers.
--region TEXT Sets the AWS Region of the service (for example, us-east-1).
When it's accessed (through a browser, CLI, and so on), it starts a Docker container locally to invoke the
function. It reads the CodeUri property of the AWS::Serverless::Function resource to find the path in
your file system that contains the Lambda function code. This could be the project's root directory for
interpreted languages like Node.js and Python, or a build directory that stores your compiled artifacts or
a Java Archive (JAR) file.
If you're using an interpreted language, local changes are available immediately in the Docker container
on every invoke. For more compiled languages or projects that require complex packing support, we
recommend that you run your own building solution, and point AWS SAM to the directory or file that
contains the build artifacts.
142
AWS Serverless Application Model Developer Guide
sam local start-api
Usage:
Options:
Option Description
-p, --port INTEGER The local port number to listen on (default: '3000').
-s, --static-dir TEXT Any static asset (for example, CSS/JavaScript/HTML) files located in this
directory are presented at /.
-t, --template PATH The AWS SAM template file [default: template.[yaml|yml]].
-n, --env-vars PATH The JSON file that contains values for the Lambda function's
environment variables.
-d, --debug-port TEXT When specified, starts the Lambda function container in debug mode
and exposes this port on the local host.
--debugger-path TEXT The host path to a debugger that will be mounted into the Lambda
container.
-v, --docker-volume-basedir The location of the base directory where the AWS SAM file exists. If
TEXT Docker is running on a remote machine, you must mount the path where
the AWS SAM file exists on the Docker machine, and modify this value to
match the remote machine.
--docker-network TEXT The name or ID of an existing Docker network that the Lambda Docker
containers should connect to, along with the default bridge network. If
this isn't specified, the Lambda containers only connect to the default
bridge Docker network.
-l, --log-file TEXT The log file to send runtime logs to.
--layer-cache-basedir Specifies the location basedir where the Layers your template uses are
DIRECTORY downloaded to.
--skip-pull-image Specifies whether the CLI should skip pulling down the latest Docker
image for the Lambda runtime.
--force-image-build Specifies whether CLI should rebuild the image used for invoking
functions with layers.
--region TEXT Sets the AWS Region of the service (for example, us-east-1).
143
AWS Serverless Application Model Developer Guide
sam local start-lambda
Option Description
Usage:
Examples:
# SETUP
# ------
# Start the local Lambda endpoint by running this command in the directory that contains
your AWS SAM template.
Options:
Option Description
-p, --port INTEGER The local port number to listen on (default: '3001').
-t, --template PATH The AWS SAM template file [default: template.[yaml|yml]].
-n, --env-vars PATH The JSON file that contains values for the Lambda function's
environment variables.
144
AWS Serverless Application Model Developer Guide
sam logs
Option Description
-d, --debug-port TEXT When specified, starts the Lambda function container in debug mode,
and exposes this port on the local host.
--debugger-path TEXT The host path to a debugger to be mounted into the Lambda container.
-v, --docker-volume-basedir The location of the base directory where the AWS SAM file exists. If
TEXT Docker is running on a remote machine, you must mount the path where
the AWS SAM file exists on the Docker machine, and modify this value to
match the remote machine.
--docker-network TEXT The name or ID of an existing Docker network that Lambda Docker
containers should connect to, along with the default bridge network.
If this is specified, the Lambda containers only connect to the default
bridge Docker network.
-l, --log-file TEXT The log file to send runtime logs to.
--layer-cache-basedir Specifies the location basedir where the layers your template uses are
DIRECTORY downloaded to.
--skip-pull-image Specifies whether the CLI should skip pulling down the latest Docker
image for the Lambda runtime.
--force-image-build Specify whether the CLI should rebuild the image used for invoking
functions with layers.
--region TEXT Sets the AWS Region of the service (for example, us-east-1).
sam logs
Fetches logs that are generated by your Lambda function.
When your functions are a part of an AWS CloudFormation stack, you can fetch logs by using the
function's logical ID when you specify the stack name.
Usage:
Examples:
145
AWS Serverless Application Model Developer Guide
sam package
# You can view logs for a specific time range using the -s (--start-time) and -e (--end-
time) options
sam logs -n HelloWorldFunction --stack-name mystack -s '10min ago' -e '2min ago'
# You can also add the --tail option to wait for new logs and see them as they arrive.
sam logs -n HelloWorldFunction --stack-name mystack --tail
# Use the --filter option to quickly find logs that match terms, phrases or values in your
log events.
sam logs -n HelloWorldFunction --stack-name mystack --filter "error"
Options:
Option Description
-n, --name TEXT The name of your Lambda function. If this function is part of an AWS
CloudFormation stack, this can be the logical ID of the function resource
in the AWS CloudFormation/AWS SAM template. [required]
--stack-name TEXT The name of the AWS CloudFormation stack that the function is a part
of.
--filter TEXT Lets you specify an expression to quickly find logs that match terms,
phrases, or values in your log events. This can be a simple keyword (for
example, "error") or a pattern that's supported by Amazon CloudWatch
Logs. For the syntax, see the Amazon CloudWatch Logs documentation.
-s, --start-time TEXT Fetches logs starting at this time. The time can be relative values like
'5mins ago', 'yesterday', or a formatted timestamp like '2018-01-01
10:10:10'. It defaults to '10mins ago'.
-e, --end-time TEXT Fetches logs up to this time. The time can be relative values like '5mins
ago', 'tomorrow', or a formatted timestamp like '2018-01-01 10:10:10'.
-t, --tail Tails the log output. This ignores the end time argument and continues
to fetch logs as they become available.
--profile TEXT Selects a specific profile from your credential file to get AWS credentials.
--region TEXT Sets the AWS Region of the service (for example, us-east-1).
--debug Turns on debug logging to print debug messages that are generated by
the AWS SAM CLI.
sam package
Packages an AWS SAM application. It creates a ZIP file of your code and dependencies, and uploads it to
Amazon S3. It then returns a copy of your AWS SAM template, replacing references to local artifacts with
the Amazon S3 location where the command uploaded the artifacts.
Note
sam deploy (p. 136) now implicitly performs the functionality of sam package. You can use
the sam deploy (p. 136) command directly to package and deploy your application.
146
AWS Serverless Application Model Developer Guide
sam publish
Usage:
Options:
Option Description
--template-file PATH The path where your AWS SAM template is located. Default: template.
[yaml|yml].
--s3-bucket TEXT The name of the S3 bucket where this command uploads the artifacts
that are referenced in your template. Required.
--s3-prefix TEXT Prefix added to the artifacts name that are uploaded to the Amazon S3
bucket. The prefix name is a path name (folder name) for the Amazon S3
bucket.
--kms-key-id TEXT The ID of an AWS KMS key used to encrypt artifacts that are at rest in
the Amazon S3 bucket.
--output-template-file The path to the file where the command writes the packaged template.
PATH If you don't specify a path, the command writes the template to the
standard output.
--use-json Output JSON for the AWS CloudFormation template. YAML is used by
default.
--force-upload Override existing files in the Amazon S3 bucket. Specify this flag to
upload artifacts even if they match existing artifacts in the Amazon S3
bucket.
--metadata A map of metadata to attach to all artifacts that are referenced in your
template. Optional.
--profile TEXT Select a specific profile from your credential file to get AWS credentials.
--region TEXT Sets the AWS Region of the service (for example, us-east-1).
Note
If the AWS SAM template contains a Metadata section for ServerlessRepo, and the
LicenseUrl or ReadmeUrl properties contain references to local files, you must update AWS
CLI to version 1.16.77 or later. For more information about the Metadata section of AWS SAM
templates and publishing applications with AWS SAM CLI, see Publishing Serverless Applications
Using the AWS SAM CLI (p. 123).
sam publish
Publish an AWS SAM application to the AWS Serverless Application Repository. This command takes a
packaged AWS SAM template and publishes the application to the specified region.
This command expects the AWS SAM template to include a Metadata containing application metadata
required for publishing. Furthermore, these properties must include references to Amazon S3 buckets
147
AWS Serverless Application Model Developer Guide
sam validate
for LicenseUrl and ReadmeUrl values, and not references to local files. For more details about the
Metadata section of the AWS SAM template, see Publishing Serverless Applications Using the AWS SAM
CLI (p. 123).
This command creates the application as private by default, so you must share the application before
other AWS accounts are allowed to view and deploy the application. For more information on sharing
applications see Using Resource-Based Policies for the AWS Serverless Application Repository.
Usage:
Examples:
# To publish an application
sam publish --template packaged.yaml --region us-east-1
Options:
Option Description
--semantic-version TEXT Optional. The semantic version of the application provided by this
parameter overrides SemanticVersion in the Metadata section of the
template file. https://semver.org/
--profile TEXT Select a specific profile from your credential file to get AWS credentials.
--region TEXT Sets the AWS Region of the service (for example, us-east-1).
sam validate
Validates an AWS SAM template.
Usage:
Options:
Option Description
-t, --template PATH The AWS SAM template file [default: template.[yaml|yml]].
--profile TEXT Selects a specific profile from your credential file to get AWS credentials.
--region TEXT Sets the AWS Region of the service (for example, us-east-1).
148
AWS Serverless Application Model Developer Guide
AWS SAM CLI Config
For example, when executing the sam deploy --guided command, AWS SAM CLI automatically adds
the required parameters into the configuration file. You can subsequently execute sam deploy with no
parameters, and the values will be retrieved from the configuration file.
Config Basics
The configuration file for a project should be created as samconfig.toml in your project's root
directory. If you run a command like sam deploy --guided this file will be created for you. These files
are written in TOML format: https://github.com/toml-lang/toml.
Example
Here is an exampe AWS SAM CLI config file that is created when using the sam deploy --guided
command:
version=0.1
[default.deploy.parameters]
region = "us-west-2"
stack_name = "my-app-stack"
capabilites = "CAPABILITY_IAM"
s3_bucket = "my-source-bucket"
Options
region
Set the region you want to deploy to. If you omit region, then the AWS SAM CLI will try to resolve
the region through AWS profiles and then environment variables.
stack_name
A list of capabilities that you must specify to allow AWS CloudFormation to create certain stacks.
Some stack templates might include resources that can affect permissions in your AWS account, for
example, by creating new AWS Identity and Access Management (IAM) users. For those stacks, you
must explicitly acknowledge their capabilities by specifying this parameter.
The only valid values are CAPABILITY_IAM and CAPABILITY_NAMED_IAM. If you have IAM
resources, you can specify either capability. If you have IAM resources with custom names, you
must specify CAPABILITY_NAMED_IAM. If you don't specify this parameter, this action returns an
InsufficientCapabilities error.
149
AWS Serverless Application Model Developer Guide
AWS SAM Policy Templates
s3_bucket
The S3 bucket name used for deployment artifacts for the sam deploy command. You may use
your own Amazon S3 bucket by providing your own value here.
AWS SAM applications in the AWS Serverless Application Repository that use policy templates don't
require any special customer acknowledgments to deploy the application from the AWS Serverless
Application Repository.
1. Submit a pull request against the policy_templates.json source file in the develop branch of the AWS
SAM GitHub project. You can find the source file in policy_templates.json on the GitHub website.
2. Submit an issue in the AWS SAM GitHub project that includes the reasons for your pull request and a
link to the request. Use this link to submit a new issue: AWS Serverless Application Model: Issues.
Examples
There are two AWS SAM template examples in this section: one with a policy template that includes
placeholder values, and one that doesn't include placeholder values.
MyFunction:
Type: 'AWS::Serverless::Function'
Properties:
CodeUri: ${codeuri}
Handler: hello.handler
Runtime: python2.7
Policies:
- SQSPollerPolicy:
QueueName:
!GetAtt MyQueue.QueueName
MyFunction:
Type: 'AWS::Serverless::Function'
Properties:
CodeUri: ${codeuri}
Handler: hello.handler
Runtime: python2.7
Policies:
150
AWS Serverless Application Model Developer Guide
Policy Template Table
- CloudWatchPutMetricPolicy: {}
SQSPollerPolicy (p.Gives
154) permission to poll an Amazon SQS
Queue.
LambdaInvokePolicy
Gives
(p. 154)
permission to invoke a Lambda
function, alias, or version.
CloudWatchPutMetricPolicy
Gives permission
(p. 155) to put metrics to
CloudWatch.
EC2DescribePolicy (p.
Gives
155)
permission to describe Amazon EC2
instances.
DynamoDBCrudPolicy
Gives
(p.create,
155) read, update, and delete
permissions to a DynamoDB table.
DynamoDBReadPolicy
Gives(p.read-only
156) permission to a DynamoDB
table.
DynamoDBReconfigurePolicy
Gives permission
(p. 157)to reconfigure a DynamoDB
table.
SESSendBouncePolicy
Gives
(p.SendBounce
157) permission to an Amazon
SES identity.
ElasticsearchHttpPostPolicy
Gives POST(p. permission
157) to Amazon
Elasticsearch Service.
AMIDescribePolicy (p.
Gives
159)
permission to describe Amazon
Machine Images (AMIs).
CloudFormationDescribeStacksPolicy
Gives permission to(p.describe
160) AWS
CloudFormation stacks.
RekognitionDetectOnlyPolicy
Gives permission
(p. 160)
to detect faces, labels, and
text.
RekognitionNoDataAccessPolicy
Gives permission
(p. 160)
to compare and detect faces
and labels.
RekognitionReadPolicy
Gives(p.permission
161) to list and search faces.
RekognitionWriteOnlyAccessPolicy
Gives permission(p.
to161)
create collection and
index faces.
151
AWS Serverless Application Model Developer Guide
Policy Template Table
SQSSendMessagePolicy
Gives(p.
permission
162) to send message to an
Amazon SQS queue.
SNSPublishMessagePolicy
Gives permission
(p. 162) to publish a message to an
Amazon SNS topic.
VPCAccessPolicy (p.Gives
162) access to create, delete, describe, and
detach Elastic Network Interfaces.
DynamoDBStreamReadPolicy
Gives permission
(p. 163)
to describe and read
DynamoDB streams and records.
KinesisStreamReadPolicy
Gives permission
(p. 163) to list and read an Amazon
Kinesis stream.
KinesisCrudPolicy (p.
Gives
165)permission to create, publish, and
delete an Amazon Kinesis stream.
KMSDecryptPolicy (p.
Gives
165)
permission to decrypt with an AWS
KMS key.
PollyFullAccessPolicy
Gives
(p. 166)
full access permission to Amazon Polly
lexicon resources.
S3FullAccessPolicy Gives
(p. 166)
full access permission to objects in an
Amazon S3 bucket.
CodePipelineLambdaExecutionPolicy
Gives permission for
(p.a167)
Lambda function
invoked by CodePipeline to report the status
of the job.
ServerlessRepoReadWriteAccessPolicy
Gives permission to(p.
create
168)and list
applications in the AWS Serverless
Application Repository service.
EC2CopyImagePolicy
Gives
(p. 168)
permission to copy Amazon EC2
images.
AWSSecretsManagerRotationPolicy
Gives permission(p.
to 168)
rotate a secret in AWS
Secrets Manager.
AWSSecretsManagerGetSecretValuePolicy
Gives permission to GetSecretValue
(p. 169) for the
specified AWS Secrets Manager secret.
CodePipelineReadOnlyPolicy
Gives read(p.
permission
170) to get details about a
CodePipeline pipeline.
CloudWatchDashboardPolicy
Gives permissions
(p. 170) to put metrics to operate
on CloudWatch dashboards.
RekognitionFacesManagementPolicy
Gives permission to (p.add,
170)delete, and search
faces in a collection.
152
AWS Serverless Application Model Developer Guide
Policy Template Table
RekognitionFacesPolicy
Gives(p.
permission
171) to compare and detect faces
and labels.
RekognitionLabelsPolicy
Gives (p.
permission
171) to detect object and
moderation labels.
DynamoDBBackupFullAccessPolicy
Gives read and write
(p. 171)
permission to
DynamoDB on-demand backups for a table.
DynamoDBRestoreFromBackupPolicy
Gives permission to(p.
restore
172) a DynamoDB
table from backup.
ComprehendBasicAccessPolicy
Gives permission
(p. 173)
for detecting entities, key
phrases, languages, and sentiments.
MobileAnalyticsWriteOnlyAccessPolicy
Gives write-only permission
(p. 173) to put event data
for all application resources.
PinpointEndpointAccessPolicy
Gives permission
(p. 173)
to get and update
endpoints for an Amazon Pinpoint
application.
FirehoseWritePolicyGives
(p. 174)
permission to write to a Kinesis Data
Firehose delivery stream.
FirehoseCrudPolicyGives
(p. 174)
permission to create, write, update,
and delete a Kinesis Data Firehose delivery
stream.
EKSDescribePolicy (p.
Gives
175)
permission to describe or list Amazon
EKS clusters.
CostExplorerReadOnlyPolicy
Gives read-only
(p. 175)
permission to the read-only
Cost Explorer APIs for billing history.
OrganizationsListAccountsPolicy
Gives read-only
(p.permission
175) to list child
account names and IDs.
SESBulkTemplatedCrudPolicy
Gives permission
(p. 176)
to send email, templated
email, templated bulk emails and verify
identity.
SESEmailTemplateCrudPolicy
Gives permission
(p. 176)
to create, get, list, update
and delete Amazon SES email templates.
FilterLogEventsPolicy
Gives
(p. permission
176) to filter log events from a
specified log group.
SSMParameterReadPolicy
Gives permission
(p. 177) to access a parameter to
load secrets in this account.
StepFunctionsExecutionPolicy
Gives permission
(p. 177)
to access a parameter to
load secrets in this account.
CodeCommitCrudPolicy
Gives(p.
permissions
178) to create/read/update/
delete objects within a specific codecommit
repository.
153
AWS Serverless Application Model Developer Guide
Policy Template List
CodeCommitReadPolicy
Gives (p.
permissions
179) to read objects within a
specific codecommit repository.
SQSPollerPolicy
Gives permission to poll an Amazon SQS Queue.
"Statement": [
{
"Effect": "Allow",
"Action": [
"sqs:ChangeMessageVisibility",
"sqs:ChangeMessageVisibilityBatch",
"sqs:DeleteMessage",
"sqs:DeleteMessageBatch",
"sqs:GetQueueAttributes",
"sqs:ReceiveMessage"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:sqs:${AWS::Region}:${AWS::AccountId}:${queueName}",
{
"queueName": {
"Ref": "QueueName"
}
}
]
}
}
]
LambdaInvokePolicy
Gives permission to invoke a Lambda function, alias, or version.
"Statement": [
{
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:
${functionName}*",
{
"functionName": {
"Ref": "FunctionName"
154
AWS Serverless Application Model Developer Guide
Policy Template List
}
}
]
}
}
]
CloudWatchPutMetricPolicy
Gives permission to put metrics to CloudWatch.
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudwatch:PutMetricData"
],
"Resource": "*"
}
]
EC2DescribePolicy
Gives permission to describe Amazon EC2 instances.
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeRegions",
"ec2:DescribeInstances"
],
"Resource": "*"
}
]
DynamoDBCrudPolicy
Gives create, read, update, and delete permissions to a DynamoDB table.
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:DeleteItem",
"dynamodb:PutItem",
"dynamodb:Scan",
"dynamodb:Query",
"dynamodb:UpdateItem",
"dynamodb:BatchWriteItem",
"dynamodb:BatchGetItem",
"dynamodb:DescribeTable"
],
"Resource": [
155
AWS Serverless Application Model Developer Guide
Policy Template List
{
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}",
{
"tableName": {
"Ref": "TableName"
}
}
]
},
{
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}/index/*",
{
"tableName": {
"Ref": "TableName"
}
}
]
}
]
}
]
DynamoDBReadPolicy
Gives read-only permission to a DynamoDB table.
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:Scan",
"dynamodb:Query",
"dynamodb:BatchGetItem",
"dynamodb:DescribeTable"
],
"Resource": [
{
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}",
{
"tableName": {
"Ref": "TableName"
}
}
]
},
{
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}/index/*",
{
"tableName": {
"Ref": "TableName"
}
}
]
156
AWS Serverless Application Model Developer Guide
Policy Template List
}
]
}
]
DynamoDBReconfigurePolicy
Gives permission to reconfigure a DynamoDB table.
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:UpdateTable"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}",
{
"tableName": {
"Ref": "TableName"
}
}
]
}
}
]
SESSendBouncePolicy
Gives SendBounce permission to an Amazon SES identity.
"Statement": [
{
"Effect": "Allow",
"Action": [
"ses:SendBounce"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/
${identityName}",
{
"identityName": {
"Ref": "IdentityName"
}
}
]
}
}
]
ElasticsearchHttpPostPolicy
Gives POST and PUT permission to Amazon Elasticsearch Service.
157
AWS Serverless Application Model Developer Guide
Policy Template List
"Statement": [
{
"Effect": "Allow",
"Action": [
"es:ESHttpPost",
"es:ESHttpPut"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:es:${AWS::Region}:${AWS::AccountId}:domain/
${domainName}/*",
{
"domainName": {
"Ref": "DomainName"
}
}
]
}
}
]
S3ReadPolicy
Gives read-only permission to objects in an Amazon S3 bucket.
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket",
"s3:GetBucketLocation",
"s3:GetObjectVersion",
"s3:GetLifecycleConfiguration"
],
"Resource": [
{
"Fn::Sub": [
"arn:${AWS::Partition}:s3:::${bucketName}",
{
"bucketName": {
"Ref": "BucketName"
}
}
]
},
{
"Fn::Sub": [
"arn:${AWS::Partition}:s3:::${bucketName}/*",
{
"bucketName": {
"Ref": "BucketName"
}
}
]
}
]
}
]
158
AWS Serverless Application Model Developer Guide
Policy Template List
S3CrudPolicy
Gives create, read, update, and delete permission to objects in an Amazon S3 bucket.
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:ListBucket",
"s3:GetBucketLocation",
"s3:GetObjectVersion",
"s3:PutObject",
"s3:PutObjectAcl",
"s3:GetLifecycleConfiguration",
"s3:PutLifecycleConfiguration",
"s3:DeleteObject"
],
"Resource": [
{
"Fn::Sub": [
"arn:${AWS::Partition}:s3:::${bucketName}",
{
"bucketName": {
"Ref": "BucketName"
}
}
]
},
{
"Fn::Sub": [
"arn:${AWS::Partition}:s3:::${bucketName}/*",
{
"bucketName": {
"Ref": "BucketName"
}
}
]
}
]
}
]
AMIDescribePolicy
Gives permission to describe Amazon Machine Images (AMIs).
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeImages"
],
"Resource": {
"Fn::Sub": "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:image/
*"
}
}
]
159
AWS Serverless Application Model Developer Guide
Policy Template List
CloudFormationDescribeStacksPolicy
Gives permission to describe AWS CloudFormation stacks.
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudformation:DescribeStacks"
],
"Resource": {
"Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:
${AWS::AccountId}:stack/*"
}
}
]
RekognitionDetectOnlyPolicy
Gives permission to detect faces, labels, and text.
"Statement": [
{
"Effect": "Allow",
"Action": [
"rekognition:DetectFaces",
"rekognition:DetectLabels",
"rekognition:DetectModerationLabels",
"rekognition:DetectText"
],
"Resource": "*"
}
]
RekognitionNoDataAccessPolicy
Gives permission to compare and detect faces and labels.
"Statement": [
{
"Effect": "Allow",
"Action": [
"rekognition:CompareFaces",
"rekognition:DetectFaces",
"rekognition:DetectLabels",
"rekognition:DetectModerationLabels"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:rekognition:${AWS::Region}:
${AWS::AccountId}:collection/${collectionId}",
{
"collectionId": {
"Ref": "CollectionId"
160
AWS Serverless Application Model Developer Guide
Policy Template List
}
}
]
}
}
]
RekognitionReadPolicy
Gives permission to list and search faces.
"Statement": [
{
"Effect": "Allow",
"Action": [
"rekognition:ListCollections",
"rekognition:ListFaces",
"rekognition:SearchFaces",
"rekognition:SearchFacesByImage"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:rekognition:${AWS::Region}:
${AWS::AccountId}:collection/${collectionId}",
{
"collectionId": {
"Ref": "CollectionId"
}
}
]
}
}
]
RekognitionWriteOnlyAccessPolicy
Gives permission to create collection and index faces.
"Statement": [
{
"Effect": "Allow",
"Action": [
"rekognition:CreateCollection",
"rekognition:IndexFaces"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:rekognition:${AWS::Region}:
${AWS::AccountId}:collection/${collectionId}",
{
"collectionId": {
"Ref": "CollectionId"
}
}
]
}
}
]
161
AWS Serverless Application Model Developer Guide
Policy Template List
SQSSendMessagePolicy
Gives permission to send message to an Amazon SQS queue.
"Statement": [
{
"Effect": "Allow",
"Action": [
"sqs:SendMessage*"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:sqs:${AWS::Region}:${AWS::AccountId}:${queueName}",
{
"queueName": {
"Ref": "QueueName"
}
}
]
}
}
]
SNSPublishMessagePolicy
Gives permission to publish a message to an Amazon SNS topic.
"Statement": [
{
"Effect": "Allow",
"Action": [
"sns:Publish"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:sns:${AWS::Region}:${AWS::AccountId}:${topicName}",
{
"topicName": {
"Ref": "TopicName"
}
}
]
}
}
]
VPCAccessPolicy
Gives access to create, delete, describe, and detach Elastic Network Interfaces.
"Statement": [
{
"Effect": "Allow",
"Action": [
162
AWS Serverless Application Model Developer Guide
Policy Template List
"ec2:CreateNetworkInterface",
"ec2:DeleteNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DetachNetworkInterface"
],
"Resource": "*"
}
]
DynamoDBStreamReadPolicy
Gives permission to describe and read DynamoDB streams and records.
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:DescribeStream",
"dynamodb:GetRecords",
"dynamodb:GetShardIterator",
"dynamodb:ListStreams"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}/${streamName}",
{
"tableName": {
"Ref": "TableName"
},
"streamName": {
"Ref": "StreamName"
}
}
]
}
}
]
KinesisStreamReadPolicy
Gives permission to list and read an Amazon Kinesis stream.
"Statement": [
{
"Effect": "Allow",
"Action": [
"kinesis:ListStreams",
"kinesis:DescribeLimits"
],
"Resource": {
"Fn::Sub": "arn:${AWS::Partition}:kinesis:${AWS::Region}:
${AWS::AccountId}:stream/*"
}
},
{
"Effect": "Allow",
"Action": [
163
AWS Serverless Application Model Developer Guide
Policy Template List
"kinesis:DescribeStream",
"kinesis:GetRecords",
"kinesis:GetShardIterator"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:kinesis:${AWS::Region}:${AWS::AccountId}:stream/
${streamName}",
{
"streamName": {
"Ref": "StreamName"
}
}
]
}
}
]
SESCrudPolicy
Gives permission to send email and verify identity.
"Statement": [
{
"Effect": "Allow",
"Action": [
"ses:GetIdentityVerificationAttributes",
"ses:SendEmail",
"ses:VerifyEmailIdentity"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/
${identityName}",
{
"identityName": {
"Ref": "IdentityName"
}
}
]
}
}
]
SNSCrudPolicy
Gives permission to create, publish, and subscribe to Amazon SNS topics.
"Statement": [
{
"Effect": "Allow",
"Action": [
"sns:ListSubscriptionsByTopic",
"sns:CreateTopic",
"sns:SetTopicAttributes",
"sns:Subscribe",
"sns:Publish"
],
164
AWS Serverless Application Model Developer Guide
Policy Template List
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:sns:${AWS::Region}:${AWS::AccountId}:${topicName}*",
{
"topicName": {
"Ref": "TopicName"
}
}
]
}
}
]
KinesisCrudPolicy
Gives permission to create, publish, and delete an Amazon Kinesis stream.
"Statement": [
{
"Effect": "Allow",
"Action": [
"kinesis:AddTagsToStream",
"kinesis:CreateStream",
"kinesis:DecreaseStreamRetentionPeriod",
"kinesis:DeleteStream",
"kinesis:DescribeStream",
"kinesis:GetShardIterator",
"kinesis:IncreaseStreamRetentionPeriod",
"kinesis:ListTagsForStream",
"kinesis:MergeShards",
"kinesis:PutRecord",
"kinesis:PutRecords",
"kinesis:SplitShard",
"kinesis:RemoveTagsFromStream"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:kinesis:${AWS::Region}:${AWS::AccountId}:stream/
${streamName}",
{
"streamName": {
"Ref": "StreamName"
}
}
]
}
}
]
KMSDecryptPolicy
Gives permission to decrypt with an AWS KMS key.
"Statement": [
{
"Action": "kms:Decrypt",
"Effect": "Allow",
"Resource": {
165
AWS Serverless Application Model Developer Guide
Policy Template List
"Fn::Sub": [
"arn:${AWS::Partition}:kms:${AWS::Region}:${AWS::AccountId}:key/${keyId}",
{
"keyId": {
"Ref": "KeyId"
}
}
]
}
}
]
PollyFullAccessPolicy
Gives full access permission to Amazon Polly lexicon resources.
"Statement": [
{
"Effect": "Allow",
"Action": [
"polly:GetLexicon",
"polly:DeleteLexicon"
],
"Resource": [
{
"Fn::Sub": [
"arn:${AWS::Partition}:polly:${AWS::Region}:${AWS::AccountId}:lexicon/
${lexiconName}",
{
"lexiconName": {
"Ref": "LexiconName"
}
}
]
}
]
},
{
"Effect": "Allow",
"Action": [
"polly:DescribeVoices",
"polly:ListLexicons",
"polly:PutLexicon",
"polly:SynthesizeSpeech"
],
"Resource": [
{
"Fn::Sub": "arn:${AWS::Partition}:polly:${AWS::Region}:
${AWS::AccountId}:lexicon/*"
}
]
}
]
S3FullAccessPolicy
Gives full access permission to objects in an Amazon S3 bucket.
166
AWS Serverless Application Model Developer Guide
Policy Template List
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:GetObjectAcl",
"s3:GetObjectVersion",
"s3:PutObject",
"s3:PutObjectAcl",
"s3:DeleteObject",
"s3:DeleteObjectTagging",
"s3:DeleteObjectVersionTagging",
"s3:GetObjectTagging",
"s3:GetObjectVersionTagging",
"s3:PutObjectTagging",
"s3:PutObjectVersionTagging"
],
"Resource": [
{
"Fn::Sub": [
"arn:${AWS::Partition}:s3:::${bucketName}/*",
{
"bucketName": {
"Ref": "BucketName"
}
}
]
}
]
},
{
"Effect": "Allow",
"Action": [
"s3:ListBucket",
"s3:GetBucketLocation",
"s3:GetLifecycleConfiguration",
"s3:PutLifecycleConfiguration"
],
"Resource": [
{
"Fn::Sub": [
"arn:${AWS::Partition}:s3:::${bucketName}",
{
"bucketName": {
"Ref": "BucketName"
}
}
]
}
]
}
]
CodePipelineLambdaExecutionPolicy
Gives permission for a Lambda function invoked by CodePipeline to report the status of the job.
"Statement": [
{
"Effect": "Allow",
"Action": [
"codepipeline:PutJobSuccessResult",
167
AWS Serverless Application Model Developer Guide
Policy Template List
"codepipeline:PutJobFailureResult"
],
"Resource": "*"
}
]
ServerlessRepoReadWriteAccessPolicy
Gives permission to create and list applications in the AWS Serverless Application Repository service.
"Statement": [
{
"Effect": "Allow",
"Action": [
"serverlessrepo:CreateApplication",
"serverlessrepo:CreateApplicationVersion",
"serverlessrepo:GetApplication",
"serverlessrepo:ListApplications",
"serverlessrepo:ListApplicationVersions"
],
"Resource": [
{
"Fn::Sub": "arn:${AWS::Partition}:serverlessrepo:${AWS::Region}:
${AWS::AccountId}:applications/*"
}
]
}
]
EC2CopyImagePolicy
Gives permission to copy Amazon EC2 images.
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:CopyImage"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:image/
${imageId}",
{
"imageId": {
"Ref": "ImageId"
}
}
]
}
}
]
AWSSecretsManagerRotationPolicy
Gives permission to rotate a secret in AWS Secrets Manager.
168
AWS Serverless Application Model Developer Guide
Policy Template List
"Statement": [
{
"Effect": "Allow",
"Action": [
"secretsmanager:DescribeSecret",
"secretsmanager:GetSecretValue",
"secretsmanager:PutSecretValue",
"secretsmanager:UpdateSecretVersionStage"
],
"Resource": {
"Fn::Sub": "arn:${AWS::Partition}:secretsmanager:${AWS::Region}:
${AWS::AccountId}:secret:*"
},
"Condition": {
"StringEquals": {
"secretsmanager:resource/AllowRotationLambdaArn": {
"Fn::Sub": [
"arn:${AWS::Partition}:lambda:${AWS::Region}:
${AWS::AccountId}:function:${functionName}",
{
"functionName": {
"Ref": "FunctionName"
}
}
]
}
}
}
},
{
"Effect": "Allow",
"Action": [
"secretsmanager:GetRandomPassword"
],
"Resource": "*"
}
]
AWSSecretsManagerGetSecretValuePolicy
Gives permission to GetSecretValue for the specified AWS Secrets Manager secret.
"Statement": [
{
"Effect": "Allow",
"Action": [
"secretsmanager:GetSecretValue"
],
"Resource": {
"Fn::Sub": [
"${secretArn}",
{
"secretArn": {
"Ref": "SecretArn"
}
}
]
}
}
]
169
AWS Serverless Application Model Developer Guide
Policy Template List
CodePipelineReadOnlyPolicy
Gives read permission to get details about a CodePipeline pipeline.
"Statement": [
{
"Effect": "Allow",
"Action": [
"codepipeline:ListPipelineExecutions"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:codepipeline:${AWS::Region}:${AWS::AccountId}:
${pipelinename}",
{
"pipelinename": {
"Ref": "PipelineName"
}
}
]
}
}
]
CloudWatchDashboardPolicy
Gives permissions to put metrics to operate on CloudWatch dashboards.
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudwatch:GetDashboard",
"cloudwatch:ListDashboards",
"cloudwatch:PutDashboard",
"cloudwatch:ListMetrics"
],
"Resource": "*"
}
]
RekognitionFacesManagementPolicy
Gives permission to add, delete, and search faces in a collection.
"Statement": [{
"Effect": "Allow",
"Action": [
"rekognition:IndexFaces",
"rekognition:DeleteFaces",
"rekognition:SearchFaces",
"rekognition:SearchFacesByImage",
"rekognition:ListFaces"
],
170
AWS Serverless Application Model Developer Guide
Policy Template List
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:rekognition:${AWS::Region}:
${AWS::AccountId}:collection/${collectionId}",
{
"collectionId": {
"Ref": "CollectionId"
}
}
]
}
]
RekognitionFacesPolicy
Gives permission to compare and detect faces and labels.
"Statement": [{
"Effect": "Allow",
"Action": [
"rekognition:CompareFaces",
"rekognition:DetectFaces"
],
"Resource": "*"
}
]
RekognitionLabelsPolicy
Gives permission to detect object and moderation labels.
"Statement": [{
"Effect": "Allow",
"Action": [
"rekognition:DetectLabels",
"rekognition:DetectModerationLabels"
],
"Resource": "*"
}
]
DynamoDBBackupFullAccessPolicy
Gives read and write permission to DynamoDB on-demand backups for a table.
"Statement": [{
"Effect": "Allow",
"Action": [
"dynamodb:CreateBackup",
"dynamodb:DescribeContinuousBackups"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}",
171
AWS Serverless Application Model Developer Guide
Policy Template List
{
"tableName": {
"Ref": "TableName"
}
}
]
}
},
{
"Effect": "Allow",
"Action": [
"dynamodb:DeleteBackup",
"dynamodb:DescribeBackup",
"dynamodb:ListBackups"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}/backup/*",
{
"tableName": {
"Ref": "TableName"
}
}
]
}
}
]
DynamoDBRestoreFromBackupPolicy
Gives permission to restore a DynamoDB table from backup.
"Statement": [{
"Effect": "Allow",
"Action": [
"dynamodb:RestoreTableFromBackup"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}/backup/*",
{
"tableName": {
"Ref": "TableName"
}
}
]
}
},
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:DeleteItem",
"dynamodb:GetItem",
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:BatchWriteItem"
],
"Resource": {
172
AWS Serverless Application Model Developer Guide
Policy Template List
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}",
{
"tableName": {
"Ref": "TableName"
}
}
]
}
}
]
ComprehendBasicAccessPolicy
Gives permission for detecting entities, key phrases, languages, and sentiments.
"Statement": [{
"Effect": "Allow",
"Action": [
"comprehend:BatchDetectKeyPhrases",
"comprehend:DetectDominantLanguage",
"comprehend:DetectEntities",
"comprehend:BatchDetectEntities",
"comprehend:DetectKeyPhrases",
"comprehend:DetectSentiment",
"comprehend:BatchDetectDominantLanguage",
"comprehend:BatchDetectSentiment"
],
"Resource": "*"
}
]
MobileAnalyticsWriteOnlyAccessPolicy
Gives write-only permission to put event data for all application resources.
"Statement": [
{
"Effect": "Allow",
"Action": [
"mobileanalytics:PutEvents"
],
"Resource": "*"
}
]
PinpointEndpointAccessPolicy
Gives permission to get and update endpoints for an Amazon Pinpoint application.
"Statement": [
{
"Effect": "Allow",
"Action": [
173
AWS Serverless Application Model Developer Guide
Policy Template List
"mobiletargeting:GetEndpoint",
"mobiletargeting:UpdateEndpoint",
"mobiletargeting:UpdateEndpointsBatch"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:mobiletargeting:${AWS::Region}:
${AWS::AccountId}:apps/${pinpointApplicationId}/endpoints/*",
{
"pinpointApplicationId": {
"Ref": "PinpointApplicationId"
}
}
]
}
}
]
FirehoseWritePolicy
Gives permission to write to a Kinesis Data Firehose delivery stream.
"Statement": [
{
"Effect": "Allow",
"Action": [
"firehose:PutRecord",
"firehose:PutRecordBatch"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:firehose:${AWS::Region}:
${AWS::AccountId}:deliverystream/${deliveryStreamName}",
{
"deliveryStreamName": {
"Ref": "DeliveryStreamName"
}
}
]
}
}
]
FirehoseCrudPolicy
Gives permission to create, write, update, and delete a Kinesis Data Firehose delivery stream.
"Statement": [
{
"Effect": "Allow",
"Action": [
"firehose:CreateDeliveryStream",
"firehose:DeleteDeliveryStream",
"firehose:DescribeDeliveryStream",
"firehose:PutRecord",
"firehose:PutRecordBatch",
"firehose:UpdateDestination"
],
174
AWS Serverless Application Model Developer Guide
Policy Template List
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:firehose:${AWS::Region}:
${AWS::AccountId}:deliverystream/${deliveryStreamName}",
{
"deliveryStreamName": {
"Ref": "DeliveryStreamName"
}
}
]
}
}
]
EKSDescribePolicy
Gives permission to describe or list Amazon EKS clusters.
"Statement": [
{
"Effect": "Allow",
"Action": [
"eks:DescribeCluster",
"eks:ListClusters"
],
"Resource": "*"
}
]
CostExplorerReadOnlyPolicy
Gives read-only permission to the read-only Cost Explorer APIs for billing history.
"Statement": [{
"Effect": "Allow",
"Action": [
"ce:GetCostAndUsage",
"ce:GetDimensionValues",
"ce:GetReservationCoverage",
"ce:GetReservationPurchaseRecommendation",
"ce:GetReservationUtilization",
"ce:GetTags"
],
"Resource": "*"
}]
OrganizationsListAccountsPolicy
Gives read-only permission to list child account names and IDs.
"Statement": [{
"Effect": "Allow",
"Action": [
"organizations:ListAccounts"
],
175
AWS Serverless Application Model Developer Guide
Policy Template List
"Resource": "*"
}]
SESBulkTemplatedCrudPolicy
Gives permission to send email, templated email, templated bulk emails and verify identity.
"Statement": [
{
"Effect": "Allow",
"Action": [
"ses:GetIdentityVerificationAttributes",
"ses:SendEmail",
"ses:SendRawEmail",
"ses:SendTemplatedEmail",
"ses:SendBulkTemplatedEmail",
"ses:VerifyEmailIdentity"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/
${identityName}",
{
"identityName": {
"Ref": "IdentityName"
}
}
]
}
}
]
SESEmailTemplateCrudPolicy
Gives permission to create, get, list, update and delete Amazon SES email templates.
"Statement": [{
"Effect": "Allow",
"Action": [
"ses:CreateTemplate",
"ses:GetTemplate",
"ses:ListTemplates",
"ses:UpdateTemplate",
"ses:DeleteTemplate",
"ses:TestRenderTemplate"
],
"Resource": "*"
}]
FilterLogEventsPolicy
Gives permission to filter log events from a specified log group.
"Statement": [
{
176
AWS Serverless Application Model Developer Guide
Policy Template List
"Effect": "Allow",
"Action": [
"logs:FilterLogEvents"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:
${logGroupName}:log-stream:*",
{
"logGroupName": {
"Ref": "LogGroupName"
}
}
]
}
}
]
SSMParameterReadPolicy
Gives permission to access a parameter to load secrets in this account.
Note
If you are not using default key, you will also need KMSDecryptPolicy.
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssm:DescribeParameters"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"ssm:GetParameters",
"ssm:GetParameter",
"ssm:GetParametersByPath"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/
${parameterName}",
{
"parameterName": {
"Ref": "ParameterName"
}
}
]
}
}
]
StepFunctionsExecutionPolicy
Gives permission to start a Step Functions state machine execution.
"Statement": [
177
AWS Serverless Application Model Developer Guide
Policy Template List
{
"Effect": "Allow",
"Action": [
"states:StartExecution"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:states:${AWS::Region}:
${AWS::AccountId}:stateMachine:${stateMachineName}",
{
"stateMachineName": {
"Ref": "StateMachineName"
}
}
]
}
}
]
CodeCommitCrudPolicy
Gives permissions to create/read/update/delete objects within a specific codecommit repository.
"Statement": [
{
"Effect": "Allow",
"Action": [
"codecommit:GitPull",
"codecommit:GitPush",
"codecommit:CreateBranch",
"codecommit:DeleteBranch",
"codecommit:GetBranch",
"codecommit:ListBranches",
"codecommit:MergeBranchesByFastForward",
"codecommit:MergeBranchesBySquash",
"codecommit:MergeBranchesByThreeWay",
"codecommit:UpdateDefaultBranch",
"codecommit:BatchDescribeMergeConflicts",
"codecommit:CreateUnreferencedMergeCommit",
"codecommit:DescribeMergeConflicts",
"codecommit:GetMergeCommit",
"codecommit:GetMergeOptions",
"codecommit:BatchGetPullRequests",
"codecommit:CreatePullRequest",
"codecommit:DescribePullRequestEvents",
"codecommit:GetCommentsForPullRequest",
"codecommit:GetCommitsFromMergeBase",
"codecommit:GetMergeConflicts",
"codecommit:GetPullRequest",
"codecommit:ListPullRequests",
"codecommit:MergePullRequestByFastForward",
"codecommit:MergePullRequestBySquash",
"codecommit:MergePullRequestByThreeWay",
"codecommit:PostCommentForPullRequest",
"codecommit:UpdatePullRequestDescription",
"codecommit:UpdatePullRequestStatus",
"codecommit:UpdatePullRequestTitle",
"codecommit:DeleteFile",
"codecommit:GetBlob",
"codecommit:GetFile",
"codecommit:GetFolder",
"codecommit:PutFile",
178
AWS Serverless Application Model Developer Guide
Policy Template List
"codecommit:DeleteCommentContent",
"codecommit:GetComment",
"codecommit:GetCommentsForComparedCommit",
"codecommit:PostCommentForComparedCommit",
"codecommit:PostCommentReply",
"codecommit:UpdateComment",
"codecommit:BatchGetCommits",
"codecommit:CreateCommit",
"codecommit:GetCommit",
"codecommit:GetCommitHistory",
"codecommit:GetDifferences",
"codecommit:GetObjectIdentifier",
"codecommit:GetReferences",
"codecommit:GetTree",
"codecommit:GetRepository",
"codecommit:UpdateRepositoryDescription",
"codecommit:ListTagsForResource",
"codecommit:TagResource",
"codecommit:UntagResource",
"codecommit:GetRepositoryTriggers",
"codecommit:PutRepositoryTriggers",
"codecommit:TestRepositoryTriggers",
"codecommit:GetBranch",
"codecommit:GetCommit",
"codecommit:UploadArchive",
"codecommit:GetUploadArchiveStatus",
"codecommit:CancelUploadArchive"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:codecommit:${AWS::Region}:${AWS::AccountId}:
${repositoryName}",
{
"repositoryName": {
"Ref": "RepositoryName"
}
}
]
}
}
]
CodeCommitReadPolicy
Gives permissions to read objects within a specific codecommit repository.
"Statement": [
{
"Effect": "Allow",
"Action": [
"codecommit:GitPull",
"codecommit:GetBranch",
"codecommit:ListBranches",
"codecommit:BatchDescribeMergeConflicts",
"codecommit:DescribeMergeConflicts",
"codecommit:GetMergeCommit",
"codecommit:GetMergeOptions",
"codecommit:BatchGetPullRequests",
"codecommit:DescribePullRequestEvents",
"codecommit:GetCommentsForPullRequest",
"codecommit:GetCommitsFromMergeBase",
"codecommit:GetMergeConflicts",
179
AWS Serverless Application Model Developer Guide
AWS SAM CLI Telemetry
"codecommit:GetPullRequest",
"codecommit:ListPullRequests",
"codecommit:GetBlob",
"codecommit:GetFile",
"codecommit:GetFolder",
"codecommit:GetComment",
"codecommit:GetCommentsForComparedCommit",
"codecommit:BatchGetCommits",
"codecommit:GetCommit",
"codecommit:GetCommitHistory",
"codecommit:GetDifferences",
"codecommit:GetObjectIdentifier",
"codecommit:GetReferences",
"codecommit:GetTree",
"codecommit:GetRepository",
"codecommit:ListTagsForResource",
"codecommit:GetRepositoryTriggers",
"codecommit:TestRepositoryTriggers",
"codecommit:GetBranch",
"codecommit:GetCommit",
"codecommit:GetUploadArchiveStatus"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:codecommit:${AWS::Region}:${AWS::AccountId}:
${repositoryName}",
{
"repositoryName": {
"Ref": "RepositoryName"
}
}
]
}
}
]
The AWS SAM CLI collects telemetry, such as generic usage metrics, system and environment
information, and errors. For details of the types of telemetry collected, see Types of Information
Collected (p. 181).
The AWS SAM CLI does not collect personal information, such as usernames or email addresses. It also
does not extract sensitive project-level information.
Customers control whether telemetry is enabled, and can change their settings at any point of time. If
telemetry remains enabled, the AWS SAM CLI sends telemetry data in the background without requiring
any additional customer interaction.
180
AWS Serverless Application Model Developer Guide
Disabling Telemetry for Your Profile in All Sessions
export SAM_CLI_TELEMETRY=0
1. Run:
2. Run:
source ~/.profile
1. Run:
2. Run:
source ~/.profile
1. Run:
setx SAM_CLI_TELEMETRY 0
2. Run:
refreshenv
181
AWS Serverless Application Model Developer Guide
Learn More
Learn More
The telemetry data that's collected adheres to the AWS data privacy policies. For more information, see
the following:
182
AWS Serverless Application Model Developer Guide
AWS SAM Specification and AWS Migrated the AWS SAM November 25, 2019
SAM CLI updates (p. 183) Specification from GitHub. For
more information see AWS SAM
Specification. Also updated
the deployment workflow with
changes to the sam deploy
command.
New options for controlling Added new options for August 29, 2019
access to API Gateway controlling access to API
APIs and policy template Gateway APIs: IAM permissions,
updates (p. 183) API keys, and resource policies.
For more information, see
Controlling Access to API
Gateway APIs. Also updated
two policy templates:
RekognitionFacesPolicy and
ElasticsearchHttpPostPolicy. For
more information, see AWS SAM
Policy Templates.
Controlling access to API Added support for controlling March 21, 2019
Gateway APIs (p. 183) access to API Gateway APIs.
For more information, see
Controlling Access to API
Gateway APIs.
Added sam publish to the AWS The new sam publish December 21, 2018
SAM CLI (p. 183) command in the AWS SAM
CLI simplifies the process
for publishing serverless
applications in the AWS
Serverless Application
183
AWS Serverless Application Model Developer Guide
Nested applications and layers Added support for nested November 29, 2018
support (p. 183) applications and layers. For
more information, see Nested
Applications and Working with
Layers.
Added sam build to the AWS The new sam build command November 19, 2018
SAM CLI (p. 183) in the AWS SAM CLI simplifies
the process for compiling
serverless applications
with dependencies so you
can locally test and deploy
these applications. For more
information, see Building
Applications with Dependencies.
Added new installation options Added Linuxbrew (Linux), MSI November 7, 2018
for the AWS SAM CLI (p. 183) (Windows), and Homebrew
(macOS) installation options
for the AWS SAM CLI. For more
information, see Installing the
AWS SAM CLI.
New guide (p. 183) This is the first release of the October 17, 2018
AWS Serverless Application Model
Developer Guide.
184