Serverless Application Model
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 ........................................................................................................................... 7
macOS .............................................................................................................................. 9
Setting up AWS credentials ....................................................................................................... 11
Using the AWS CLI ........................................................................................................... 12
Not using the AWS CLI ..................................................................................................... 12
Tutorial: Hello World application ................................................................................................ 12
Prerequisites .................................................................................................................... 13
Step 1: Download a sample AWS SAM application ................................................................ 14
Step 2: Build your application ............................................................................................ 15
Step 3: Deploy your application to the AWS Cloud ................................................................ 15
Step 4: (Optional) Test your application locally .................................................................... 18
Troubleshooting ............................................................................................................... 20
Clean up ......................................................................................................................... 22
Conclusion ....................................................................................................................... 22
Next steps ....................................................................................................................... 22
AWS SAM specification ...................................................................................................................... 24
Template anatomy ................................................................................................................... 24
YAML .............................................................................................................................. 24
Template sections ............................................................................................................ 25
Next steps ....................................................................................................................... 26
Globals ............................................................................................................................ 26
Resource and property reference ................................................................................................ 30
AWS::Serverless::Api .......................................................................................................... 30
AWS::Serverless::Application ............................................................................................... 61
AWS::Serverless::Function .................................................................................................. 65
AWS::Serverless::HttpApi .................................................................................................. 120
AWS::Serverless::LayerVersion ........................................................................................... 139
AWS::Serverless::SimpleTable ........................................................................................... 142
AWS::Serverless::StateMachine .......................................................................................... 145
Resource attributes ................................................................................................................. 161
Intrinsic functions ................................................................................................................... 162
Generated resources ............................................................................................................... 162
Referencing generated AWS CloudFormation resources ........................................................ 162
Generated AWS CloudFormation resource reference ............................................................ 163
AWS::Serverless::Api ........................................................................................................ 164
AWS::Serverless::Function ................................................................................................ 165
AWS::Serverless::HttpApi .................................................................................................. 167
API Gateway extensions .......................................................................................................... 168
Authoring ...................................................................................................................................... 170
Validating AWS SAM template files ........................................................................................... 170
Working with layers ................................................................................................................ 170
Using nested applications ........................................................................................................ 172
Defining a nested application from the AWS Serverless Application Repository ....................... 172
Defining a nested application from the local file system ...................................................... 173
Deploying nested applications .......................................................................................... 174
Controlling access to APIs ........................................................................................................ 174
Choosing a mechanism to control access ........................................................................... 176
Customizing error responses ............................................................................................ 176
iii
AWS Serverless Application Model Developer Guide
iv
AWS Serverless Application Model Developer Guide
Step 1: Add a Metadata section to the AWS SAM template .................................................. 212
Step 2: Package the application ....................................................................................... 212
Step 3: Publish the application ......................................................................................... 213
Publishing a new version of an existing application ..................................................................... 213
Additional topics .................................................................................................................... 213
Metadata section properties ..................................................................................................... 214
Properties ...................................................................................................................... 214
Use cases ....................................................................................................................... 215
Example ........................................................................................................................ 216
Example applications ...................................................................................................................... 217
Process DynamoDB events ....................................................................................................... 217
Before you begin ............................................................................................................ 217
Step 1: Initialize the application ....................................................................................... 217
Step 2: Test the application locally ................................................................................... 217
Step 3: Package the application ....................................................................................... 218
Step 4: Deploy the application ......................................................................................... 218
Next steps ..................................................................................................................... 219
Process Amazon S3 events ...................................................................................................... 219
Before you begin ............................................................................................................ 219
Step 1: Initialize the application ....................................................................................... 219
Step 2: Package the application ....................................................................................... 220
Step 3: Deploy the application ......................................................................................... 220
Step 4: Test the application locally ................................................................................... 221
Next steps ..................................................................................................................... 221
AWS SAM reference ........................................................................................................................ 222
AWS SAM specification ............................................................................................................ 222
AWS SAM CLI command reference ............................................................................................ 222
AWS SAM policy templates ...................................................................................................... 222
Topics ................................................................................................................................... 222
AWS SAM CLI command reference ............................................................................................ 223
sam build ...................................................................................................................... 223
sam deploy .................................................................................................................... 225
sam init ......................................................................................................................... 229
sam local generate-event ................................................................................................ 231
sam local invoke ............................................................................................................. 233
sam local start-api .......................................................................................................... 234
sam local start-lambda .................................................................................................... 236
sam logs ........................................................................................................................ 238
sam package .................................................................................................................. 240
sam publish ................................................................................................................... 241
sam validate .................................................................................................................. 242
AWS SAM CLI configuration file ................................................................................................ 243
Example ........................................................................................................................ 243
Configuration file rules .................................................................................................... 243
Writing configurations with sam deploy --guided ......................................................... 244
AWS SAM policy templates ...................................................................................................... 245
Syntax ........................................................................................................................... 245
Examples ....................................................................................................................... 246
Policy template table ...................................................................................................... 246
Troubleshooting ............................................................................................................. 250
Policy template list ......................................................................................................... 251
AWS SAM CLI telemetry .......................................................................................................... 286
Disabling telemetry for a session ...................................................................................... 286
Disabling telemetry for your profile in all sessions .............................................................. 286
Types of information collected ......................................................................................... 287
Learn more .................................................................................................................... 287
Permissions ............................................................................................................................ 288
v
AWS Serverless Application Model Developer Guide
vi
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. 24).
• 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. 222).
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. 12) 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)
• Setting up AWS credentials (p. 11)
• Tutorial: Deploying a Hello World application (p. 12)
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. 7)
• Installing the AWS SAM CLI on macOS (p. 9)
Note
Following these instructions changes your environment's default Python version to the one that
Homebrew installs. This change occurs in Step 4: Install Homebrew (p. 5).
3
AWS Serverless Application Model Developer Guide
Linux
In addition, to enable the AWS SAM CLI to make AWS service calls, you must set up AWS credentials. For
more information, see Setting up AWS credentials (p. 11).
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.
To run serverless projects and functions locally with the AWS SAM CLI, you must have Docker installed
and working. 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,
for example, CentOS, Debian, and Ubuntu. For information about installing Docker on your particular
operating system, see Get Docker on the Docker Docs website.
4. Add the ec2-user to the docker group so that you can run Docker commands without using sudo.
5. Log out and log back in again to pick up the new docker group permissions. You can do 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 using sudo.
4
AWS Serverless Application Model Developer Guide
Linux
docker ps
You should see the following output, confirming that Docker is installed and running:
If you run into issues installing Docker, see the Troubleshooting (p. 6) section later in this guide. Or,
see the Troubleshooting section of Post-installation steps for Linux on the Docker Docs website.
To install the AWS SAM CLI on Linux, we recommend using the Homebrew package manager. For more
information about Homebrew, see Homebrew on Linux on the Homebrew Documentation website.
To install Homebrew, you must first install Git. Git is available on many different operating systems,
including most modern Linux distributions. For instructions about installing Git on your particular
operating system, see Installing Git on the Git website.
After successfully installing Git, to install Homebrew, run the following command:
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 and Ubuntu, or ~/.bash_profile on
CentOS, Fedora, and RedHat.
brew --version
On successful installation of Homebrew, you should see output like the following:
Homebrew 2.1.6
Homebrew/homebrew-core (git revision ef21; last commit 2019-06-19)
5
AWS Serverless Application Model Developer Guide
Linux
sam --version
On successful installation of the AWS SAM CLI, you should see output like the following:
Upgrading
To upgrade the AWS SAM CLI, you still use Homebrew, but replace install with upgrade as follows:
Troubleshooting
Docker error: "Cannot connect to the Docker daemon. Is the docker daemon
running on this host?"
In some cases, to provide permissions for the ec2-user to access the Docker daemon, you might need
to reboot your instance. If you receive this error, try rebooting your instance.
For example, if you used the instructions in this topic to both install Homebrew and use Homebrew to
install the AWS SAM CLI, then the AWS SAM CLI executable is installed to the following location:
/home/linuxbrew/.linuxbrew/bin/sam
If you do not want to set up a password for the current user, you can install Homebrew in non-interactive
mode by setting the environmentment variable CI=1. For example:
6
AWS Serverless Application Model Developer Guide
Windows
Installing AWS SAM CLI error: "The following formulae cannot be installed from
bottles and must be built from source. pkg-config, gdbm, openssl@1.1, ncurses,
xz and python@3.8
During Step 5: Install the AWS SAM CLI, if you see this error, it is because you don't have the gcc
module installed. Installing the gcc module depends on your Linux distribution, as follows:
After installing the gcc module, run the commands in Step 5: Install the AWS SAM CLI again.
Next steps
You're now ready to begin building your own serverless applications using AWS SAM. To start with a
sample serverless application, choose one of the following links:
• Tutorial: Deploying a Hello World application (p. 12) – 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.
7
AWS Serverless Application Model Developer Guide
Windows
In addition, to enable the AWS SAM CLI to make AWS service calls, you must set up AWS credentials. For
more information, see Setting up AWS credentials (p. 11).
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.
To run serverless projects and functions locally with the AWS SAM CLI, you must have Docker installed
and working. 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. In some cases you must share your drive in order for Docker to function properly.
After Docker is installed, verify that it's working. Also confirm that you can run Docker commands
from the command line (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 Logs and troubleshooting section of the Docker
installation guide for additional 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.
8
AWS Serverless Application Model Developer Guide
macOS
sam --version
You should see output like the following after successful installation of the AWS SAM CLI:
3. Install Git.
To download sample applications using the sam init command, you must also install Git. For
instructions, see Installing Git.
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. 12) – 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.
9
AWS Serverless Application Model Developer Guide
macOS
In addition, to enable the AWS SAM CLI to make AWS service calls, you must set up AWS credentials. For
more information, see Setting up AWS credentials (p. 11).
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.
To run serverless projects and functions locally with the AWS SAM CLI, you must have Docker installed
and working. 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
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 command line (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 Logs and troubleshooting section of the Docker
installation guide for additional troubleshooting tips.
To install Homebrew, you must first install Git. For more information about Git, see Git Documentation.
Git is available on many different operating systems, including macOS. For instructions about installing
Git on your particular operating system, see Installing Git.
Once you have successfully installed Git, run the following to install Homebrew, making sure to follow
the prompts:
brew --version
10
AWS Serverless Application Model Developer Guide
Setting up AWS credentials
You should see output like the following on successful installation of Homebrew:
Homebrew 2.5.7
Homebrew/homebrew-core (git revision 1be3ad; last commit 2020-10-29)
Homebrew/homebrew-cask (git revision a0cf3; last commit 2020-10-29)
sam --version
You should see output like the following after successful installation of the AWS SAM CLI:
Upgrading
To upgrade the AWS SAM CLI, you still use Homebrew, but replace install with upgrade as follows:
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. 12) – 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.
You might have already set AWS credentials to work with AWS tools, like one of the AWS SDKs or the
AWS CLI. If you haven't, this topic shows you the recommended approaches for setting AWS credentials.
11
AWS Serverless Application Model Developer Guide
Using the AWS CLI
To set AWS credentials, you must have the access key ID and your secret access key for the IAM user you
want to configure. For information about access key IDs and secret access keys, see Managing Access
Keys for IAM Users in the IAM User Guide.
Next, determine whether you have the AWS CLI installed. Then follow the instructions in one of the
following sections:
$ aws configure
AWS Access Key ID [None]: your_access_key_id
AWS Secret Access Key [None]: your_secret_access_key
Default region name [None]:
Default output format [None]:
For information about the aws configure command, see Quickly Configuring the AWS CLI in the AWS
Command Line Interface User Guide.
• Credentials file – You can set credentials in the AWS credentials file on your local system. This file
must be located in one of the following locations:
• ~/.aws/credentials on Linux or macOS
• C:\Users\USERNAME\.aws\credentials on Windows
[default]
aws_access_key_id = your_access_key_id
aws_secret_access_key = your_secret_access_key
• Environment variables – You can set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY
environment variables.
export AWS_ACCESS_KEY_ID=your_access_key_id
export AWS_SECRET_ACCESS_KEY=your_secret_access_key
set AWS_ACCESS_KEY_ID=your_access_key_id
set AWS_SECRET_ACCESS_KEY=your_secret_access_key
12
AWS Serverless Application Model Developer Guide
Prerequisites
This application implements a basic API backend. It consists of an Amazon API Gateway endpoint and an
AWS 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.
When you initialize your sample application, you have the option to choose a Lambda deployment
package type, either Zip or Image. For more information about package types, see Lambda deployment
packages in the AWS Lambda Developer Guide.
The following is a preview of commands that you run to create your Hello World application. For more
information about each of these commands, see the sections later in this tutorial.
Prerequisites
This guide assumes that you've completed the steps for your operating system in Installing the AWS SAM
CLI (p. 3), including:
13
AWS Serverless Application Model Developer Guide
Step 1: Download a sample AWS SAM application
sam init
Follow the on-screen prompts. For this tutorial, we recommend that you choose AWS Quick Start
Templates, the Zip package type, 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 that you provided as the project name. The contents of
the project directory are similar to the following:
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/
### __init__.py
### test_handler.py
Note
These project directory contents are created when you choose one of the Python runtimes and
the Hello World Example.
• 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.
14
AWS Serverless Application Model Developer Guide
Step 2: Build your application
First, change into the project directory, where the template.yaml file for the sample application is
located. (By default, this directory 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.
Follow the on-screen prompts. To accept the default options provided in the interactive experience,
respond with Enter. If you selected the Image package type when you downloaded your sample
application, you are prompted for an Amazon ECR repository. To deploy your serverless application,
provide a valid Amazon ECR repository URI.
Note
For the prompt HelloWorldFunction may not have authorization defined, Is
this okay? [y/N], AWS SAM is informing you that the sample application configures an API
15
AWS Serverless Application Model Developer Guide
Step 3: Deploy your application to the AWS Cloud
Gateway API without authorization. When you deploy the sample application, AWS SAM creates
a publicly available URL.
You can acknowledge this notification by answering "Y" to the prompt. For information about
configuring authorization, see Controlling access to API Gateway APIs (p. 174).
Example output:
Initiating deployment
=====================
16
AWS Serverless Application Model Developer Guide
Step 3: Deploy your application to the AWS Cloud
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 takes the deployment artifacts that
you build with the sam build command, packages and uploads them to an Amazon Simple Storage
Service (Amazon S3) bucket that the AWS SAM CLI creates, and deploys the application using AWS
CloudFormation. In the output of the sam deploy command, you can see the changes being made to
your AWS CloudFormation stack.
If your application created an HTTP endpoint, the outputs that sam deploy generates 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/
After successfully deploying your application, you see output like the following:
17
AWS Serverless Application Model Developer Guide
Step 4: (Optional) Test your application locally
If you see {"message": "hello world"} after executing the curl command, you've successfully
deployed your serverless application to AWS, and you're calling your live Lambda function. Otherwise,
see the Troubleshooting (p. 20) section later in this tutorial.
Example output:
It can 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:
18
AWS Serverless Application Model Developer Guide
Step 4: (Optional) Test your application locally
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 in locally. 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 the sample
application provides.
Your initialized application comes with a default aws-proxy event for API Gateway. A number of values
are pre-populated 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 substitute in to the request to
simulate what you would expect from an actual request. The 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:
19
AWS Serverless Application Model Developer Guide
Troubleshooting
Troubleshooting
AWS SAM CLI error: "Security Constraints Not Satisfied"
When executing sam deploy --guided, you are prompted with the question HelloWorldFunction
may not have authorization defined, Is this okay? [y/N]. If you respond to this prompt
with "N" (the default response), you see the following error:
The prompt is informing you that the application you're about to deploy may have an API Gateway API
configured without authorization. By responding "N" to this prompt (the default), you are saying that this
is not OK.
• Configure your application with authorization. For information about configuring authorization, see
Controlling access to API Gateway APIs (p. 174).
• Respond to this question with "Y" to indicate that you are OK with deploying an application that has
an API Gateway API configured without authorization.
20
AWS Serverless Application Model Developer Guide
Troubleshooting
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.33.0 or later,
or omit the --app-template parameter from the sam init command.
This means that you are using an older version of the AWS SAM CLI that does not support the --guided
parameter. To fix this, you can either update your version of AWS SAM CLI to 0.33.0 or later, or omit the
--guided parameter from the sam deploy command.
This means that you have not set up AWS credentials to enable the AWS SAM CLI to make AWS
service calls. To fix this, you must set up AWS credentials. For more information, see Setting up AWS
credentials (p. 11).
AWS SAM CLI error: "Running AWS SAM projects locally requires
Docker. Have you got it installed?"
When executing sam local start-api, you see the following error:
Error: Running AWS SAM projects locally requires Docker. Have you got it installed?
This means that you do not have Docker properly installed. Docker is required to test your application
locally. To fix this, follow the instructions for installing Docker for your development host. Go to
Installing the AWS SAM CLI (p. 3), choose the appropriate platform, and then follow the instructions
in the section titled Install Docker.
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.
21
AWS Serverless Application Model Developer Guide
Clean up
curl: (6) Could not resolve: endpointdomain (Domain name not found)
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 deployed successfully by using the AWS CloudFormation console or the AWS CLI,
and verify that your curl command is correct.
Clean up
If you no longer need the AWS resources that 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 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 sam-app (or the name of the stack that you created).
4. Choose Delete.
Alternatively, you can delete the AWS CloudFormation stack by running the following AWS CLI
command:
Conclusion
In this tutorial, you've done the following:
1. Created, built, and deployed a serverless application to AWS using AWS SAM.
2. Tested your application locally 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.
22
AWS Serverless Application Model Developer Guide
Next steps
To help you get started, you can download any of the example applications from the AWS Serverless
Application Repository Examples repository on GitHub.
23
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. 24)
• AWS SAM resource and property reference (p. 30)
• Resource attributes (p. 161)
• Intrinsic functions (p. 162)
• Generated AWS CloudFormation resources (p. 162)
• API Gateway extensions (p. 168)
All other sections of an AWS SAM template file correspond to the AWS CloudFormation template file
section of the same name.
YAML
The following example shows a YAML-formatted template fragment.
24
AWS Serverless Application Model Developer Guide
Template sections
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
AWS SAM templates can include several major sections. Only the Transform and Resources sections
are required.
You can include template sections 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. 26)
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.
Metadata (optional)
25
AWS Serverless Application Model Developer Guide
Next steps
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.
Values that are passed in using the --parameter-overrides parameter of the sam deploy
command—and entries in the configuration file—take precendence over entries in the AWS SAM
template file. For more information about the sam deploy command, see sam deploy (p. 225) in
the AWS SAM CLI command reference. For more information about the configuration file, see AWS
SAM CLI configuration file (p. 243).
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)
The stack resources and their properties, such as an Amazon Elastic Compute Cloud (Amazon EC2)
instance or an Amazon Simple Storage Service (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)
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 Command Line Interface (AWS CLI) command to view the name.
This section corresponds directly with the Outputs section of AWS CloudFormation templates.
Next steps
To download and deploy a sample serverless application that contains an AWS SAM template file, see
Getting started with AWS SAM (p. 3) and follow the instructions in Tutorial: Deploying a Hello World
application (p. 12).
26
AWS Serverless Application Model Developer Guide
Globals
Example:
Globals:
Function:
Runtime: nodejs12.x
Timeout: 180
Handler: index.handler
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 "nodejs12.x" 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:
Handler:
Runtime:
CodeUri:
DeadLetterQueue:
Description:
MemorySize:
Timeout:
VpcConfig:
Environment:
Tags:
Tracing:
KmsKeyArn:
Layers:
AutoPublishAlias:
DeploymentPreference:
PermissionsBoundary:
ReservedConcurrentExecutions:
ProvisionedConcurrencyConfig:
AssumeRolePolicyDocument:
27
AWS Serverless Application Model Developer Guide
Globals
EventInvokeConfig:
Api:
Auth:
Name:
DefinitionUri:
CacheClusterEnabled:
CacheClusterSize:
Variables:
EndpointConfiguration:
MethodSettings:
BinaryMediaTypes:
MinimumCompressionSize:
Cors:
GatewayResponses:
AccessLogSetting:
CanarySetting:
TracingEnabled:
OpenApiVersion:
Domain:
HttpApi:
Auth:
AccessLogSettings:
StageVariables:
Tags:
SimpleTable:
SSESpecification:
Note
Any resources and properties that are not included in the previous list are not supported. Some
reasons for not supporting them include: 1) They open potential security issues, or 2) They make
the template hard to understand.
Implicit APIs
AWS SAM creates implicit APIs when you declare an API in the Events section. You can use Globals to
override all properties of implicit APIs.
Overridable properties
Resources can override the properties that you declare in the Globals section. 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 section.
More generally, the Globals section declares properties that all your resources share. Some resources
can provide new values for globally declared properties, but they can't 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:
28
AWS Serverless Application Model Developer Guide
Globals
Function:
Runtime: nodejs12.x
Resources:
MyFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.6
Map entries in the Resources section are merged with global map entries. If there are duplicates, the
Resource section entry overrides the Globals section 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"
}
List entries in the Globals section are prepended to the list in the Resources section.
Example:
Globals:
Function:
VpcConfig:
SecurityGroupIds:
- sg-123
- sg-456
Resources:
29
AWS Serverless Application Model Developer Guide
Resource and property reference
MyFunction:
Type: AWS::Serverless::Function
Properties:
VpcConfig:
SecurityGroupIds:
- sg-first
Topics
• AWS::Serverless::Api (p. 30)
• AWS::Serverless::Application (p. 61)
• AWS::Serverless::Function (p. 65)
• AWS::Serverless::HttpApi (p. 120)
• AWS::Serverless::LayerVersion (p. 139)
• AWS::Serverless::SimpleTable (p. 142)
• AWS::Serverless::StateMachine (p. 145)
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. 30) 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. 65) resources defined in the template that do not refer to an
AWS::Serverless::Api (p. 30) resource.
An AWS::Serverless::Api (p. 30) 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 Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Type: AWS::Serverless::Api
Properties:
AccessLogSetting: AccessLogSetting
Auth: ApiAuth (p. 38)
BinaryMediaTypes: List
CacheClusterEnabled: Boolean
CacheClusterSize: String
CanarySetting: CanarySetting
Cors: String | CorsConfiguration (p. 55)
30
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
DefinitionBody: String
DefinitionUri: String | ApiDefinition (p. 54)
Description: String
Domain: DomainConfiguration (p. 56)
EndpointConfiguration: EndpointConfiguration (p. 60)
GatewayResponses: Map
MethodSettings: MethodSettings
MinimumCompressionSize: Integer
Models: Map
Name: String
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. 174).
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
31
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Type: String
Required: No
Type: CanarySetting
Required: No
AWS CloudFormation compatibility: This property is passed directly to the CanarySetting property
of an AWS::ApiGateway::Stage resource.
Cors
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
AWS SAM to modify your OpenAPI definition. So, it works only if inline OpenApi is defined with
DefinitionBody.
For more information about CORS, see Enable CORS for an API Gateway REST API Resource in the
API Gateway Developer Guide.
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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.
32
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
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 referenced by DefinitionUri. Use
instead the DefinitionBody property with the Include Transform to import an OpenApi definition
into the template.
Required: No
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Description property of
an AWS::ApiGateway::RestApi resource.
Domain
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
EndpointConfiguration
Required: No
Configures Gateway Responses 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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
MethodSettings
Configures all settings for API stage including Logging, Metrics, CacheTTL, Throttling.
33
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Name
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Name property of an
AWS::ApiGateway::RestApi resource.
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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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).
34
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
To reference the stage resource, use <api-logical-id>.Stage. For more information about
referencing resources generated when an AWS::Serverless::Api (p. 30) resource is specified,
see AWS CloudFormation resources generated when AWS::Serverless::Api is specified (p. 164).
For general information about generated AWS CloudFormation resources, see Generated AWS
CloudFormation resources (p. 162).
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. For more information about X-
Ray, see Tracing user requests to REST APIs using X-Ray in the API Gateway Developer Guide.
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
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Variables property of an
AWS::ApiGateway::Stage resource.
Return Values
Ref
When the logical ID of this resource is provided to the Ref intrinsic function, it returns the ID of the
underlying API Gateway API.
35
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
For more information about using the Ref function, see Ref in the AWS CloudFormation User Guide.
Fn::GetAtt
Fn::GetAtt returns a value for a specified attribute of this type. The following are the available
attributes and sample return values.
For more information about using Fn::GetAtt, see Fn::GetAtt in the AWS CloudFormation User
Guide.
RootResourceId
Examples
SimpleApiExample
A Hello World AWS SAM template file that contains a Lambda Function with an API endpoint. This is a
full AWS SAM template file for a working serverless application.
YAML
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: AWS SAM template with a simple API definition
Resources:
ApiGatewayApi:
Type: AWS::Serverless::Api
Properties:
StageName: prod
ApiFunction: # Adds a GET api endpoint at "/" to the ApiGatewayApi via an Api event
Type: AWS::Serverless::Function
Properties:
Events:
ApiEvent:
Type: Api
Properties:
Path: /
Method: get
RestApiId:
Ref: ApiGatewayApi
Runtime: python3.7
Handler: index.handler
InlineCode: |
def handler(event, context):
return {'body': 'Hello World!', 'statusCode': 200}
ApiCorsExample
An AWS SAM template snippet with an API defined in an external Swagger file along with Lambda
integrations and CORS configurations. This is just a portion of an AWS SAM template file showing an
AWS::Serverless::Api definition.
YAML
Resources:
ApiGatewayApi:
36
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Type: AWS::Serverless::Api
Properties:
StageName: Prod
# Allows www.example.com to call these APIs
# SAM will automatically add AllowMethods with a list of methods for this API
Cors: "'www.example.com'"
DefinitionBody: # Pull in an OpenApi definition from S3
'Fn::Transform':
Name: 'AWS::Include'
# Replace "bucket" with your bucket name
Parameters:
Location: s3://bucket/swagger.yaml
ApiCognitoAuthExample
An AWS SAM template snippet with an API that uses AWS Cognito to authorize requests against the API.
This is just a portion of an AWS SAM template file showing an AWS::Serverless::Api definition.
YAML
Resources:
ApiGatewayApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Cors: "'*'"
Auth:
DefaultAuthorizer: MyCognitoAuthorizer
Authorizers:
MyCognitoAuthorizer:
UserPoolArn:
Fn::GetAtt: [MyCognitoUserPool, Arn]
ApiModelsExample
An AWS SAM template snippet with an API that includes a Models schema. This is just a portion of an
AWS SAM template file, showing an AWS::Serverless::Api definition with two model schemas.
YAML
Resources:
ApiGatewayApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Models:
User:
type: object
required:
- username
- employee_id
properties:
username:
type: string
employee_id:
type: integer
department:
type: string
Item:
type: object
properties:
37
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
count:
type: integer
category:
type: string
price:
type: integer
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. 174).
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AddDefaultAuthorizerToCorsPreflight: Boolean
ApiKeyRequired: Boolean
Authorizers: CognitoAuthorizer (p. 42) | LambdaTokenAuthorizer (p. 48)
| LambdaRequestAuthorizer (p. 45)
DefaultAuthorizer: String
InvokeRole: String
ResourcePolicy: ResourcePolicyStatement (p. 51)
UsagePlan: ApiUsagePlan (p. 40)
Properties
AddDefaultAuthorizerToCorsPreflight
Type: Boolean
Required: No
Default: True
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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.
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
38
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Authorizers
For more information, see Controlling access to API Gateway APIs (p. 174).
Required: No
Default: None
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
InvokeRole
Sets integration credentials for all resources and methods to this value.
Type: String
Required: No
Default: CALLER_CREDENTIALS
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
ResourcePolicy
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
39
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Configures a usage plan associated with this API. For more information about usage plans see Create
and Use Usage Plans with API Keys in the API Gateway Developer Guide.
This AWS SAM property generates three additional AWS CloudFormation resources when this
property is set: an AWS::ApiGateway::UsagePlan, an AWS::ApiGateway::UsagePlanKey, and
an AWS::ApiGateway::ApiKey. For information about this scenario, see UsagePlan property is
specified (p. 165). For general information about generated AWS CloudFormation resources, see
Generated AWS CloudFormation resources (p. 162).
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
CognitoAuth
YAML
Auth:
Authorizers:
MyCognitoAuth:
UserPoolArn:
Fn::GetAtt:
- MyUserPool
- Arn
AuthType: "COGNITO_USER_POOLS"
DefaultAuthorizer: MyCognitoAuth
InvokeRole: CALLER_CREDENTIALS
AddDefaultAuthorizerToCorsPreflight: false
ApiKeyRequired: false
ResourcePolicy:
CustomStatements: [{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/Prod/GET/pets",
"Condition": {
"IpAddress": {
"aws:SourceIp": "1.2.3.4"
}
}
}]
IpRangeBlacklist:
- "10.20.30.40"
ApiUsagePlan
Configures a usage plan for an API Gateway API. For more information about usage plans, see Create and
Use Usage Plans with API Keys in the API Gateway Developer Guide.
40
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
CreateUsagePlan: String
Description: String
Quota: QuotaSettings
Tags: List
Throttle: ThrottleSettings
UsagePlanName: String
Properties
CreateUsagePlan
Determines how this usage plan is configured. Valid values are PER_API, SHARED, and NONE.
NONE disables the creation or association of a usage plan with this API. This is only necessary if
SHARED or PER_API is specified in the Globals section of the AWS SAM template (p. 26).
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Description
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Description property of
an AWS::ApiGateway::UsagePlan resource.
Quota
Configures the number of requests that users can make within a given interval.
Type: QuotaSettings
Required: No
41
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
AWS CloudFormation compatibility: This property is passed directly to the Quota property of an
AWS::ApiGateway::UsagePlan resource.
Tags
An array of arbitrary tags (key-value pairs) to associate with the usage plan.
Type: List
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Tags property of an
AWS::ApiGateway::UsagePlan resource.
Throttle
Configures the overall request rate (average requests per second) and burst capacity.
Type: ThrottleSettings
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Throttle property of an
AWS::ApiGateway::UsagePlan resource.
UsagePlanName
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the UsagePlanName property
of an AWS::ApiGateway::UsagePlan resource.
Examples
UsagePlan
YAML
Auth:
UsagePlan:
CreateUsagePlan: PER_API
Description: Usage plan for this API
Quota:
Limit: 500
Period: MONTH
Throttle:
BurstLimit: 100
RateLimit: 50
Tags:
- Key: TagName
Value: TagValue
CognitoAuthorizer
Define a Amazon Cognito User Pool authorizer.
42
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
For more information and examples, see Controlling access to API Gateway APIs (p. 174).
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AuthorizationScopes: List
Identity: CognitoAuthorizationIdentity (p. 44)
UserPoolArn: String
Properties
AuthorizationScopes
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Identity
This property can be used to specify an IdentitySource in an incoming request for an authorizer
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
CognitoAuth
YAML
Auth:
Authorizers:
MyCognitoAuth:
AuthorizationScopes:
43
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
- scope1
- scope2
UserPoolArn:
Fn::GetAtt:
- MyCognitoUserPool
- Arn
Identity:
Header: MyAuthorizationHeader
ValidationExpression: myauthvalidationexpression
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 Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Header: String
ReauthorizeEvery: Integer
ValidationExpression: String
Properties
Header
Type: String
Required: No
Default: Authorization
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
ValidationExpression
Type: String
44
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
CognitoAuthIdentity
YAML
Identity:
Header: MyCustomAuthHeader
ValidationExpression: Bearer.*
ReauthorizeEvery: 30
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. 174).
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AuthorizationScopes: List
FunctionArn: String
FunctionInvokeRole: String
FunctionPayloadType: String
Identity: LambdaRequestAuthorizationIdentity (p. 46)
Properties
AuthorizationScopes
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
FunctionArn
Specify the function arn of the Lambda function which provides authorization for the API.
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
45
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
FunctionInvokeRole
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Identity
This property can be used to specify an IdentitySource in an incoming request for an authorizer
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
LambdaRequestAuth
YAML
Authorizer:
MyLambdaRequestAuth:
FunctionPayloadType: REQUEST
FunctionArn:
Fn::GetAtt:
- MyAuthFunction
- Arn
FunctionInvokeRole:
Fn::GetAtt:
- LambdaAuthInvokeRole
- Arn
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.
46
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Context: List
Headers: List
QueryStrings: List
ReauthorizeEvery: Integer
StageVariables: List
Properties
Context
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Headers
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
47
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
LambdaRequestIdentity
YAML
Identity:
QueryStrings:
- auth
Headers:
- Authorization
StageVariables:
- VARIABLE
Context:
- authcontext
ReauthorizeEvery: 100
LambdaTokenAuthorizer
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. 174).
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AuthorizationScopes: List
FunctionArn: String
FunctionInvokeRole: String
FunctionPayloadType: String
Identity: LambdaTokenAuthorizationIdentity (p. 50)
Properties
AuthorizationScopes
Type: List
Required: No
48
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
FunctionArn
Specify the function arn of the Lambda function which provides authorization for the API.
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
FunctionInvokeRole
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Identity
This property can be used to specify an IdentitySource in an incoming request for an authorizer.
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
LambdaTokenAuth
YAML
Authorizers:
MyLambdaTokenAuth:
FunctionArn:
Fn::GetAtt:
- MyAuthFunction
49
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
- Arn
Identity:
Header: MyCustomAuthHeader # OPTIONAL; Default: 'Authorization'
ValidationExpression: mycustomauthexpression # OPTIONAL
ReauthorizeEvery: 20 # OPTIONAL; Service Default: 300
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 Serverless Application Model (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
Default: 300
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
ValidationExpression
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
50
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Examples
LambdaTokenIdentity
YAML
Identity:
Header: Auth
ValidationExpression: Bearer.*
ReauthorizeEvery: 30
ResourcePolicyStatement
Configures a resource policy for all methods and paths of an API. For more information about resource
policies, see Controlling access to an API with API Gateway resource policies in the API Gateway Developer
Guide.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AwsAccountBlacklist: List
AwsAccountWhitelist: List
CustomStatements: List
IntrinsicVpcBlacklist: List
IntrinsicVpcWhitelist: List
IntrinsicVpceBlacklist: List
IntrinsicVpceWhitelist: List
IpRangeBlacklist: List
IpRangeWhitelist: List
SourceVpcBlacklist: List
SourceVpcWhitelist: List
Properties
AwsAccountBlacklist
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AwsAccountWhitelist
The AWS accounts to allow. For an example use of this property, see the Examples section at the
bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
51
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
CustomStatements
A list of custom resource policy statements to apply to this API. For an example use of this property,
see the Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpcBlacklist
The list of virtual private clouds (VPCs) to block, where each VPC is specified as a reference such
as a dynamic reference or the Ref intrinsic function. For an example use of this property, see the
Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpcWhitelist
The list of VPCs to allow, where each VPC is specified as a reference such as a dynamic reference or
the Ref intrinsic function.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpceBlacklist
The list of VPC endpoints to block, where each VPC endpoint is specified as a reference such as a
dynamic reference or the Ref intrinsic function.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpceWhitelist
The list of VPC endpoints to allow, where each VPC endpoint is specified as a reference such as
a dynamic reference or the Ref intrinsic function. For an example use of this property, see the
Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IpRangeBlacklist
The IP addresses or address ranges to block. For an example use of this property, see the Examples
section at the bottom of this page.
52
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IpRangeWhitelist
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
SourceVpcBlacklist
The source VPC or VPC endpoints to block. Source VPC names must start with "vpc-" and source
VPC endpoint names must start with "vpce-". For an example use of this property, see the
Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
SourceVpcWhitelist
The source VPC or VPC endpoints to allow. Source VPC names must start with "vpc-" and source
VPC endpoint names must start with "vpce-".
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
The following example blocks two IP addresses and a source VPC, and allows an AWS account.
YAML
Auth:
ResourcePolicy:
CustomStatements: [{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/Prod/GET/pets",
"Condition": {
"IpAddress": {
"aws:SourceIp": "1.2.3.4"
}
}
53
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
}]
IpRangeBlacklist:
- "10.20.30.40"
- "1.2.3.4"
SourceVpcBlacklist:
- "vpce-1a2b3c4d"
AwsAccountWhitelist:
- "111122223333"
IntrinsicVpcBlacklist:
- "{{resolve:ssm:SomeVPCReference:1}}"
- !Ref MyVPC
IntrinsicVpceWhitelist:
- "{{resolve:ssm:SomeVPCEReference:1}}"
- !Ref MyVPCE
ApiDefinition
An OpenAPI document defining the API.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Bucket: String
Key: String
Version: String
Properties
Bucket
The name of the Amazon S3 bucket where the OpenAPI file is stored.
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the Bucket property of the
AWS::ApiGateway::RestApi S3Location data type.
Key
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the Key property of the
AWS::ApiGateway::RestApi S3Location data type.
Version
Type: String
Required: No
54
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
AWS CloudFormation compatibility: This property is passed directly to the Version property of the
AWS::ApiGateway::RestApi S3Location data type.
Examples
Definition Uri example
API Definition example
YAML
DefinitionUri:
Bucket: mybucket-name
Key: mykey-name
Version: 121212
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 only works with inline OpenApi defined in the DefinitionBody property.
For more information about CORS, see Enable CORS for an API Gateway REST API Resource in the API
Gateway Developer Guide.
Note: If CorsConfiguration is set both in OpenAPI and at the property level, AWS SAM merges them, with
the properties taking precedence.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AllowCredentials: Boolean
AllowHeaders: String
AllowMethods: String
AllowOrigin: String
MaxAge: String
Properties
AllowCredentials
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AllowHeaders
Type: String
55
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AllowMethods
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AllowOrigin
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
MaxAge
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
CorsConfiguration
Cors Configuration example. This is just a portion of an AWS SAM template file showing an
AWS::Serverless::Api definition with Cors configured.
YAML
Resources:
ApiGatewayApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
Cors:
AllowMethods: "'POST, GET'"
AllowHeaders: "'X-Forwarded-For'"
AllowOrigin: "'www.example.com'"
MaxAge: "'600'"
AllowCredentials: True
DomainConfiguration
Configures a custom domain for an API.
56
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
BasePath: List
CertificateArn: String
DomainName: String
EndpointConfiguration: String
MutualTlsAuthentication: MutualTlsAuthentication
Route53: Route53Configuration (p. 59)
SecurityPolicy: String
Properties
BasePath
A list of the basepaths to configure with the Amazon API Gateway domain name.
Type: List
Required: No
Default: /
The Amazon Resource Name (ARN) of an AWS managed certificate this domain name's endpoint.
AWS Certificate Manager is the only supported source.
Type: String
Required: Yes
Additional notes: For an EDGE endpoint, you must create the certificate in the us-east-1 AWS
Region.
DomainName
The custom domain name for your API Gateway API. Uppercase letters are not supported.
Type: String
Required: Yes
57
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
AWS CloudFormation compatibility: This property is passed directly to the DomainName property of
an AWS::ApiGateway::DomainName resource.
EndpointConfiguration
Defines the type of API Gateway endpoint to map to the custom domain. The value of this property
determines how the CertificateArn property is mapped in AWS CloudFormation.
Type: String
Required: No
Default: REGIONAL
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
MutualTlsAuthentication
The mutual Transport Layer Security (TLS) authentication configuration for a custom domain name.
Type: MutualTlsAuthentication
Required: No
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
SecurityPolicy
The TLS version plus cipher suite for this domain name.
Type: String
Required: No
Examples
DomainName
DomainName example
YAML
Domain:
DomainName: www.example.com
CertificateArn: arn-example
EndpointConfiguration: EDGE
58
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Route53:
HostedZoneId: Z1PA6795UKMFR9
BasePath:
- /foo
- /bar
Route53Configuration
Configures the Route53 record sets for an API.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
DistributionDomainName: String
EvaluateTargetHealth: Boolean
HostedZoneId: String
HostedZoneName: String
IpV6: Boolean
Properties
DistributionDomainName
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the DNSName property of an
AWS::Route53::RecordSetGroup AliasTarget resource.
When EvaluateTargetHealth is true, an alias record inherits the health of the referenced AWS
resource, such as an Elastic Load Balancing load balancer or another record in the hosted zone.
Type: Boolean
Required: No
Additional notes: You can't set EvaluateTargetHealth to true when the alias target is a CloudFront
distribution.
HostedZoneId
The ID of the hosted zone that you want to create records in.
Specify either HostedZoneName or HostedZoneId, but not both. If you have multiple hosted zones
with the same domain name, you must specify the hosted zone using HostedZoneId.
Type: String
59
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
Required: No
AWS CloudFormation compatibility: This property is passed directly to the HostedZoneId property
of an AWS::Route53::RecordSetGroup RecordSet resource.
HostedZoneName
The name of the hosted zone that you want to create records in.
Specify either HostedZoneName or HostedZoneId, but not both. If you have multiple hosted zones
with the same domain name, you must specify the hosted zone using HostedZoneId.
Type: String
Required: No
When this property is set, AWS SAM creates a AWS::Route53::RecordSet resource and sets Type
to AAAA for the provided HostedZone.
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
YAML
Domain:
DomainName: www.example.com
CertificateArn: arn-example
EndpointConfiguration: EDGE
Route53:
HostedZoneId: Z1PA6795UKMFR9
EvaluateTargetHealth: true
DistributionDomainName: xyz
EndpointConfiguration
The endpoint type of a REST API.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Type: String
VPCEndpointIds: List
60
AWS Serverless Application Model Developer Guide
AWS::Serverless::Application
Properties
Type
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Types property of the
AWS::ApiGateway::RestApi EndpointConfiguration data type.
VPCEndpointIds
A list of VPC endpoint IDs of a REST API against which to create Route53 aliases.
Type: List
Required: No
Examples
EndpointConfiguration
YAML
EndpointConfiguration:
Type: EDGE
VPCEndpointIds:
- vpce-123a123a
- vpce-321a321a
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. 61) resources.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Type: AWS::Serverless::Application
Properties:
Location: String | ApplicationLocationObject (p. 64)
NotificationARNs: List
61
AWS Serverless Application Model Developer Guide
AWS::Serverless::Application
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. 64) 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
Type: Map
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Parameters property of
an AWS::CloudFormation::Stack resource.
Tags
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
62
AWS Serverless Application Model Developer Guide
AWS::Serverless::Application
if this application is from the AWS Serverless Application Repository, then SAM will also
automatically the two additional tags serverlessrepo:applicationId:ApplicationId and
serverlessrepo:semanticVersion:SemanticVersion.
TimeoutInMinutes
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 in the AWS CloudFormation User Guide.
Fn::GetAtt
Fn::GetAtt returns a value for a specified attribute of this type. The following are the available
attributes and sample return values.
For more information about using Fn::GetAtt, see Fn::GetAtt in the AWS CloudFormation User
Guide.
Outputs.ApplicationOutputName
Examples
SAR Application
Application that uses a template from the Serverless Application Repository
YAML
Type: AWS::Serverless::Application
Properties:
Location:
ApplicationId: 'arn:aws:serverlessrepo:us-east-1:012345678901:applications/my-
application'
SemanticVersion: 1.0.0
Parameters:
StringParameter: parameter-value
IntegerParameter: 2
63
AWS Serverless Application Model Developer Guide
AWS::Serverless::Application
Normal-Application
Application from an S3 url
YAML
Type: AWS::Serverless::Application
Properties:
Location: https://s3.amazonaws.com/demo-bucket/template.yaml
ApplicationLocationObject
An application that has been published to the AWS Serverless Application Repository.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
ApplicationId: String
SemanticVersion: String
Properties
ApplicationId
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
SemanticVersion
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
my-application
Example application location object
YAML
Location:
ApplicationId: 'arn:aws:serverlessrepo:us-east-1:012345678901:applications/my-
application'
64
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
SemanticVersion: 1.0.0
AWS::Serverless::Function
Creates an AWS Lambda function, an AWS Identity and Access Management (IAM) execution role, and
event source mappings that trigger the function.
The AWS::Serverless::Function (p. 65) resource also supports the Metadata resource attribute, so you
can instruct AWS SAM to build custom runtimes that your application requires. For more information
about building custom runtimes, see Building custom runtimes (p. 189).
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Type: AWS::Serverless::Function
Properties:
AssumeRolePolicyDocument: JSON
AutoPublishAlias: String
AutoPublishCodeSha256: String
CodeSigningConfigArn: String
CodeUri: String | FunctionCode (p. 119)
DeadLetterQueue: Map | DeadLetterQueue (p. 74)
DeploymentPreference: DeploymentPreference (p. 75)
Description: String
Environment: Environment
EventInvokeConfig: EventInvokeConfiguration (p. 78)
Events: EventSource (p. 83)
FileSystemConfigs: List
FunctionName: String
Handler: String
ImageConfig: ImageConfig
ImageUri: String
InlineCode: String
KmsKeyArn: String
Layers: List
MemorySize: Integer
PackageType: String
PermissionsBoundary: String
Policies: String | List | Map
ProvisionedConcurrencyConfig: ProvisionedConcurrencyConfig
ReservedConcurrentExecutions: Integer
Role: String
Runtime: String
Tags: Map
Timeout: Integer
Tracing: String
VersionDescription: String
VpcConfig: VpcConfig
Properties
AssumeRolePolicyDocument
Adds an AssumeRolePolicyDocument for the default created Role for this function. If this property
isn't specified, AWS SAM adds a default assume role for this function.
65
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: JSON
Required: No
The name of the Lambda alias. For more information about Lambda aliases, see Lambda function
aliases in the AWS Lambda Developer Guide. For examples that use this property, see Deploying
serverless applications gradually (p. 206).
AWS SAM generates AWS::Lambda::Version and AWS::Lambda::Alias resources when this property
is set. For information about this scenario, see AutoPublishAlias property is specified (p. 166).
For general information about generated AWS CloudFormation resources, see Generated AWS
CloudFormation resources (p. 162).
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AutoPublishCodeSha256
The string value that is used, along with the value in CodeUri, to determine whether a new Lambda
version should be published.
This property addresses a problem that occurs when an AWS SAM template has the following
characteristics: the DeploymentPreference object is configured for gradual deployments (as
described in Deploying serverless applications gradually (p. 206)), the AutoPublishAlias
property is set and doesn't change between deployments, and the CodeUri property is set and
doesn't change between deployments.
This scenario can occur when the deployment package stored in an Amazon Simple Storage Service
(Amazon S3) location is replaced by a new deployment package that contains updated Lambda
function code, but the CodeUri property remains unchanged (as opposed to the new deployment
package being uploaded to a new Amazon S3 location and the CodeUri being changed to the new
location).
In this scenario, to trigger the gradual deployment successfully, you must provide a unique value for
AutoPublishCodeSha256.
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
CodeSigningConfigArn
The ARN of the AWS::Lambda::CodeSigningConfig resource, used to enable code signing for this
function. For more information about code signing, see Configuring code signing for AWS SAM
applications (p. 183).
Type: String
66
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required: No
The function code's Amazon S3 URI, local file path, or FunctionCode (p. 119) object.
If an Amazon S3 URI or FunctionCode (p. 119) object is provided, the Amazon S3 object referenced
must be a valid Lambda deployment package.
If a local file path is provided, for the code to be transformed properly the template must go
through the workflow that includes the sam deploy or sam package command.
Required: Conditional
Configures an Amazon Simple Notification Service (Amazon SNS) topic or Amazon Simple Queue
Service (Amazon 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 in the AWS
Lambda Developer Guide.
Required: No
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
See also: For more information about this property, see Deploying serverless applications
gradually (p. 206).
Description
Type: String
67
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Description property of
an AWS::Lambda::Function resource.
Environment
Type: Environment
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Environment property of
an AWS::Lambda::Function resource.
EventInvokeConfig
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Events
Specifies the events that trigger this function. Events consist of a type and a set of properties that
depend on the type.
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
FileSystemConfigs
List of FileSystemConfig objects that specify the connection settings for an Amazon Elastic File
System (Amazon EFS) file system.
If your template contains an AWS::EFS::MountTarget resource, you must also specify a DependsOn
resource attribute to ensure that the mount target is created or updated before the function.
Type: List
Required: No
A name for the function. If you don't specify a name, a unique name is generated for you.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the FunctionName property
of an AWS::Lambda::Function resource.
68
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Handler
The function within your code that is called to begin execution. This property is only required if the
PackageType property is set to Zip.
Type: String
Required: Conditional
AWS CloudFormation compatibility: This property is passed directly to the Handler property of an
AWS::Lambda::Function resource.
ImageConfig
The object used to configure Lambda container image settings. For more information, see Using
container images with Lambda in the AWS Lambda Developer Guide.
Type: ImageConfig
Required: No
AWS CloudFormation compatibility: This property is passed directly to the ImageConfig property of
an AWS::Lambda::Function resource.
ImageUri
The URI of the Amazon Elastic Container Registry (Amazon ECR) repository for the Lambda
function's container image. For more information, see Using container images with Lambda in the
AWS Lambda Developer Guide.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the ImageUri property of the
AWS::Lambda::Function Code data type.
InlineCode
Type: String
Required: Conditional
AWS CloudFormation compatibility: This property is passed directly to the ZipFile property of the
AWS::Lambda::Function Code data type.
KmsKeyArn
The 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
AWS CloudFormation compatibility: This property is passed directly to the KmsKeyArn property of an
AWS::Lambda::Function resource.
Layers
The list of LayerVersion ARNs that this function should use. The order specified here is the order
in which they will be imported when running the Lambda function.
69
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: List
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Layers property of an
AWS::Lambda::Function resource.
MemorySize
Type: Integer
Required: No
AWS CloudFormation compatibility: This property is passed directly to the MemorySize property of
an AWS::Lambda::Function resource.
PackageType
The deployment package type of the Lambda function. For more information, see Lambda
deployment packages in the AWS Lambda Developer Guide.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the PackageType property of
an AWS::Lambda::Function resource.
PermissionsBoundary
The ARN of a permissions boundary to use for this function's execution role. This property works
only if the role is generated for you.
Type: String
Required: No
One or more policies that this function needs. They 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
policies or AWS SAM policy templates, or inline IAM policy documents formatted in YAML.
For more information about AWS managed policies, see AWS managed policies in the IAM
User Guide. For more information about AWS SAM policy templates, see AWS SAM policy
templates (p. 245) in the AWS Serverless Application Model Developer Guide. For more
information about inline policies, see Inline policies in the IAM User Guide.
Required: No
70
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
templates, in addition to JSON policy documents. AWS CloudFormation accepts only JSON policy
documents.
ProvisionedConcurrencyConfig
Type: ProvisionedConcurrencyConfig
Required: No
The maximum number of concurrent executions that 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
The identifier of the function's runtime. This property is only required if the PackageType property
is set to Zip.
Note: If you specify the provided identifier for this property, you can use the Metadata resource
attribute to instruct AWS SAM to build the custom runtime that this function requires. For more
information about building custom runtimes, see Building custom runtimes (p. 189).
Type: String
Required: Conditional
AWS CloudFormation compatibility: This property is passed directly to the Runtime property of an
AWS::Lambda::Function resource.
Tags
A map (string to string) that specifies the tags added to the Lambda function and the corresponding
execution role. Keys and values are limited to alphanumeric characters. Keys can be 1 to 127 Unicode
71
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
characters in length and cannot be prefixed with aws:. Values can be 1 to 255 Unicode characters in
length.
Type: Map
Required: No
The maximum time in seconds that the function can run before it is stopped.
Type: Integer
Required: No
Default: 3
AWS CloudFormation compatibility: This property is passed directly to the Timeout property of an
AWS::Lambda::Function resource.
Tracing
The string that specifies the function's X-Ray tracing mode. For more information about X-Ray, see
Using AWS Lambda with AWS X-Ray in the AWS Lambda Developer Guide.
Type: String
Required: No
Specifies the Description field that is added on the new Lambda version resource.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Description property of
an AWS::Lambda::Version resource.
VpcConfig
The configuration that enables this function to access private resources within your virtual private
cloud (VPC).
Type: VpcConfig
Required: No
AWS CloudFormation compatibility: This property is passed directly to the VpcConfig property of an
AWS::Lambda::Function resource.
72
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 in the AWS CloudFormation User Guide.
Fn::GetAtt
Fn::GetAtt returns a value for a specified attribute of this type. The following are the available
attributes and sample return values.
For more information about using Fn::GetAtt, see Fn::GetAtt in the AWS CloudFormation User
Guide.
Arn
Examples
Simple function
The following is a basic example of an AWS::Serverless::Function (p. 65) resource.
YAML
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: python3.6
CodeUri: s3://bucket/key
YAML
Type: AWS::Serverless::Function
DependsOn: MyMountTarget # This is needed if an AWS::EFS::MountTarget resource is
declared for EFS
Properties:
Handler: index.handler
Runtime: python3.6
InlineCode: |
def handler(event, context):
print("Hello, world!")
ReservedConcurrentExecutions: 30
Layers:
- Ref: MyLayer
Tracing: Active
Timeout: 120
FileSystemConfigs:
- Arn: !Ref MyEfsFileSystem
73
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
LocalMountPath: /mnt/EFS
Policies:
- AWSLambdaExecute
- Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- s3:GetObject
- s3:GetObjectACL
Resource: 'arn:aws:s3:::my-bucket/*'
Events:
ApiEvent:
Type: Api
Properties:
Path: /path
Method: get
ImageConfig example
The following is an example of an ImageConfig for a Lambda function of package type Image.
YAML
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
PackageType: Image
ImageConfig:
Command:
- "app.lambda_handler"
EntryPoint:
- "entrypoint1"
WorkingDirectory: "workDir"
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 Serverless Application Model (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.
74
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the TargetArn property of
the AWS::Lambda::Function DeadLetterConfig data type.
Type
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
DeadLetterQueue
YAML
DeadLetterQueue:
Type: SNS
TargetArn: arn:aws:sns:us-east-2:123456789012:my-topic
DeploymentPreference
Specifies the configurations to enable gradual Lambda deployments. For more information about
configuring gradual Lambda deployments, see Deploying serverless applications gradually (p. 206).
Note: You must specify an AutoPublishAlias in your AWS::Serverless::Function (p. 65) to use a
DeploymentPreference object, otherwise an error will result.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Alarms: List
Enabled: Boolean
Hooks: Hooks (p. 77)
Role: String
TriggerConfigurations: List
Type: String
Properties
Alarms
A list of CloudWatch alarms that you want to be triggered by any errors raised by the deployment.
75
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Enabled
Type: Boolean
Required: No
Default: True
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Hooks
Validation Lambda functions that are run before and after traffic shifting.
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
TriggerConfigurations
A list of trigger configurations you want to associate with the deployment group. Used to notify an
SNS topic on lifecycle events.
Type: List
Required: No
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. 206).
Type: String
Required: Yes
76
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
DeploymentPreference
YAML
DeploymentPreference:
Enabled: True
Type: Canary10Percent10Minutes
Alarms:
- Ref: AliasErrorMetricGreaterThanZeroAlarm
- Ref: LatestVersionErrorMetricGreaterThanZeroAlarm
Hooks:
PreTraffic:
Ref: PreTrafficLambdaFunction
PostTraffic:
Ref: PostTrafficLambdaFunction
Hooks
Validation Lambda functions that are run before and after traffic shifting.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
PostTraffic: String
PreTraffic: String
Properties
PostTraffic
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
PreTraffic
Type: String
77
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
Hooks
YAML
Hooks:
PreTraffic:
Ref: PreTrafficLambdaFunction
PostTraffic:
Ref: PostTrafficLambdaFunction
EventInvokeConfiguration
Configuration options for asynchronous Lambda Alias or Version invocations.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Properties
DestinationConfig
A configuration object that specifies the destination of an event after Lambda processes it.
Required: No
The maximum age of a request that Lambda sends to a function for processing.
Type: Integer
Required: No
78
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
MaximumRetryAttempts
The maximum number of times to retry before the function returns an error.
Type: Integer
Required: No
Examples
MaximumEventAgeInSeconds
MaximumEventAgeInSeconds example
YAML
EventInvokeConfig:
MaximumEventAgeInSeconds: 60
MaximumRetryAttempts: 2
DestinationConfig:
OnSuccess:
Type: SQS
Destination: arn:aws:sqs:us-west-2:012345678901:my-queue
OnFailure:
Type: Lambda
Destination: !GetAtt DestinationLambda.Arn
EventInvokeDestinationConfiguration
A configuration object that specifies the destination of an event after Lambda processes it.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Properties
OnFailure
Required: No
79
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required: No
Examples
OnSuccess
OnSuccess example
YAML
EventInvokeConfig:
DestinationConfig:
OnSuccess:
Type: SQS
Destination: arn:aws:sqs:us-west-2:012345678901:my-queue
OnFailure:
Type: Lambda
Destination: !GetAtt DestinationLambda.Arn
OnFailure
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Destination: String
Type: String
Properties
Destination
Type: String
Required: Conditional
Type of the resource referenced in the destination. Supported types are SQS, SNS, Lambda, and
EventBridge.
80
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Additional notes: If the type is SQS/SNS and the Destination property is left blank, then the SQS/
SNS resource is auto generated by SAM. To reference the resource, use <function-logical-
id>.DestinationQueue for SQS or <function-logical-id>.DestinationTopic for SNS. If
the type is Lambda/EventBridge, Destination is required.
Examples
In this example no Destination is given for the SQS OnSuccess configuration, so SAM implicitly creates
a SQS queue and adds any necessary permissions. Also for this example, a Destination for a Lambda
resource declared in the template file is specified in the OnFailure configuration, so SAM adds the
necessary permissions to this Lambda function to call the destination Lambda function.
YAML
EventInvokeConfig:
DestinationConfig:
OnSuccess:
Type: SQS
OnFailure:
Type: Lambda
Destination: !GetAtt DestinationLambda.Arn # Arn of a Lambda function declared in
the template file.
In this example a Destination is given for an SNS topic declared in the template file for the OnSuccess
configuration.
YAML
EventInvokeConfig:
DestinationConfig:
OnSuccess:
Type: SNS
Destination:
Ref: DestinationSNS # Arn of an SNS topic declared in the tempate file
OnSuccess
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Destination: String
81
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: String
Properties
Destination
Type: String
Required: Conditional
Type of the resource referenced in the destination. Supported types are SQS, SNS, Lambda, and
EventBridge.
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Additional notes: If the type is SQS/SNS and the Destination property is left blank, then the SQS/
SNS resource is auto generated by SAM. To reference the resource, use <function-logical-
id>.DestinationQueue for SQS or <function-logical-id>.DestinationTopic for SNS. If
the type is Lambda/EventBridge, Destination is required.
Examples
In this example no Destination is given for the SQS OnSuccess configuration, so SAM implicitly creates
a SQS queue and adds any necessary permissions. Also for this example, a Destination for a Lambda
resource declared in the template file is specified in the OnFailure configuration, so SAM adds the
necessary permissions to this Lambda function to call the destination Lambda function.
YAML
EventInvokeConfig:
DestinationConfig:
OnSuccess:
Type: SQS
OnFailure:
Type: Lambda
Destination: !GetAtt DestinationLambda.Arn # Arn of a Lambda function declared in
the template file.
In this example a Destination is given for an SNS topic declared in the template file for the OnSuccess
configuration.
82
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
YAML
EventInvokeConfig:
DestinationConfig:
OnSuccess:
Type: SNS
Destination:
Ref: DestinationSNS # Arn of an SNS topic declared in the tempate file
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 Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Properties: S3 (p. 112) | SNS (p. 114) | Kinesis (p. 106) | DynamoDB (p. 96)
| SQS (p. 117) | Api (p. 84) | Schedule (p. 113) | CloudWatchEvent (p. 93)
| EventBridgeRule (p. 99) | CloudWatchLogs (p. 94) | IoTRule (p. 105)
| AlexaSkill (p. 84) | Cognito (p. 95) | HttpApi (p. 101) | MSK (p. 110) | MQ (p. 108)
Type: String
Properties
Properties
Object describing properties of this event mapping. The set of properties must conform to the
defined Type.
Type: S3 (p. 112) | SNS (p. 114) | Kinesis (p. 106) | DynamoDB (p. 96) | SQS (p. 117) |
Api (p. 84) | Schedule (p. 113) | CloudWatchEvent (p. 93) | EventBridgeRule (p. 99)
| CloudWatchLogs (p. 94) | IoTRule (p. 105) | AlexaSkill (p. 84) | Cognito (p. 95) |
HttpApi (p. 101) | MSK (p. 110) | MQ (p. 108)
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Type
Valid values: S3, SNS, Kinesis, DynamoDB, SQS, Api, Schedule, CloudWatchEvent,
CloudWatchLogs, IoTRule, AlexaSkill, Cognito, EventBridgeRule, HttpApi, MSK, MQ
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
83
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Examples
APIEvent
Example of using an API event
YAML
ApiEvent:
Type: Api
Properties:
Method: get
Path: /group/{user}
RestApiId:
Ref: MyApi
AlexaSkill
The object describing an AlexaSkill event source type.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
SkillId: String
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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
AlexaSkillTrigger
Alexa Skill Event Example
YAML
AlexaSkillEvent:
Type: AlexaSkill
Api
The object describing an Api event source type. If an AWS::Serverless::Api (p. 30) resource is defined,
the path and method values must correspond to an operation in the OpenAPI definition of the API.
84
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
If no AWS::Serverless::Api (p. 30) 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 Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Properties
Auth
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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Method
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Path
Uri path for which this function is invoked. Must start with /.
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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. 30) resource.
85
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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. 30) resource defined in this template.
If you don't define this property, AWS SAM creates a default AWS::Serverless::Api (p. 30) resource
using a generated OpenApi document. That resource contains a union of all paths and methods
defined by Api events in the same template that do not specify a RestApiId.
This cannot reference an AWS::Serverless::Api (p. 30) resource defined in another template.
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
ApiEvent
YAML
Events:
ApiEvent:
Type: Api
Properties:
Path: /path
Method: get
RequestParameters:
- method.request.header.Authorization
ApiFunctionAuth
Configures authorization at the event level, for a specific API, path, and method.
86
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
ApiKeyRequired: Boolean
AuthorizationScopes: List
Authorizer: String
InvokeRole: String
ResourcePolicy: ResourcePolicyStatement (p. 88)
Properties
ApiKeyRequired
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AuthorizationScopes
The scopes that you specify will override any scopes applied by the DefaultAuthorizer property
if you have specified it.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
InvokeRole
Type: String
Required: No
Default: CALLER_CREDENTIALS
87
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
Function-Auth
YAML
Auth:
ApiKeyRequired: true
Authorizer: NONE
ResourcePolicyStatement
Configures a resource policy for all methods and paths of an API. For more information about resource
policies, see Controlling access to an API with API Gateway resource policies in the API Gateway Developer
Guide.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AwsAccountBlacklist: List
AwsAccountWhitelist: List
CustomStatements: List
IntrinsicVpcBlacklist: List
IntrinsicVpcWhitelist: List
IntrinsicVpceBlacklist: List
IntrinsicVpceWhitelist: List
IpRangeBlacklist: List
IpRangeWhitelist: List
SourceVpcBlacklist: List
SourceVpcWhitelist: List
Properties
AwsAccountBlacklist
88
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AwsAccountWhitelist
The AWS accounts to allow. For an example use of this property, see the Examples section at the
bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
CustomStatements
A list of custom resource policy statements to apply to this API. For an example use of this property,
see the Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpcBlacklist
The list of virtual private clouds (VPCs) to block, where each VPC is specified as a reference such
as a dynamic reference or the Ref intrinsic function. For an example use of this property, see the
Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpcWhitelist
The list of VPCs to allow, where each VPC is specified as a reference such as a dynamic reference or
the Ref intrinsic function.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpceBlacklist
The list of VPC endpoints to block, where each VPC endpoint is specified as a reference such as a
dynamic reference or the Ref intrinsic function.
Type: List
Required: No
89
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpceWhitelist
The list of VPC endpoints to allow, where each VPC endpoint is specified as a reference such as
a dynamic reference or the Ref intrinsic function. For an example use of this property, see the
Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IpRangeBlacklist
The IP addresses or address ranges to block. For an example use of this property, see the Examples
section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IpRangeWhitelist
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
SourceVpcBlacklist
The source VPC or VPC endpoints to block. Source VPC names must start with "vpc-" and source
VPC endpoint names must start with "vpce-". For an example use of this property, see the
Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
SourceVpcWhitelist
The source VPC or VPC endpoints to allow. Source VPC names must start with "vpc-" and source
VPC endpoint names must start with "vpce-".
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
90
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Examples
The following example blocks two IP addresses and a source VPC, and allows an AWS account.
YAML
Auth:
ResourcePolicy:
CustomStatements: [{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/Prod/GET/pets",
"Condition": {
"IpAddress": {
"aws:SourceIp": "1.2.3.4"
}
}
}]
IpRangeBlacklist:
- "10.20.30.40"
- "1.2.3.4"
SourceVpcBlacklist:
- "vpce-1a2b3c4d"
AwsAccountWhitelist:
- "111122223333"
IntrinsicVpcBlacklist:
- "{{resolve:ssm:SomeVPCReference:1}}"
- !Ref MyVPC
IntrinsicVpceWhitelist:
- "{{resolve:ssm:SomeVPCEReference:1}}"
- !Ref MyVPCE
RequestModel
Syntax
To declare this entity in your AWS Serverless Application Model (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. 30).
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
91
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required
adds a required property in the parameters section of OpenApi definition for given API endpoint
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
Request Model
YAML
RequestModel:
Model: User
Required: true
RequestParameter
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Caching: Boolean
Required: Boolean
Properties
Caching
Type: Boolean
Required: Conditional
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Required
Type: Boolean
Required: Conditional
92
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
Request Parameter
Example of setting Request Parameters
YAML
RequestParameters:
- method.request.header.Authorization:
Required: true
Caching: true
CloudWatchEvent
The object describing a CloudWatchEvent event source type.
AWS Serverless Application Model (AWS SAM) generates an AWS::Events::Rule resource when this event
type is set.
Important Note: EventBridgeRule (p. 99) is the preferred event source type to use, instead of
CloudWatchEvent. EventBridgeRule and CloudWatchEvent use the same underlying service,
API, and AWS CloudFormation resources. However, AWS SAM will add support for new features only to
EventBridgeRule.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
EventBusName: String
Input: String
InputPath: String
Pattern: EventPattern
Properties
EventBusName
The event bus to associate with this rule. If you omit this property, AWS SAM uses the default event
bus.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the EventBusName property
of an AWS::Events::Rule resource.
Input
Valid JSON text passed to the target. If you use this property, nothing from the event text itself is
passed to the target.
93
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Input property of an
AWS::Events::Rule Target resource.
InputPath
When you don't want to pass the entire matched event to the target, use the InputPath property
to describe which part of the event to pass.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the InputPath property of an
AWS::Events::Rule Target resource.
Pattern
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
AWS CloudFormation compatibility: This property is passed directly to the EventPattern property
of an AWS::Events::Rule resource.
Examples
CloudWatchEvent
YAML
CWEvent:
Type: CloudWatchEvent
Properties:
Input: '{"Key": "Value"}'
Pattern:
detail:
state:
- terminated
CloudWatchLogs
The object describing a CloudWatchLogs event source type.
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 Serverless Application Model (AWS SAM) template, use the following
syntax.
94
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
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
AWS CloudFormation compatibility: This property is passed directly to the FilterPattern property
of an AWS::Logs::SubscriptionFilter resource.
LogGroupName
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
AWS CloudFormation compatibility: This property is passed directly to the LogGroupName property
of an AWS::Logs::SubscriptionFilter resource.
Examples
YAML
CWLog:
Type: CloudWatchLogs
Properties:
LogGroupName:
Ref: CloudWatchLambdaLogsGroup
FilterPattern: My pattern
Cognito
The object describing a Cognito event source type.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Trigger: List
95
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
UserPool: String
Properties
Trigger
The Lambda trigger configuration information for the new user pool.
Type: List
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the LambdaConfig property
of an AWS::Cognito::UserPool resource.
UserPool
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
Cognito Event
YAML
CognitoUserPoolPreSignup:
Type: Cognito
Properties:
UserPool:
Ref: MyCognitoUserPool
Trigger: PreSignUp
DynamoDB
The object describing a DynamoDB event source type. For more information, see Using AWS Lambda with
Amazon DynamoDB in the AWS Lambda Developer Guide.
AWS SAM generates an AWS::Lambda::EventSourceMapping resource when this event type is set.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
BatchSize: Integer
BisectBatchOnFunctionError: Boolean
DestinationConfig: DestinationConfig
Enabled: Boolean
MaximumBatchingWindowInSeconds: Integer
96
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
MaximumRecordAgeInSeconds: Integer
MaximumRetryAttempts: Integer
ParallelizationFactor: Integer
StartingPosition: String
Stream: String
TumblingWindowInSeconds: Integer
Properties
BatchSize
Type: Integer
Required: No
Default: 100
AWS CloudFormation compatibility: This property is passed directly to the BatchSize property of an
AWS::Lambda::EventSourceMapping resource.
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.
Type: DestinationConfig
Required: No
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Enabled property of an
AWS::Lambda::EventSourceMapping resource.
MaximumBatchingWindowInSeconds
The maximum amount of time to gather records before invoking the function, in seconds.
Type: Integer
97
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
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
Type: String
Required: Yes
Type: String
Required: Yes
The duration, in seconds, of a processing window. The valid range is 1 to 900 (15 minutes).
98
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
For more information, see Tumbling windows in the AWS Lambda Developer Guide.
Type: Integer
Required: No
Examples
YAML
Events:
DDBEvent:
Type: DynamoDB
Properties:
Stream: arn:aws:dynamodb:us-east-1:123456789012:table/TestTable/
stream/2016-08-11T21:21:33.291
StartingPosition: TRIM_HORIZON
BatchSize: 10
Enabled: false
YAML
Events:
DDBEvent:
Type: DynamoDB
Properties:
Stream:
!GetAtt MyDynamoDBTable.StreamArn # This must be the name of a DynamoDB table
declared in the same template file
StartingPosition: TRIM_HORIZON
BatchSize: 10
Enabled: false
EventBridgeRule
The object describing an EventBridgeRule event source type.
AWS Serverless Application Model (AWS SAM) generates an AWS::Events::Rule resource when this event
type is set.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
EventBusName: String
99
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Input: String
InputPath: String
Pattern: EventPattern
TargetId: String
Properties
EventBusName
The event bus to associate with this rule. If you omit this property, AWS SAM uses the default event
bus.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the EventBusName property
of an AWS::Events::Rule resource.
Input
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
AWS CloudFormation compatibility: This property is passed directly to the Input property of an
AWS::Events::Rule Target resource.
InputPath
When you don't want to pass the entire matched event to the target, use the InputPath property
to describe which part of the event to pass.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the InputPath property of an
AWS::Events::Rule Target resource.
Pattern
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
AWS CloudFormation compatibility: This property is passed directly to the EventPattern property
of an AWS::Events::Rule resource.
TargetId
A name for the events rule target that EventBridge invokes when a rule is triggered. The TargetId
can include alphanumeric characters, periods (.), hyphens (-), and underscores (_).
If this property is not specified, AWS SAM will generate a TargetId value.
100
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Id property of the
AWS::Events::Rule Target data type.
Examples
EventBridgeRule
YAML
EBRule:
Type: EventBridgeRule
Properties:
Input: '{"Key": "Value"}'
Pattern:
detail:
state:
- terminated
HttpApi
The object describing an event source with type HttpApi.
If an OpenApi definition for the specified path and method exists on the API, SAM will add the Lambda
integration and security section (if applicable) for you.
If no OpenApi definition for the specified path and method exists on the API, SAM will create this
definition for you.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
ApiId: String
Auth: HttpApiFunctionAuth (p. 104)
Method: String
Path: String
PayloadFormatVersion: String
RouteSettings: RouteSettings
TimeoutInMillis: Integer
Properties
ApiId
101
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
This cannot reference an AWS::Serverless::HttpApi (p. 120) resource defined in another template.
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Auth
Useful for overriding the API's DefaultAuthorizer or setting auth config on an individual path
when no DefaultAuthorizer is specified.
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Method
If no Path and Method are specified, SAM will create a default API path that routes any request that
doesn't map to a different endpoint to this Lambda function. Only one of these default paths can
exist per API.
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Path
Uri path for which this function is invoked. Must start with /.
If no Path and Method are specified, SAM will create a default API path that routes any request that
doesn't map to a different endpoint to this Lambda function. Only one of these default paths can
exist per API.
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
PayloadFormatVersion
NOTE: PayloadFormatVersion requires SAM to modify your OpenAPI definition, so it only works with
inline OpenApi defined in the DefinitionBody property.
Type: String
Required: No
102
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Default: 2.0
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
RouteSettings
The per-route route settings for this HTTP API. For more information about route settings, see
AWS::ApiGatewayV2::Stage RouteSettings in the API Gateway Developer Guide.
Note: If RouteSettings are specified in both the HttpApi resource and event source, AWS SAM merges
them with the event source properties taking precedence.
Type: RouteSettings
Required: No
AWS CloudFormation compatibility: This property is passed directly to the RouteSettings property
of an AWS::ApiGatewayV2::Stage resource.
TimeoutInMillis
NOTE: TimeoutInMillis requires SAM to modify your OpenAPI definition, so it only works with inline
OpenApi defined in the DefinitionBody property.
Type: Integer
Required: No
Default: 5000
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
HttpApi Event that uses the default path. All unmapped paths and methods on this API will route to this
endpoint.
YAML
Events:
HttpApiEvent:
Type: HttpApi
HttpApi
YAML
Events:
HttpApiEvent:
Type: HttpApi
Properties:
Path: /
103
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Method: GET
HttpApi Authorization
YAML
Events:
HttpApiEvent:
Type: HttpApi
Properties:
Path: /authenticated
Method: GET
Auth:
Authorizer: OpenIdAuth
AuthorizationScopes:
- scope1
- scope2
HttpApiFunctionAuth
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AuthorizationScopes: List
Authorizer: String
Properties
AuthorizationScopes
Scopes listed here will override any scopes applied by the DefaultAuthorizer if one exists.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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
104
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
Function-Auth
YAML
Auth:
Authorizer: OpenIdAuth
AuthorizationScopes:
- scope1
- scope2
IoTRule
The object describing an IoTRule event source type.
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 Serverless Application Model (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
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
AWS CloudFormation compatibility: This property is passed directly to the Sql property of an
AWS::IoT::TopicRule TopicRulePayload resource.
105
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Examples
IOT Rule
YAML
IoTRule:
Type: IoTRule
Properties:
Sql: SELECT * FROM 'topic/test'
Kinesis
The object describing a Kinesis event source type. For more information, see Using AWS Lambda with
Amazon Kinesis in the AWS Lambda Developer Guide.
AWS SAM generates an AWS::Lambda::EventSourceMapping resource when this event type is set.
Syntax
To declare this entity in your AWS Serverless Application Model (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
TumblingWindowInSeconds: Integer
Properties
BatchSize
Type: Integer
Required: No
Default: 100
AWS CloudFormation compatibility: This property is passed directly to the BatchSize property of an
AWS::Lambda::EventSourceMapping resource.
Minimum: 1
Maximum: 10000
BisectBatchOnFunctionError
If the function returns an error, split the batch in two and retry.
106
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: Boolean
Required: No
An Amazon SQS queue or Amazon SNS topic destination for discarded records.
Type: DestinationConfig
Required: No
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Enabled property of an
AWS::Lambda::EventSourceMapping resource.
MaximumBatchingWindowInSeconds
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
107
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Required: No
Type: String
Required: Yes
Type: String
Required: Yes
The duration, in seconds, of a processing window. The valid range is 1 to 900 (15 minutes).
For more information, see Tumbling windows in the AWS Lambda Developer Guide.
Type: Integer
Required: No
Examples
YAML
Events:
KinesisEvent:
Type: Kinesis
Properties:
Stream: arn:aws:kinesis:us-east-1:123456789012:stream/my-stream
StartingPosition: TRIM_HORIZON
BatchSize: 10
Enabled: false
MQ
The object describing an MQ event source type. For more information, see Using AWS Lambda with
Amazon MQ in the AWS Lambda Developer Guide.
108
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
AWS SAM generates an AWS::Lambda::EventSourceMapping resource when this event type is set.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
BatchSize: Integer
Broker: String
Enabled: Boolean
Queues: List
SourceAccessConfigurations: List
Properties
BatchSize
Type: Integer
Required: No
Default: 100
AWS CloudFormation compatibility: This property is passed directly to the BatchSize property of an
AWS::Lambda::EventSourceMapping resource.
Minimum: 1
Maximum: 10000
Broker
Type: String
Required: Yes
If true, the event source mapping is active. To pause polling polling and invocation, set to false.
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Enabled property of an
AWS::Lambda::EventSourceMapping resource.
Queues
Type: List
Required: Yes
109
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
AWS CloudFormation compatibility: This property is passed directly to the Queues property of an
AWS::Lambda::EventSourceMapping resource.
SourceAccessConfigurations
The AWS Secrets Manager secret that stores your broker credentials. Specify secrets using the
SourceAccessConfigurations data type.
Type: List
Required: Yes
Examples
YAML
Events:
MQEvent:
Type: MQ
Properties:
Broker: arn:aws:mq:us-
east-2:123456789012:broker:MyBroker:b-1234a5b6-78cd-901e-2fgh-3i45j6k178l9
Queues: List of queues
SourceAccessConfigurations:
- Type: String
URI: String
BatchSize: 200
Enabled: True
MSK
The object describing an MSK event source type. For more information, see Using AWS Lambda with
Amazon MSK in the AWS Lambda Developer Guide.
AWS SAM generates an AWS::Lambda::EventSourceMapping resource when this event type is set.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
StartingPosition: String
Stream: String
Topics: List
Properties
StartingPosition
110
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: String
Required: Yes
Type: String
Required: Yes
Type: List
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the Topics property of an
AWS::Lambda::EventSourceMapping resource.
Examples
The following is an example of an MSK event source type for an Amazon MSK cluster that already exists
in an AWS account.
YAML
Events:
MSKEvent:
Type: MSK
Properties:
StartingPosition: LATEST
Stream: arn:aws:kafka:us-east-1:012345678012:cluster/exampleClusterName/
abcdefab-1234-abcd-5678-cdef0123ab01-2
Topics:
- MyTopic
The following is an example of an MSK event source type for an Amazon MSK cluster that is declared in
the same template file.
YAML
Events:
MSKEvent:
Type: MSK
111
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Properties:
StartingPosition: LATEST
Stream:
Ref: MyMskCluster # This must be the name of an MSK cluster declared in the same
template file
Topics:
- MyTopic
S3
The object describing an S3 event source type.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Bucket: String
Events: String | List
Filter: NotificationFilter
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 a list of valid values.
Required: Yes
AWS 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 Amazon S3 objects invoke the Lambda function. For
information about Amazon S3 key name filtering, see Configuring Amazon S3 Event Notifications in
the Amazon Simple Storage Service Developer Guide.
Type: NotificationFilter
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Filter property of the
AWS::S3::Bucket LambdaConfiguration data type.
112
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Examples
S3-Event
Example of an S3 Event.
YAML
Events:
S3Event:
Type: S3
Properties:
Bucket:
Ref: ImagesBucket # This must be the name of an S3 bucket declared in the same
template file
Events: s3:ObjectCreated:*
Filter:
S3Key:
Rules:
- Name: prefix # or "suffix"
Value: value # The value to search for in the S3 object key names
Schedule
The object describing a Schedule event source type.
AWS SAM generates an AWS::Events::Rule resource when this event type is set.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Description: String
Enabled: Boolean
Input: String
Name: String
Schedule: String
Properties
Description
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Description property of
an AWS::Events::Rule resource.
Enabled
Type: Boolean
113
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
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
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Target property of an
AWS::Events::Rule Target resource.
Name
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
AWS CloudFormation compatibility: This property is passed directly to the Name property of an
AWS::Events::Rule resource.
Schedule
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:
Type: Schedule
Properties:
Schedule: 'rate(1 minute)'
Name: TestSchedule
Description: test schedule
Enabled: False
SNS
The object describing an SNS event source type.
114
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
FilterPolicy: SnsFilterPolicy
Region: String
SqsSubscription: Boolean | SqsSubscriptionObject (p. 116)
Topic: String
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
AWS CloudFormation compatibility: This property is passed directly to the FilterPolicy property
of an AWS::SNS::Subscription resource.
Region
If no region is specified, CloudFormation uses the region of the caller as the default.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Region property of an
AWS::SNS::Subscription resource.
SqsSubscription
Set this property to true, or specify SqsSubscriptionObject to enable batching SNS topic
notifications in an SQS queue. Setting this property to true creates a new SQS queue, whereas
specifying a SqsSubscriptionObject uses an existing SQS queue.
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Topic
Type: String
Required: Yes
115
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
AWS CloudFormation compatibility: This property is passed directly to the TopicArn property of an
AWS::SNS::Topic resource.
Examples
YAML
Events:
SNSEvent:
Type: SNS
Properties:
Topic: arn:aws:sns:us-east-1:123456789012:my_topic
SqsSubscription: True
FilterPolicy:
store:
- example_corp
price_usd:
- numeric:
- ">="
- 100
SqsSubscriptionObject
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
BatchSize: String
Enabled: Boolean
QueueArn: String
QueuePolicyLogicalId: String
QueueUrl: String
Properties
BatchSize
The maximum number of items to retrieve in a single batch for the SQS queue.
Type: String
Required: No
Default: 10
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Enabled
Disables the SQS event source mapping to pause polling and invocation.
116
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Type: Boolean
Required: No
Default: True
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
QueueArn
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
QueuePolicyLogicalId
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
QueueUrl
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
YAML
QueuePolicyLogicalId: CustomQueuePolicyLogicalId
QueueArn:
Fn::GetAtt: MyCustomQueue.Arn
QueueUrl:
Ref: MyCustomQueue
BatchSize: 5
SQS
The object describing an SQS event source type. For more information, see Using AWS Lambda with
Amazon SQS in the AWS Lambda Developer Guide.
117
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
BatchSize: Integer
Enabled: Boolean
MaximumBatchingWindowInSeconds: Integer
Queue: String
Properties
BatchSize
Type: Integer
Required: No
Default: 10
AWS CloudFormation compatibility: This property is passed directly to the BatchSize property of an
AWS::Lambda::EventSourceMapping resource.
Minimum: 1
Maximum: 10000
Enabled
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Enabled property of an
AWS::Lambda::EventSourceMapping resource.
MaximumBatchingWindowInSeconds
The maximum amount of time, in seconds, to gather records before invoking the function.
Type: Integer
Required: No
Type: String
Required: Yes
118
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
Examples
SQS Event
SQS Event
YAML
Events:
SQSEvent:
Type: SQS
Properties:
Queue: arn:aws:sqs:us-west-2:012345678901:my-queue
BatchSize: 10
Enabled: false
FunctionCode
The deployment package for a Lambda function.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Bucket: String
Key: String
Version: String
Properties
Bucket
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the S3Bucket property of the
AWS::Lambda::Function Code data type.
Key
Type: String
Required: Yes
AWS 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.
Type: String
119
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
Required: No
Examples
FunctionCode
YAML
FunctionCode:
Bucket: mybucket-name
Key: mykey-name
Version: 121212
AWS::Serverless::HttpApi
Creates an Amazon API Gateway HTTP API, which enables you to create RESTful APIs with lower latency
and lower costs than REST APIs. For more information, see Working with HTTP APIs in the API Gateway
Developer Guide.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Type: AWS::Serverless::HttpApi
Properties:
AccessLogSettings: AccessLogSettings
Auth: HttpApiAuth (p. 126)
CorsConfiguration: String | HttpApiCorsConfiguration (p. 132)
DefaultRouteSettings: RouteSettings
DefinitionBody: String
DefinitionUri: String | HttpApiDefinition (p. 134)
Description: String
DisableExecuteApiEndpoint: Boolean
Domain: HttpApiDomainConfiguration (p. 135)
FailOnWarnings: Boolean
RouteSettings: RouteSettings
StageName: String
StageVariables: Json
Tags: Map
Properties
AccessLogSettings
Type: AccessLogSettings
Required: No
120
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
Configures authorization for controlling access to your API Gateway HTTP API.
For more information, see Controlling access to HTTP APIs with JWT authorizers in the API Gateway
Developer Guide.
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
CorsConfiguration
Manages cross-origin resource sharing (CORS) for all your API Gateway HTTP APIs. Specify the
domain to allow as a string, or specify an HttpApiCorsConfiguration object. Note that CORS
requires AWS SAM to modify your OpenAPI definition, so CORS works only if the DefinitionBody
property is specified.
For more information, see Configuring CORS for an HTTP API in the API Gateway Developer Guide.
Note: If CorsConfiguration is set both in an OpenAPI definition and at the property level, then
AWS SAM merges both configuration sources with the properties taking precedence.
Note: If this property is set to true, then all origins are allowed.
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
DefaultRouteSettings
The default route settings for this HTTP API. These settings apply to all routes unless overridden by
the RouteSettings property for certain routes.
Type: RouteSettings
Required: No
AWS CloudFormation compatibility: This property is passed directly to the RouteSettings property
of an AWS::ApiGatewayV2::Stage resource.
DefinitionBody
The OpenAPI definition that describes your HTTP API. If you don't specify a DefinitionUri or
a DefinitionBody, AWS SAM generates a DefinitionBody for you based on your template
configuration.
Type: String
Required: No
121
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
The Amazon Simple Storage Service (Amazon S3) URI, local file path, or location object of the
the OpenAPI definition that defines the HTTP API. The Amazon S3 object that this property
references must be a valid OpenAPI definition file. If you don't specify a DefinitionUri or a
DefinitionBody are specified, AWS SAM generates a DefinitionBody for you based on your
template configuration.
If you provide a local file path, the template must go through the workflow that includes the sam
deploy or sam package command for the definition to be transformed properly.
Intrinsic functions are not supported in external OpenApi definition files that you reference with
DefinitionUri. To import an OpenApi definition into the template, use the DefinitionBody
property with the Include transform.
Required: No
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Description property of
an AWS::ApiGatewayV2::Api resource.
DisableExecuteApiEndpoint
Specifies whether clients can invoke your HTTP API by using the default execute-api endpoint
https://{api_id}.execute-api.{region}.amazonaws.com. By default, clients can invoke
your API with the default endpoint. To require that clients only use a custom domain name to invoke
your API, disable the default endpoint.
Type: Boolean
Required: No
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
FailOnWarnings
Specifies whether to roll back the HTTP API creation (true) or not (false) when a warning is
encountered. The default value is false.
122
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
Type: Boolean
Required: No
The route settings, per route, for this HTTP API. For more information, see Working with routes for
HTTP APIs in the API Gateway Developer Guide.
Type: RouteSettings
Required: No
AWS CloudFormation compatibility: This property is passed directly to the RouteSettings property
of an AWS::ApiGatewayV2::Stage resource.
StageName
The name of the API stage. If no name is specified, AWS SAM uses the $default stage from API
Gateway.
Type: String
Required: No
Default: $default
AWS CloudFormation compatibility: This property is passed directly to the StageName property of an
AWS::ApiGatewayV2::Stage resource.
StageVariables
A map that defines the stage variables. Variable names can have alphanumeric and underscore
characters. The values must match [A-Za-z0-9-._~:/?#&=,]+.
Type: Json
Required: No
A map (string to string) that specifies the tags to add 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
include the prefix aws:. Values can be 1 to 255 Unicode characters in length.
Type: Map
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Additional notes: The Tags property requires AWS SAM to modify your OpenAPI definition,
so tags are added only if the DefinitionBody property is specified—no tags are
added if the DefinitionUri property is specified. AWS SAM automatically adds an
httpapi:createdBy:SAM tag. Tags are also added to the AWS::ApiGatewayV2::Stage resource
and the AWS::ApiGatewayV2::DomainName resource (if DomainName is specified).
123
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
Return Values
Ref
When you pass the logical ID of this resource to the intrinsic Ref function, Ref returns the API ID of the
underlying AWS::ApiGatewayV2::Api resource, for example, a1bcdef2gh.
For more information about using the Ref function, see Ref in the AWS CloudFormation User Guide.
Examples
Simple HttpApi
The following example shows the minimum needed to set up an HTTP API endpoint backed by an
Lambda function. This example uses the default HTTP API that AWS SAM creates.
YAML
AWSTemplateFormatVersion: '2010-09-09'
Description: AWS SAM template with a simple API definition
Resources:
ApiFunction:
Type: AWS::Serverless::Function
Properties:
Events:
ApiEvent:
Type: HttpApi
Handler: index.handler
InlineCode: |
def handler(event, context):
return {'body': 'Hello World!', 'statusCode': 200}
Runtime: python3.7
Transform: AWS::Serverless-2016-10-31
YAML
Properties:
FailOnWarnings: True
Auth:
DefaultAuthorizer: OAuth2
Authorizers:
OAuth2:
AuthorizationScopes:
- scope4
JwtConfiguration:
issuer: "https://www.example.com/v1/connect/oauth2"
audience:
- MyApi
IdentitySource: "$request.querystring.param"
OpenIdAuth:
AuthorizationScopes:
- scope1
- scope2
OpenIdConnectUrl: "https://www.example.com/v1/connect/oidc/.well-known/openid-
configuration"
124
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
JwtConfiguration:
issuer: "https://www.example.com/v1/connect/oidc"
audience:
- MyApi
IdentitySource: "$request.querystring.param"
Note that AWS SAM fills in any missing Lambda integrations for HttpApi events that reference this HTTP
API. AWS SAM also also adds any missing paths that HttpApi events reference.
YAML
Properties:
FailOnWarnings: True
DefinitionBody:
info:
version: '1.0'
title:
Ref: AWS::StackName
paths:
"/":
get:
security:
- OpenIdAuth:
- scope1
- scope2
responses: {}
openapi: 3.0.1
securitySchemes:
OpenIdAuth:
type: openIdConnect
x-amazon-apigateway-authorizer:
identitySource: "$request.querystring.param"
type: jwt
jwtConfiguration:
audience:
- MyApi
issuer: https://www.example.com/v1/connect/oidc
openIdConnectUrl: https://www.example.com/v1/connect/oidc/.well-known/openid-
configuration
YAML
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Parameters:
StageName:
Type: String
Default: Prod
Resources:
HttpApiFunction:
Type: AWS::Serverless::Function
Properties:
InlineCode: |
125
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
HttpApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: !Ref StageName
Tags:
Tag: Value
AccessLogSettings:
DestinationArn: !GetAtt AccessLogs.Arn
Format: $context.requestId
DefaultRouteSettings:
ThrottlingBurstLimit: 200
RouteSettings:
"GET /path":
ThrottlingBurstLimit: 500 # overridden in HttpApi Event
StageVariables:
StageVar: Value
FailOnWarnings: True
AccessLogs:
Type: AWS::Logs::LogGroup
Outputs:
HttpApiUrl:
Description: URL of your API endpoint
Value:
Fn::Sub: 'https://${HttpApi}.execute-api.${AWS::Region}.${AWS::URLSuffix}/
${StageName}/'
HttpApiId:
Description: Api id of HttpApi
Value:
Ref: HttpApi
HttpApiAuth
Configure authorization to control access to your Amazon API Gateway HTTP API.
For more information about configuring access to HTTP APIs, see Controlling and managing access to an
HTTP API in API Gateway in the API Gateway Developer Guide.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
126
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
YAML
Properties
Authorizers
Required: No
Default: None
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Additional notes: AWS SAM adds the authorizers to the OpenAPI definition.
DefaultAuthorizer
Specify the default authorizer to use for authorizing API calls to your API Gateway API.
Type: String
Required: No
Default: None
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
OAuth 2.0 Authorizer
YAML
Auth:
Authorizers:
OAuth2Authorizer:
AuthorizationScopes:
- scope1
- scope2
JwtConfiguration:
issuer: "https://www.example.com/v1/connect/oauth2"
audience:
- MyApi
IdentitySource: "$request.querystring.param"
DefaultAuthorizer: OAuth2Authorizer
LambdaAuthorizer
Configure a Lambda authorizer to control access to your Amazon API Gateway HTTP API with an AWS
Lambda function.
127
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
For more information and examples, see Working with AWS Lambda authorizers for HTTP APIs in the API
Gateway Developer Guide.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AuthorizerPayloadFormatVersion: String
EnableSimpleResponses: Boolean
FunctionArn: String
FunctionInvokeRole: String
Identity: LambdaAuthorizationIdentity (p. 129)
Properties
AuthorizerPayloadFormatVersion
Specifies the format of the payload sent to an HTTP API Lambda authorizer. Required for HTTP API
Lambda authorizers.
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
EnableSimpleResponses
Specifies whether a Lambda authorizer returns a response in a simple format. By default, a Lambda
authorizer must return an AWS Identity and Access Management (IAM) policy. If enabled, the
Lambda authorizer can return a boolean value instead of an IAM policy.
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
FunctionArn
The Amazon Resource Name (ARN) of the Lambda function that provides authorization for the API.
Type: String
Required: Yes
128
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
FunctionInvokeRole
The ARN of the IAM role that has the credentials required to invoke the authorizer.
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Identity
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
LambdaAuthorizer
LambdaAuthorizer example
YAML
Authorizer:
MyLambdaAuthorizer:
AuthorizerPayloadFormatVersion: 2.0
FunctionArn:
Fn::GetAtt:
- MyAuthFunction
- Arn
FunctionInvokeRole:
Fn::GetAtt:
- LambdaAuthInvokeRole
- Arn
Identity:
Headers:
- Authorization
LambdaAuthorizationIdentity
Use property can be used to specify an IdentitySource in an incoming request for a Lambda authorizer.
For more information about identity sources, see Identity sources in the API Gateway Developer Guide.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
129
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
YAML
Context: List
Headers: List
QueryStrings: List
ReauthorizeEvery: Integer
StageVariables: List
Properties
Context
Converts the given context strings to a list of mapping expressions in the format
$context.contextString.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Headers
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
QueryStrings
Converts the given query strings to a list of mapping expressions in the format
$request.querystring.queryString.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't 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. The
maximum value is 3600, or 1 hour.
Type: Integer
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
StageVariables
Converts the given stage variables to a list of mapping expressions in the format
$stageVariables.stageVariable.
Type: List
130
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
LambdaRequestIdentity
YAML
Identity:
QueryStrings:
- auth
Headers:
- Authorization
StageVariables:
- VARIABLE
Context:
- authcontext
ReauthorizeEvery: 100
OAuth2Authorizer
Definition for an OAuth 2.0 authorizer, also known to as a JSON Web Token (JWT) authorizer.
For more information, see Controlling access to HTTP APIs with JWT authorizers in the API Gateway
Developer Guide.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AuthorizationScopes: List
IdentitySource: String
JwtConfiguration: Map
Properties
AuthorizationScopes
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IdentitySource
Type: String
131
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
JwtConfiguration
Type: Map
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
YAML
Auth:
Authorizers:
OAuth2Authorizer:
AuthorizationScopes:
- scope1
JwtConfiguration:
issuer: "https://www.example.com/v1/connect/oauth2"
audience:
- MyApi
IdentitySource: "$request.querystring.param"
DefaultAuthorizer: OAuth2Authorizer
HttpApiCorsConfiguration
Manage cross-origin resource sharing (CORS) for your HTTP 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 only works with inline OpenApi defined in the DefinitionBody property.
For more information about CORS, see Configuring CORS for an HTTP API in the API Gateway Developer
Guide.
Note: If HttpApiCorsConfiguration is set both in OpenAPI and at the property level, AWS SAM merges
them with the properties taking precedence.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AllowCredentials: Boolean
AllowHeaders: List
132
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
AllowMethods: List
AllowOrigins: List
ExposeHeaders: List
MaxAge: Integer
Properties
AllowCredentials
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AllowHeaders
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AllowMethods
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AllowOrigins
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
ExposeHeaders
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
MaxAge
The number of seconds that the browser should cache preflight request results.
133
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
Type: Integer
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
HttpApiCorsConfiguration
YAML
CorsConfiguration:
AllowOrigins:
- "https://example.com"
AllowHeaders:
- x-apigateway-header
AllowMethods:
- GET
MaxAge: 600
AllowCredentials: True
HttpApiDefinition
An OpenAPI document defining the API.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Bucket: String
Key: String
Version: String
Properties
Bucket
The name of the Amazon S3 bucket where the OpenAPI file is stored.
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the Bucket property of the
AWS::ApiGatewayV2::Api BodyS3Location data type.
Key
Type: String
134
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the Key property of the
AWS::ApiGatewayV2::Api BodyS3Location data type.
Version
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Version property of the
AWS::ApiGatewayV2::Api BodyS3Location data type.
Examples
Definition Uri example
YAML
DefinitionUri:
Bucket: mybucket-name
Key: mykey-name
Version: 121212
HttpApiDomainConfiguration
Configures a custom domain for an API.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
BasePath: List
CertificateArn: String
DomainName: String
EndpointConfiguration: String
MutualTlsAuthentication: MutualTlsAuthentication
Route53: Route53Configuration (p. 137)
SecurityPolicy: String
Properties
BasePath
A list of the basepaths to configure with the Amazon API Gateway domain name.
Type: List
Required: No
Default: /
135
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
The Amazon Resource Name (ARN) of an AWS managed certificate for this domain name's endpoint.
AWS Certificate Manager is the only supported source.
Type: String
Required: Yes
The custom domain name for your API Gateway API. Uppercase letters are not supported.
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the DomainName property of
an AWS::ApiGateway2::DomainName resource.
EndpointConfiguration
Defines the type of API Gateway endpoint to map to the custom domain. The value of this property
determines how the CertificateArn property is mapped in AWS CloudFormation.
Type: String
Required: No
Default: REGIONAL
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
MutualTlsAuthentication
The mutual transport layer security (TLS) authentication configuration for a custom domain name.
Type: MutualTlsAuthentication
Required: No
136
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
SecurityPolicy
The TLS version of the security policy for this domain name.
Type: String
Required: No
Examples
DomainName
DomainName example
YAML
Domain:
DomainName: www.example.com
CertificateArn: arn-example
EndpointConfiguration: REGIONAL
Route53:
HostedZoneId: Z1PA6795UKMFR9
BasePath:
- /foo
- /bar
Route53Configuration
Configures the Route53 record sets for an API.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
DistributionDomainName: String
EvaluateTargetHealth: Boolean
HostedZoneId: String
HostedZoneName: String
IpV6: Boolean
Properties
DistributionDomainName
Type: String
137
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
Required: No
AWS CloudFormation compatibility: This property is passed directly to the DNSName property of an
AWS::Route53::RecordSetGroup AliasTarget resource.
When EvaluateTargetHealth is true, an alias record inherits the health of the referenced AWS
resource, such as an Elastic Load Balancing load balancer or another record in the hosted zone.
Type: Boolean
Required: No
Additional notes: You can't set EvaluateTargetHealth to true when the alias target is a CloudFront
distribution.
HostedZoneId
The ID of the hosted zone that you want to create records in.
Specify either HostedZoneName or HostedZoneId, but not both. If you have multiple hosted zones
with the same domain name, you must specify the hosted zone using HostedZoneId.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the HostedZoneId property
of an AWS::Route53::RecordSetGroup RecordSet resource.
HostedZoneName
The name of the hosted zone that you want to create records in.
Specify either HostedZoneName or HostedZoneId, but not both. If you have multiple hosted zones
with the same domain name, you must specify the hosted zone using HostedZoneId.
Type: String
Required: No
When this property is set, AWS SAM creates a AWS::Route53::RecordSet resource and sets Type
to AAAA for the provided HostedZone.
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
138
AWS Serverless Application Model Developer Guide
AWS::Serverless::LayerVersion
Examples
YAML
Domain:
DomainName: www.example.com
CertificateArn: arn-example
EndpointConfiguration: EDGE
Route53:
HostedZoneId: Z1PA6795UKMFR9
EvaluateTargetHealth: true
DistributionDomainName: xyz
AWS::Serverless::LayerVersion
Creates a Lambda LayerVersion that contains library or runtime code needed by a Lambda Function.
The AWS::Serverless::LayerVersion (p. 139) resource also supports the Metadata resource attribute,
so you can instruct AWS SAM to build layers included in your application. For more information about
building layers, see Building layers (p. 188).
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. 139).
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 Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Type: AWS::Serverless::LayerVersion
Properties:
CompatibleRuntimes: List
ContentUri: String | LayerContent (p. 141)
Description: String
LayerName: String
LicenseInfo: String
RetentionPolicy: String
Properties
CompatibleRuntimes
Type: List
Required: No
139
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 contains 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
AWS CloudFormation compatibility: This property is passed directly to the Description property of
an AWS::Lambda::LayerVersion resource.
LayerName
Type: String
Required: No
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the LicenseInfo property of
an AWS::Lambda::LayerVersion resource.
RetentionPolicy
Specifies whether old versions of your LayerVersion are retained or deleted after an update.
Type: String
Required: No
140
AWS Serverless Application Model Developer Guide
AWS::Serverless::LayerVersion
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Additional notes: When you specify Retain, AWS SAM adds a Resource attributes (p. 161) 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 in the AWS CloudFormation User Guide.
Examples
LayerVersionExample
Example of a LayerVersion
YAML
Properties:
LayerName: MyLayer
Description: Layer description
ContentUri: 's3://my-bucket/my-layer.zip'
CompatibleRuntimes:
- nodejs10.x
- nodejs12.x
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 Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Bucket: String
Key: String
Version: String
Properties
Bucket
Type: String
141
AWS Serverless Application Model Developer Guide
AWS::Serverless::SimpleTable
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the S3Bucket property of the
AWS::Lambda::LayerVersion Content data type.
Key
Type: String
Required: Yes
AWS 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 Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Type: AWS::Serverless::SimpleTable
Properties:
PrimaryKey: PrimaryKeyObject (p. 144)
ProvisionedThroughput: ProvisionedThroughput
142
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
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
ProvisionedThroughput
Type: ProvisionedThroughput
Required: No
Type: SSESpecification
Required: No
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the TableName property of an
AWS::DynamoDB::Table resource.
Tags
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
143
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 in the AWS CloudFormation User Guide.
Examples
SimpleTableExample
Example of a SimpleTable
YAML
Properties:
TableName: my-table
Tags:
Department: Engineering
AppType: Serverless
PrimaryKeyObject
The object describing the properties of a primary key.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Name: String
Type: String
Properties
Name
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the AttributeName property
of the AWS::DynamoDB::Table AttributeDefinition data type.
144
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the AttributeType property
of the AWS::DynamoDB::Table AttributeDefinition data type.
Examples
PrimaryKey
YAML
Properties:
PrimaryKey:
Name: MyPrimaryKey
Type: String
AWS::Serverless::StateMachine
Creates an AWS Step Functions state machine, which you can use to orchestrate AWS Lambda functions
and other AWS resources to form complex and robust workflows.
For more information about Step Functions, see the AWS Step Functions Developer Guide.
Note: To manage AWS SAM templates that contain Step Functions state machines, you must use
version 0.52.0 or later of the AWS SAM CLI. To check which version you have, run the command sam --
version.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Type: AWS::Serverless::StateMachine
Properties:
Definition: Map
DefinitionSubstitutions: Map
DefinitionUri: String | S3Location
Events: EventSource (p. 149)
Logging: LoggingConfiguration
Name: String
PermissionsBoundary: String
Policies: String | List | Map
Role: String
145
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
Tags: Map
Tracing: TracingConfiguration
Type: String
Properties
Definition
The state machine definition is an object, where the format of the object matches the format of
your AWS SAM template file, for example, JSON or YAML. State machine definitions adhere to the
Amazon States Language.
For an example of an inline state machine definition, see Examples (p. 149).
Type: Map
Required: Conditional
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
DefinitionSubstitutions
A string-to-string map that specifies the mappings for placeholder variables in the state machine
definition. This enables you to inject values obtained at runtime (for example, from intrinsic
functions) into the state machine definition.
Type: Map
Required: No
The Amazon Simple Storage Service (Amazon S3) URI or local file path of the state machine
definition written in the Amazon States Language.
If you provide a local file path, the template must go through the workflow that includes the sam
deploy or sam package command to correctly transform the definition. To do this, you must use
version 0.52.0 or later of the AWS SAM CLI.
Required: Conditional
Specifies the events that trigger this state machine. Events consist of a type and a set of properties
that depend on the type.
146
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Logging
Defines which execution history events are logged and where they are logged.
Type: LoggingConfiguration
Required: No
Type: String
Required: No
The ARN of a permissions boundary to use for this state machine's execution role. This property only
works if the role is generated for you.
Type: String
Required: No
One or more policies that this state machine's execution role needs.
This property accepts a single string or a list of strings. The property can be the name of AWS
managed AWS Identity and Access Management (IAM) policies, AWS SAM policy templates, or one or
more inline policy documents formatted as a map.
Required: Conditional
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Role
The ARN of an IAM role to use as this state machine's execution role.
147
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
Type: String
Required: Conditional
AWS CloudFormation compatibility: This property is passed directly to the RoleArn property of an
AWS::StepFunctions::StateMachine resource.
Tags
A string-to-string map that specifies the tags added to the state machine and the corresponding
execution role.
Type: Map
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Tags property of an
AWS::StepFunctions::StateMachine resource.
Tracing
Selects whether or not AWS X-Ray is enabled for the state machine. For more information about
using X-Ray with Step Functions, see AWS X-Ray and Step Functions in the AWS Step Functions
Developer Guide.
Type: TracingConfiguration
Required: No
Type: String
Required: No
Default: STANDARD
Return Values
Ref
When you provide the logical ID of this resource to the Ref intrinsic function, Ref returns the Amazon
Resource Name (ARN) of the underlying AWS::StepFunctions::StateMachine resource.
For more information about using the Ref function, see Ref in the AWS CloudFormation User Guide.
Fn::GetAtt
Fn::GetAtt returns a value for a specified attribute of this type. The following are the available
attributes and sample return values.
148
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
For more information about using Fn::GetAtt, see Fn::GetAtt in the AWS CloudFormation User
Guide.
Name
Examples
State Machine Definition File
The following is an example of a state machine defined with a definition file. The
my_state_machine.asl.json file must be written in the Amazon States Language.
In this example, the DefinitionSubstitution entries allow the state machine to include resources
that are declared in the AWS SAM template file.
YAML
MySampleStateMachine:
Type: AWS::Serverless::StateMachine
Properties:
DefinitionUri: statemachine/my_state_machine.asl.json
Role: arn:aws:iam::123456123456:role/service-role/my-sample-role
Tracing:
Enabled: True
DefinitionSubstitutions:
MyFunctionArn: !GetAtt MyFunction.Arn
MyDDBTable: !Ref TransactionTable
In this example, the AWS SAM template file is written in YAML, so the state machine definition is also in
YAML. To declare an inline state machine definition in JSON, write your AWS SAM template file in JSON.
YAML
MySampleStateMachine:
Type: AWS::Serverless::StateMachine
Properties:
Definition:
StartAt: MyLambdaState
States:
MyLambdaState:
Type: Task
Resource: arn:aws:lambda:us-east-1:123456123456:function:my-sample-lambda-app
End: true
Role: arn:aws:iam::123456123456:role/service-role/my-sample-role
Tracing:
Enabled: True
EventSource
The object describing the source of events which trigger the state machine. 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 subtopic corresponding to that type.
149
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Properties: Schedule (p. 150) | CloudWatchEvent (p. 158) | EventBridgeRule (p. 159)
| Api (p. 152)
Type: String
Properties
Properties
An object describing the properties of this event mapping. The set of properties must conform to
the defined Type.
Type: Schedule (p. 150) | CloudWatchEvent (p. 158) | EventBridgeRule (p. 159) | Api (p. 152)
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Type
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
API
YAML
ApiEvent:
Type: Api
Properties:
Method: get
Path: /group/{user}
RestApiId:
Ref: MyApi
Schedule
The object describing a Schedule event source type.
150
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
AWS SAM generates an AWS::Events::Rule resource when this event type is set.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Description: String
Enabled: Boolean
Input: String
Name: String
Schedule: String
Properties
Description
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Description property of
an AWS::Events::Rule resource.
Enabled
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
Required: No
AWS CloudFormation compatibility: This property is passed directly to the Target property of an
AWS::Events::Rule Target resource.
Name
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
151
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
AWS CloudFormation compatibility: This property is passed directly to the Name property of an
AWS::Events::Rule resource.
Schedule
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:
Type: Schedule
Properties:
Schedule: 'rate(1 minute)'
Name: TestSchedule
Description: test schedule
Enabled: False
Api
The object describing an Api event source type. If an AWS::Serverless::Api (p. 30) resource is defined,
the path and method values must correspond to an operation in the OpenAPI definition of the API.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
Properties
Auth
Use this property to override the API's DefaultAuthorizer setting for an individual path, when no
DefaultAuthorizer is specified, or to override the default ApiKeyRequired setting.
Required: No
152
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Method
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Path
The URI path for which this function is invoked. The value must start with /.
Type: String
Required: Yes
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
RestApiId
The 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. 30) resource that is defined
in this template.
If you don't define this property, AWS SAM creates a default AWS::Serverless::Api (p. 30) resource
using a generated OpenApi document. That resource contains a union of all paths and methods
defined by Api events in the same template that do not specify a RestApiId.
This property can't reference an AWS::Serverless::Api (p. 30) resource that is defined in another
template.
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
ApiEvent
YAML
Events:
ApiEvent:
Type: Api
Properties:
Path: /path
Method: get
RequestParameters:
- method.request.header.Authorization
153
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
ApiStateMachineAuth
Configures authorization at the event level, for a specific API, path, and method.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
ApiKeyRequired: Boolean
AuthorizationScopes: List
Authorizer: String
ResourcePolicy: ResourcePolicyStatement (p. 155)
Properties
ApiKeyRequired
Type: Boolean
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AuthorizationScopes
The scopes that you specify will override any scopes applied by the DefaultAuthorizer property
if you have specified it.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Authorizer
If you have specified a global authorizer for the API and want to make this state machine public,
override the global authorizer by setting Authorizer to NONE.
Type: String
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
ResourcePolicy
154
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
StateMachine-Auth
YAML
Auth:
ApiKeyRequired: true
Authorizer: NONE
ResourcePolicyStatement
Configures a resource policy for all methods and paths of an API. For more information about resource
policies, see Controlling access to an API with API Gateway resource policies in the API Gateway Developer
Guide.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
AwsAccountBlacklist: List
AwsAccountWhitelist: List
CustomStatements: List
IntrinsicVpcBlacklist: List
IntrinsicVpcWhitelist: List
IntrinsicVpceBlacklist: List
IntrinsicVpceWhitelist: List
IpRangeBlacklist: List
IpRangeWhitelist: List
SourceVpcBlacklist: List
SourceVpcWhitelist: List
Properties
AwsAccountBlacklist
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
AwsAccountWhitelist
The AWS accounts to allow. For an example use of this property, see the Examples section at the
bottom of this page.
155
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
CustomStatements
A list of custom resource policy statements to apply to this API. For an example use of this property,
see the Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpcBlacklist
The list of virtual private clouds (VPCs) to block, where each VPC is specified as a reference such
as a dynamic reference or the Ref intrinsic function. For an example use of this property, see the
Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpcWhitelist
The list of VPCs to allow, where each VPC is specified as a reference such as a dynamic reference or
the Ref intrinsic function.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpceBlacklist
The list of VPC endpoints to block, where each VPC endpoint is specified as a reference such as a
dynamic reference or the Ref intrinsic function.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IntrinsicVpceWhitelist
The list of VPC endpoints to allow, where each VPC endpoint is specified as a reference such as
a dynamic reference or the Ref intrinsic function. For an example use of this property, see the
Examples section at the bottom of this page.
Type: List
156
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IpRangeBlacklist
The IP addresses or address ranges to block. For an example use of this property, see the Examples
section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
IpRangeWhitelist
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
SourceVpcBlacklist
The source VPC or VPC endpoints to block. Source VPC names must start with "vpc-" and source
VPC endpoint names must start with "vpce-". For an example use of this property, see the
Examples section at the bottom of this page.
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
SourceVpcWhitelist
The source VPC or VPC endpoints to allow. Source VPC names must start with "vpc-" and source
VPC endpoint names must start with "vpce-".
Type: List
Required: No
AWS CloudFormation compatibility: This property is unique to AWS SAM and doesn't have an AWS
CloudFormation equivalent.
Examples
The following example blocks two IP addresses and a source VPC, and allows an AWS account.
YAML
Auth:
157
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
ResourcePolicy:
CustomStatements: [{
"Effect": "Allow",
"Principal": "*",
"Action": "execute-api:Invoke",
"Resource": "execute-api:/Prod/GET/pets",
"Condition": {
"IpAddress": {
"aws:SourceIp": "1.2.3.4"
}
}
}]
IpRangeBlacklist:
- "10.20.30.40"
- "1.2.3.4"
SourceVpcBlacklist:
- "vpce-1a2b3c4d"
AwsAccountWhitelist:
- "111122223333"
IntrinsicVpcBlacklist:
- "{{resolve:ssm:SomeVPCReference:1}}"
- !Ref MyVPC
IntrinsicVpceWhitelist:
- "{{resolve:ssm:SomeVPCEReference:1}}"
- !Ref MyVPCE
CloudWatchEvent
The object describing a CloudWatchEvent event source type.
AWS Serverless Application Model (AWS SAM) generates an AWS::Events::Rule resource when this event
type is set.
Important Note: EventBridgeRule (p. 159) is the preferred event source type to use, instead of
CloudWatchEvent. EventBridgeRule and CloudWatchEvent use the same underlying service,
API, and AWS CloudFormation resources. However, AWS SAM will add support for new features only to
EventBridgeRule.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
EventBusName: String
Input: String
InputPath: String
Pattern: EventPattern
Properties
EventBusName
The event bus to associate with this rule. If you omit this property, AWS SAM uses the default event
bus.
Type: String
Required: No
158
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
AWS CloudFormation compatibility: This property is passed directly to the EventBusName property
of an AWS::Events::Rule resource.
Input
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
AWS CloudFormation compatibility: This property is passed directly to the Input property of an
AWS::Events::Rule Target resource.
InputPath
When you don't want to pass the entire matched event to the target, use the InputPath property
to describe which part of the event to pass.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the InputPath property of an
AWS::Events::Rule Target resource.
Pattern
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
AWS CloudFormation compatibility: This property is passed directly to the EventPattern property
of an AWS::Events::Rule resource.
Examples
CloudWatchEvent
YAML
CWEvent:
Type: CloudWatchEvent
Properties:
Input: '{"Key": "Value"}'
Pattern:
detail:
state:
- terminated
EventBridgeRule
The object describing an EventBridgeRule event source type.
159
AWS Serverless Application Model Developer Guide
AWS::Serverless::StateMachine
AWS Serverless Application Model (AWS SAM) generates an AWS::Events::Rule resource when this event
type is set.
Syntax
To declare this entity in your AWS Serverless Application Model (AWS SAM) template, use the following
syntax.
YAML
EventBusName: String
Input: String
InputPath: String
Pattern: EventPattern
Properties
EventBusName
The event bus to associate with this rule. If you omit this property, AWS SAM uses the default event
bus.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the EventBusName property
of an AWS::Events::Rule resource.
Input
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
AWS CloudFormation compatibility: This property is passed directly to the Input property of an
AWS::Events::Rule Target resource.
InputPath
When you don't want to pass the entire matched event to the target, use the InputPath property
to describe which part of the event to pass.
Type: String
Required: No
AWS CloudFormation compatibility: This property is passed directly to the InputPath property of an
AWS::Events::Rule Target resource.
Pattern
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
160
AWS Serverless Application Model Developer Guide
Resource attributes
Required: Yes
AWS CloudFormation compatibility: This property is passed directly to the EventPattern property
of an AWS::Events::Rule resource.
Examples
EventBridgeRule
YAML
EBRule:
Type: EventBridgeRule
Properties:
Input: '{"Key": "Value"}'
Pattern:
detail:
state:
- terminated
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.
Notes:
* For more information about using the Metadata resource attribute with the
AWS::Serverless::Function resource type, see Building custom runtimes (p. 189).
161
AWS Serverless Application Model Developer Guide
Intrinsic functions
** For more information about using the Metadata resource attribute with the
AWS::Serverless::LayerVersion resource type, see Building layers (p. 188).
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.
For example, if you specify an AWS::Serverless::Function resource in your AWS SAM template
file, AWS SAM always generates an AWS::Lambda::Function base resource. If you also specify the
optional AutoPublishAlias property, AWS SAM additionally generates AWS::Lambda::Alias and
AWS::Lambda::Version resources.
This section lists the scenarios and the AWS CloudFormation resources that they generate, and shows
how to reference the generated AWS CloudFormation resources in your AWS SAM template file.
Topics
• Referencing generated AWS CloudFormation resources (p. 162)
• Generated AWS CloudFormation resource reference (p. 163)
• AWS CloudFormation resources generated when AWS::Serverless::Api is specified (p. 164)
• AWS CloudFormation resources generated when AWS::Serverless::Function is specified (p. 165)
• AWS CloudFormation resources generated when AWS::Serverless::HttpApi is specified (p. 167)
162
AWS Serverless Application Model Developer Guide
Generated AWS CloudFormation resource reference
Note
The LogicalIds of some generated resources include a unique hash value to avoid namespace
clashes. The LogicalIds of these resources are derived when the stack is created. You can
retrieve them only after the stack has been created using the AWS Management Console, AWS
CLI, or one of the AWS SDKs. We don't recommend referencing these resources by LogicalId
because the hash values might change.
The topics in the AWS SAM Resources column provide details about the base resources that are
generated when you specify the AWS SAM resource. The topics in the Scenarios column provide details
about the additional resources generated for that scenario.
• DomainName
property is
specified (p. 165)
AWS::Serverless::Api (p. 164)
• UsagePlan
property is
specified (p. 165)
• AutoPublishAlias
property is
specified (p. 166)
• Role property
is not
specified (p. 166)
• OnSuccess
(or OnFailure)
AWS::Serverless::Function (p. 165) property is
specified for
Amazon SNS
events (p. 166)
• OnSuccess
(or OnFailure)
property is
specified for
Amazon SQS
events (p. 167)
163
AWS Serverless Application Model Developer Guide
AWS::Serverless::Api
• StageName
property is
specified (p. 168)
• StageName
AWS::Serverless::HttpApi (p. 167) property is not
specified (p. 168)
• DomainName
property is
specified (p. 168)
Topics
• AWS CloudFormation resources generated when AWS::Serverless::Api is specified (p. 164)
• AWS CloudFormation resources generated when AWS::Serverless::Function is specified (p. 165)
• AWS CloudFormation resources generated when AWS::Serverless::HttpApi is specified (p. 167)
AWS::ApiGateway::RestApi
LogicalId: <api‑LogicalId>
Referenceable property: N/A (you must use the LogicalId to reference this AWS CloudFormation
resource)
AWS::ApiGateway::Stage
LogicalId: <api‑LogicalId><stage‑name>Stage
<stage‑name> is the string that the StageName property is set to. For example, if you set
StageName to Gamma, the LogicalId is MyRestApiGammaStage.
LogicalId: <api‑LogicalId>Deployment<sha>
<sha> is a unique hash value that is generated when the stack is created. For example,
MyRestApiDeployment926eeb5ff1.
Scenarios
• DomainName property is specified (p. 165)
• UsagePlan property is specified (p. 165)
164
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
AWS::ApiGateway::DomainName
LogicalId: ApiGatewayDomainName<sha>
<sha> is a unique hash value that is generated when the stack is created. For example:
ApiGatewayDomainName926eeb5ff1.
AWS::ApiGateway::UsagePlan
LogicalId: <api‑LogicalId>UsagePlan
LogicalId: <api‑LogicalId>UsagePlanKey
LogicalId: <api‑LogicalId>ApiKey
AWS::Lambda::Function
LogicalId: <function‑LogicalId>
Referenceable property: N/A (you must use the LogicalId to reference this AWS CloudFormation
resource)
Scenarios
165
AWS Serverless Application Model Developer Guide
AWS::Serverless::Function
AWS::Lambda::Alias
LogicalId: <function‑LogicalId>Alias<alias‑name>
<alias‑name> is the string that AutoPublishAlias is set to. For example, if you set
AutoPublishAlias to live, the LogicalId is: MyFunctionAliaslive.
LogicalId: <function‑LogicalId>Version<sha>
<sha> is a unique hash value that is generated when the stack is created. For example,
MyFunctionVersion926eeb5ff1.
AWS::IAM::Role
LogicalId: <function‑LogicalId>Role
Referenceable property: N/A (you must use the LogicalId to reference this AWS CloudFormation
resource)
AWS::Lambda::EventInvokeConfig
LogicalId: <function‑LogicalId>EventInvokeConfig
Referenceable property: N/A (you must use the LogicalId to reference this AWS CloudFormation
resource)
166
AWS Serverless Application Model Developer Guide
AWS::Serverless::HttpApi
AWS::SNS::Topic
If both OnSuccess and OnFailure are specified for an Amazon SNS event, to distinguish between
the generated resources, you must use the LogicalId.
AWS::Lambda::EventInvokeConfig
LogicalId: <function‑LogicalId>EventInvokeConfig
Referenceable property: N/A (you must use the LogicalId to reference this AWS CloudFormation
resource)
AWS::SQS::Queue
If both OnSuccess and OnFailure are specified for an Amazon SQS event, to distinguish between
the generated resources, you must use the LogicalId.
AWS::ApiGatewayV2::Api
LogicalId: <httpapi‑LogicalId>
Referenceable property: N/A (you must use the LogicalId to reference this AWS CloudFormation
resource)
Scenarios
• StageName property is specified (p. 168)
• StageName property is not specified (p. 168)
• DomainName property is specified (p. 168)
167
AWS Serverless Application Model Developer Guide
API Gateway extensions
AWS::ApiGatewayV2::Stage
LogicalId: <httpapi‑LogicalId><stage‑name>Stage
<stage‑name> is the string that the StageName property is set to. For example, if you set
StageName to Gamma, the LogicalId is: MyHttpApiGammaStage.
AWS::ApiGatewayV2::Stage
LogicalId: <httpapi‑LogicalId>ApiGatewayDefaultStage
AWS::ApiGatewayV2::DomainName
LogicalId: ApiGatewayDomainNameV2<sha>
<sha> is a unique hash value that is generated when the stack is created. For example,
ApiGatewayDomainNameV2926eeb5ff1.
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
168
AWS Serverless Application Model Developer Guide
API Gateway extensions
x-amazon-apigateway-documentation Object No
x-amazon-apigateway-endpoint-configuration Object No
x-amazon-apigateway-integration.requestParameters Object No
x-amazon-apigateway-request-validator Property No
x-amazon-apigateway-request-validators Object No
x-amazon-apigateway-request-validators.requestValidator Object No
169
AWS Serverless Application Model Developer Guide
Validating AWS SAM template files
This section contains topics about validating your AWS SAM template and building your application with
dependencies. It also contains topics about using AWS SAM for certain use cases such as working with
Lambda layers, using nested applications, controlling access to API Gateway APIs, orchestrating AWS
resources with Step Functions, and code signing your applications.
Topics
• Validating AWS SAM template files (p. 170)
• Working with layers (p. 170)
• Using nested applications (p. 172)
• Controlling access to API Gateway APIs (p. 174)
• Orchestrating AWS resources with AWS Step Functions (p. 182)
• Configuring code signing for AWS SAM applications (p. 183)
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 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:
170
AWS Serverless Application Model Developer Guide
Working with layers
- <LayerVersion ARN>
For more information about including layers in your application, see AWS::Serverless::Function (p. 65).
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
Directory name = myLayer-1-926eeb5ff1
To compute the unique layers hash, combine all unique layer names with a delimiter of '-', take the
SHA256 hash, and then take the first 10 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 '-':
171
AWS Serverless Application Model Developer Guide
Using nested applications
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,
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.
To define a nested application in your serverless application, use the AWS::Serverless::Application (p. 61)
resource type.
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.
172
AWS Serverless Application Model Developer Guide
Defining a nested application from the local file system
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:
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
173
AWS Serverless Application Model Developer Guide
Deploying nested applications
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.
AWS SAM supports several mechanisms for controlling access to your API Gateway APIs. The set of
supported mechanisms differs between AWS::Serverless::HttpApi and AWS::Serverless::Api
resource types.
The following table summarizes the mechanisms that each resource type supports.
Lambda authorizers ✓ ✓
IAM permissions ✓
API keys ✓
Resource policies ✓
* You can use Amazon Cognito as a JSON Web Token (JWT) issuer with the
AWS::Serverless::HttpApi resource type.
174
AWS Serverless Application Model Developer Guide
Controlling access to APIs
is invoked with a request context or an authorization token that the client application provides. The
Lambda function responds whether the caller is authorized to perform the requested operation.
For more information about Lambda authorizers with AWS::Serverless::HttpApi, see Working
with AWS Lambda authorizers for HTTP APIs in the API Gateway Developer Guide. For more information
about Lambda authorizers with AWS::Serverless::Api, see Use API Gateway Lambda authorizers
in the API Gateway Developer Guide.
For examples of Lambda authorizers for either resource type, see Lambda authorizer
examples (p. 176).
• IAM permissions – You can control who can invoke your API using AWS Identity and Access
Management (IAM) permissions. Users calling your API must be authenticated with IAM credentials.
Calls to your API succeed only 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 the user assumes.
For more information, see Control access to an API with IAM permissions in the API Gateway Developer
Guide. For an example, see IAM permission example (p. 178).
• Amazon Cognito user pools – Amazon Cognito user pools are user directories in Amazon Cognito. A
client of your API must first sign in a user to the user pool and obtain an identity or access token for
the user. Then the client calls your API with one of the returned tokens. The API call succeeds only if
the required token is valid.
The AWS::Serverless::Api resource type supports Amazon Cognito user pools. The
AWS::Serverless::HttpApi resource type supports the use of Amazon Cognito as a JWT issuer.
For more information, see Control access to a REST API using Amazon Cognito user pools as authorizer
in the API Gateway Developer Guide. For an example, see Amazon Cognito user pool example (p. 179).
• 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 Creating and using usage plans with API keys in the API
Gateway Developer Guide. For an example of API keys, see API key example (p. 180).
• Resource policies – Resource policies are JSON policy documents that you can attach to an API
Gateway API. Use resource policies to control whether a specified principal (typically an IAM user or
role) can invoke the API.
Only the AWS::Serverless::Api resource type supports resource policies as a mechanism for
controlling access to API Gateway APIs.
For more information about resource policies, see Controlling access to an API with API Gateway
resource policies in the API Gateway Developer Guide. For an example of resource policies, see Resource
policy example (p. 180).
• OAuth 2.0/JWT authorizers – You can use JWTs as a part of OpenID Connect (OIDC) and OAuth 2.0
frameworks to control access to your APIs. API Gateway validates the JWTs that clients submit with API
requests, and allows or denies requests based on token validation and, optionally, scopes in the token.
For more information, see Controlling access to HTTP APIs with JWT authorizers in the API Gateway
Developer Guide. For an example, see OAuth 2.0/JWT authorizer example (p. 181).
175
AWS Serverless Application Model Developer Guide
Choosing a mechanism to control access
However, if your application already has authentication set up, then using Lambda authorizers might
be your 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.
When you've chosen which mechanism to use, see the corresponding section in Examples (p. 176) for
how to use AWS SAM to configure your application to use that mechanism.
For more information about API Gateway responses, see Gateway responses in API Gateway in the
API Gateway Developer Guide. For an example of customized responses, see Customized response
example (p. 182).
Examples
• Lambda authorizer examples (p. 176)
• IAM permission example (p. 178)
• Amazon Cognito user pool example (p. 179)
• API key example (p. 180)
• Resource policy example (p. 180)
• OAuth 2.0/JWT authorizer example (p. 181)
• Customized response example (p. 182)
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
176
AWS Serverless Application Model Developer Guide
Lambda authorizer examples
Authorizers:
MyLambdaTokenAuthorizer:
FunctionArn: !GetAtt MyAuthFunction.Arn
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: index.handler
Runtime: nodejs12.x
Events:
GetRoot:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: get
MyAuthFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: authorizer.handler
Runtime: nodejs12.x
For more information about Lambda authorizers, see Use API Gateway Lambda authorizers in the API
Gateway Developer Guide.
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: nodejs12.x
Events:
GetRoot:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: get
177
AWS Serverless Application Model Developer Guide
IAM permission example
MyAuthFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: authorizer.handler
Runtime: nodejs12.x
For more information about Lambda authorizers, see Use API Gateway Lambda authorizers in the API
Gateway Developer Guide.
The following is an example AWS SAM template section for a Lambda authorizer:
Resources:
MyApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: Prod
Auth:
DefaultAuthorizer: MyLambdaRequestAuthorizer
Authorizers:
MyLambdaRequestAuthorizer:
FunctionArn: !GetAtt MyAuthFunction.Arn
FunctionInvokeRole: !GetAtt MyAuthFunctionRole.Arn
Identity:
Headers:
- Authorization
AuthorizerPayloadFormatVersion: 2.0
EnableSimpleResponses: true
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: index.handler
Runtime: nodejs12.x
Events:
GetRoot:
Type: HttpApi
Properties:
ApiId: !Ref MyApi
Path: /
Method: get
PayloadFormatVersion: "2.0"
MyAuthFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: authorizer.handler
Runtime: nodejs12.x
178
AWS Serverless Application Model Developer Guide
Amazon Cognito user pool 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: nodejs12.x
Events:
GetRoot:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: get
For more information about IAM permissions, see Control access to an API with IAM permissions in the
API Gateway Developer Guide.
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
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Handler: lambda.handler
Runtime: nodejs12.x
Events:
Root:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: GET
MyCognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
179
AWS Serverless Application Model Developer Guide
API key example
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.
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: nodejs12.x
Events:
ApiKey:
Type: Api
Properties:
RestApiId: !Ref MyApi
Path: /
Method: get
Auth:
ApiKeyRequired: true
For more information about API keys, see Creating and using usage plans with API keys in the API
Gateway Developer Guide.
The following is an example AWS SAM template section for resource policies:
180
AWS Serverless Application Model Developer Guide
OAuth 2.0/JWT authorizer example
Resources:
ExplicitApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
EndpointConfiguration: PRIVATE
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 Controlling access to an API with API Gateway resource
policies in the API Gateway Developer Guide.
The following is an example AWS SAM template section for an OAuth 2.0/JWT authorizer:
Resources:
MyApi:
Type: AWS::Serverless::HttpApi
Properties:
Auth:
Authorizers:
MyOauth2Authorizer:
AuthorizationScopes:
- scope
IdentitySource: $request.header.Authorization
JwtConfiguration:
audience:
- audience1
- audience2
issuer: "https://www.example.com/v1/connect/oidc"
DefaultAuthorizer: MyOauth2Authorizer
StageName: Prod
MyFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: ./src
Events:
GetRoot:
Properties:
181
AWS Serverless Application Model Developer Guide
Customized response example
ApiId: MyApi
Method: get
Path: /
PayloadFormatVersion: "2.0"
Type: HttpApi
Handler: index.handler
Runtime: nodejs12.x
For more information about OAuth 2.0/JWT authorizers, see Controlling access to HTTP APIs with JWT
authorizers 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: nodejs12.x
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 API Gateway responses, see Gateway responses in API Gateway in the API
Gateway Developer Guide.
182
AWS Serverless Application Model Developer Guide
Example
Step Functions is based on the concepts of tasks and state machines. You define state machines using
the JSON-based Amazon States Language. The Step Functions console displays a graphical view of your
state machine's structure so you can visually check your state machine's logic and monitor executions.
With Step Functions support in AWS Serverless Application Model (AWS SAM), you can do the following:
• Define state machines, either directly within an AWS SAM template or in a separate file
• Create state machine execution roles through AWS SAM policy templates, inline policies, or managed
policies
• Trigger state machine executions with API Gateway or Amazon EventBridge events, on a schedule
within an AWS SAM template, or by calling APIs directly
• Use available AWS SAM Policy Templates for common Step Functions development patterns.
Example
The following example snippet from a AWS SAM template file defines a Step Functions state machine in
a definition file. Note that the my_state_machine.asl.json file must be written in Amazon States
Language.
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM template with Step Functions State Machine
Resources:
MyStateMachine:
Type: AWS::Serverless::StateMachine
Properties:
DefinitionUri: statemachine/my_state_machine.asl.json
...
To download a sample AWS SAM application that includes a Step Functions state machine, see Create a
Step Functions State Machine Using AWS SAM in the AWS Step Functions Developer Guide.
More information
To learn more about Step Functions and using it with AWS SAM, see the following:
Before you can configure code signing for your serverless application, you must create a signing profile
using AWS Signer. You use this signing profile for the following tasks:
183
AWS Serverless Application Model Developer Guide
Example
When you deploy a serverless application, Lambda performs validation checks on all functions that
you've enabled code signing for. Lambda also performs validation checks on any layers that those
functions depend on. For more information about Lambda's validation checks, see Signature validation in
the AWS Lambda Developer Guide.
Example
Creating a signing profile
To create a signing profile, run the following command:
If the previous command is successful, you see the signing profile's ARN returned. For example:
{
"arn": "arn:aws:signer:us-east-1:111122223333:/signing-profiles/MySigningProfile",
"profileVersion": "SAMPLEverx",
"profileVersionArn": "arn:aws:signer:us-east-1:111122223333:/signing-
profiles/MySigningProfile/SAMPLEverx"
}
The profileVersionArn field contains the ARN to use when you create the code signing configuration.
Resources:
HelloWorld:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.7
CodeSigningConfigArn: !Ref MySignedFunctionCodeSigningConfig
MySignedFunctionCodeSigningConfig:
Type: AWS::Lambda::CodeSigningConfig
Properties:
Description: "Code Signing for MySignedLambdaFunction"
AllowedPublishers:
SigningProfileVersionArns:
184
AWS Serverless Application Model Developer Guide
Providing signing profiles with sam deploy --guided
- MySigningProfile-profileVersionArn
CodeSigningPolicies:
UntrustedArtifactOnDeployment: "Enforce"
Signing both your function code and a layer that your function depends on, when packaging your
application:
185
AWS Serverless Application Model Developer Guide
Building applications
For example, you might want to locally test your application, or you might want to deploy your
application using the AWS SAM CLI. Both of these activities use the build artifacts of your application as
inputs.
This section shows you how to use the sam build (p. 223) command to build serverless applications
using AWS SAM. You have the option to build all functions and layers of your application, or individual
components of your application, like a specific function or layer.
Topics
• Building applications (p. 186)
• Building layers (p. 188)
• Building custom runtimes (p. 189)
Building applications
To build your serverless application, use the sam build (p. 223) command. This command also
gathers the build artifacts of your application's dependencies and places them in the proper format and
location for next steps, such as locally testing, packaging, and deploying.
You specify your application's dependencies in a manifest file, such as requirements.txt (Python) or
package.json (Node.js), or by using the Layers property of a function resource. The Layers property
contains a list of AWS Lambda layer resources that the Lambda function depends on.
The format of your application's build artifacts depends on each function's PackageType property. The
options for the PackageType property are:
• Zip – A .zip file archive, which contains your application code and its dependencies. If you package
your code as a .zip file archive, you must specify a Lambda runtime for your function.
• Image – A container image, which includes the base operating system, the runtime, and extensions, in
addition to your application code and its dependencies.
For more information about Lambda package types, see Lambda deployment packages in the AWS
Lambda Developer Guide.
If your Lambda function depends on packages that have natively compiled programs, use the --use-
container flag. The --use-container flag locally compiles your functions in a Docker container that
behaves like a Lambda environment, so they are in the right format when you deploy them to the AWS
Cloud.
See the Examples section later in this topic for an example of building a .zip file archive application.
186
AWS Serverless Application Model Developer Guide
Building a container image
• Dockerfile: The name of the Dockerfile associated with the Lambda function
• DockerContext: The location of the Dockerfile
• DockerTag: Optional tag to apply to the built image
• DockerBuildArgs: Build arguments for the build
Metadata:
Dockerfile: Dockerfile
DockerContext: ./hello_world
DockerTag: v1
To download a sample application that is configured with the Image package type, see Step 1:
Download a sample AWS SAM application in Tutorial: Deploying a Hello World application (p. 12). At
the prompt asking which package type you want to install, choose Image.
Examples
Example 1: .zip file archive
The following sam build commands build a .zip file archive:
# Run the build process inside a Docker container that functions like a Lambda environment
sam build --use-container
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
PackageType: Image
ImageConfig:
Command: ["app.lambda_handler"]
Metadata:
Dockerfile: Dockerfile
DockerContext: ./hello_world
DockerTag: v1
187
AWS Serverless Application Model Developer Guide
Building layers
FROM public.ecr.aws/lambda/python:3.8
Building layers
To build layers that you have declared in your AWS Serverless Application Model (AWS SAM) template
file, include a Metadata resource attribute section with a BuildMethod entry. Valid values for
BuildMethod are identifiers for an AWS Lambda runtime, or makefile.
If you specify makefile, provide the custom makefile, where you declare a build target of the
form build-layer-logical-id that contains the build commands for your layer. Your makefile
is responsible for compiling the layer if necessary, and copying the build artifacts into the proper
location required for subsequent steps in your workflow. The location of the makefile is specified by the
ContentUri property of the layer resource, and must be named Makefile.
Metadata:
BuildMethod: python3.6
Note
If you don't include the Metadata resource attribute section, AWS SAM doesn't build the
layer. Instead, it copies the build artifacts from the location specified in the CodeUri property
of the layer resource. For more information, see the ContentUri (p. 140) property of the
AWS::Serverless::LayerVersion resource type.
When you include the Metadata resource attribute section, you can use the sam build (p. 223)
command to build the layer, both as an independent object, or as a dependency of an AWS Lambda
function.
• As an independent object. You might want to build just the layer object, for example when you're
locally testing a code change to the layer and don't need to build your entire application. To build the
layer independently, specify the layer resource with the sam build layer-logical-id command.
• As a dependency of a Lambda function. When you include a layer's logical ID in the Layers property
of a Lambda function in the same AWS SAM template file, the layer is a dependency of that Lambda
function. When that layer also includes a Metadata resource attribute section with a BuildMethod
entry, you build the layer either by building the entire application with the sam build command or by
specifying the function resource with the sam build function-logical-id command.
Examples
Template example 1: Build a layer against the Python 3.6
runtime environment
The following example AWS SAM template builds a layer against the Python 3.6 runtime environment.
188
AWS Serverless Application Model Developer Guide
Building custom runtimes
Resources:
MyLayer:
Type: AWS::Serverless::LayerVersion
Properties:
ContentUri: my_layer
CompatibleRuntimes:
- python3.6
Metadata:
BuildMethod: python3.6 # Required to have AWS SAM build this layer
Resources:
MyLayer:
Type: AWS::Serverless::LayerVersion
Properties:
ContentUri: my_layer
CompatibleRuntimes:
- python3.8
Metadata:
BuildMethod: makefile
The following makefile contains the build target and commands that will be executed. Note that the
ContentUri property is set to my_layer, so the makefile must be located in the root of the my_layer
subdirectory, and the filename must be Makefile.
build-MyLayer:
mkdir -p "$(ARTIFACTS_DIR)/python"
cp *.py "$(ARTIFACTS_DIR)/python"
python -m pip install -r requirements.txt -t "$(ARTIFACTS_DIR)/python"
# Build the 'function-logical-id' resource and layers that this function depends on
sam build function-logical-id
# Build the entire application, including the layers that any function depends on
sam build
To build a custom runtime, declare the Metadata resource attribute with a BuildMethod: makefile
entry. You provide a custom makefile, where you declare a build target of the form build-function-
logical-id that contains the build commands for your runtime. Your makefile is responsible for
189
AWS Serverless Application Model Developer Guide
Examples
compiling the custom runtime if necessary, and copying the build artifacts into the proper location
required for subsequent steps in your workflow. The location of the makefile is specified by the CodeUri
property of the function resource, and must be named Makefile.
Examples
Example 1: Custom runtime for a function written in Rust
The following AWS SAM template declares a function that uses a custom runtime for a Lambda
function written in Rust, and instructs sam build to execute the commands for the build-
HelloRustFunction build target.
Resources:
HelloRustFunction:
Type: AWS::Serverless::Function
Properties:
FunctionName: HelloRust
Handler: bootstrap.is.real.handler
Runtime: provided
MemorySize: 512
CodeUri: .
Metadata:
BuildMethod: makefile
The following makefile contains the build target and commands that will be executed. Note that the
CodeUri property is set to ., so the makefile must be located in the project root directory (that is, the
same directory as the application's AWS SAM template file). The filename must be Makefile.
build-HelloRustFunction:
cargo build --release --target x86_64-unknown-linux-musl
cp ./target/x86_64-unknown-linux-musl/release/bootstrap $(ARTIFACTS_DIR)
For more information about setting up your development environment in order to execute the cargo
build command in the previous makefile, see the Rust Runtime for AWS Lambda blog post.
Resources:
HelloWorldFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.7
Metadata:
BuildMethod: makefile
The following makefile contains the build target and commands that will be executed. Note that
the CodeUri property is set to hello_world, so the makefile must be located in the root of the
hello_world subdirectory, and the filename must be Makefile.
build-HelloWorldFunction:
190
AWS Serverless Application Model Developer Guide
Examples
cp *.py $(ARTIFACTS_DIR)
cp requirements.txt $(ARTIFACTS_DIR)
python -m pip install -r requirements.txt -t $(ARTIFACTS_DIR)
rm -rf $(ARTIFACTS_DIR)/bin
191
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. 192)
• Running API Gateway locally (p. 194)
• Integrating with automated tests (p. 197)
• Generating sample event payloads (p. 198)
• Step-through debugging Lambda functions locally (p. 198)
• Passing additional runtime debug arguments (p. 204)
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:
192
AWS Serverless Application Model Developer Guide
Environment Variable File
193
AWS Serverless Application Model Developer Guide
Layers
{
"MyFunction1": {
"TABLE_NAME": "localtable",
"BUCKET_NAME": "testBucket"
},
"MyFunction2": {
"TABLE_NAME": "localtable",
"STAGE": "dev"
}
}
Alternatively, your environment file can contain a single Parameters entry with the environment
variables for all functions. Note that you can't mix this format with the example above.
{
"Parameters": {
"TABLE_NAME": "localtable",
"BUCKET_NAME": "testBucket",
"STAGE": "dev"
}
}
Save your environment variables in a file named env.json. The following command uses this file to
override the included environment variables:
Layers
If your application includes layers, see Working with layers (p. 170) for more information about how to
debug layers issues on your local host.
You must execute sam local start-api in the project directory containing the function you want to
invoke.
By default, AWS SAM uses Lambda proxy integrations, and supports both HttpApi and Api resource
types. For more information about proxy integrations for HttpApi resource types, see Working with
Lambda proxy integrations for HTTP APIs. For more information about proxy integrations with Api
resource types, see Understand API Gateway Lambda proxy integration.
Example:
AWS SAM automatically finds any functions within your AWS SAM template that have HttpApi or Api
event sources defined. Then, it mounts them at the defined HTTP paths.
194
AWS Serverless Application Model Developer Guide
Running API Gateway locally
This animation shows running API Gateway locally using Microsoft Visual Studio Code:
In the following Api example, the Ratings function mounts ratings.py:handler() at /ratings
for GET requests:
Ratings:
Type: AWS::Serverless::Function
Properties:
195
AWS Serverless Application Model Developer Guide
Layers
Handler: ratings.handler
Runtime: python3.6
Events:
Api:
Type: Api
Properties:
Path: /ratings
Method: get
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.
You can structure the file as follows:
{
"MyFunction1": {
"TABLE_NAME": "localtable",
"BUCKET_NAME": "testBucket"
},
"MyFunction2": {
"TABLE_NAME": "localtable",
"STAGE": "dev"
},
}
Alternatively, your environment file can contain a single Parameters entry with the environment
variables for all functions. Note that you can't mix this format with the example above.
{
"Parameters": {
"TABLE_NAME": "localtable",
"BUCKET_NAME": "testBucket",
"STAGE": "dev"
}
}
Save your environment variables in a file named env.json. The following command uses this file to
override the included environment variables:
Layers
If your application includes layers, see Working with layers (p. 170) for more information about how to
debug layers issues on your local host.
196
AWS Serverless Application Model Developer Guide
Integrating with 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
197
AWS Serverless Application Model Developer Guide
Generating sample event payloads
# locally if it is configured to do so
response = lambda_client.invoke(FunctionName="HelloWorldFunction")
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:
198
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.
199
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": [
200
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()
201
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
202
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"
203
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:
204
AWS Serverless Application Model Developer Guide
Deploying using the AWS SAM CLI
You can deploy your application using AWS SAM command line interface (CLI) commands. To automate
your deployments, you can also use other AWS services that integrate with AWS SAM.
The standard inputs to deploying serverless applications are the build artifacts created using the
sam build (p. 223) command. For more information about sam build, see Building serverless
applications (p. 186).
If you want AWS SAM to guide you through the deployment with prompts, specify the --guided flag.
When you specify this flag, the sam deploy command zips your application artifacts, uploads them
to either Amazon S3 (for .zip file archives) or Amazon ECR (for contain images), and then deploys your
application to the AWS Cloud.
Example:
Automating deployments
To automate the deployment process of your serverless application, you can use AWS SAM with a
number of other AWS services.
• CodeBuild: Use AWS CodeBuild to build, locally test, and package your serverless application. For more
information, see What is AWS CodeBuild? in the AWS CodeBuild User Guide.
• CodeDeploy: Use AWS CodeDeploy to gradually deploy updates to your serverless applications. For
more information, see Deploying serverless applications gradually (p. 206).
• CodePipeline: Use AWS CodePipeline to model, visualize, and automate the steps that are required to
release your serverless application. For more information, see What is AWS CodePipeline? in the AWS
CodePipeline User Guide.
205
AWS Serverless Application Model Developer Guide
Troubleshooting
Troubleshooting
AWS SAM CLI error: "Security Constraints Not
Satisfied"
When executing sam deploy --guided, you are prompted with the question HelloWorldFunction
may not have authorization defined, Is this okay? [y/N]. If you respond to this prompt
with "N" (the default response), you see the following error:
The prompt is informing you that the application you're about to deploy may have an API Gateway API
configured without authorization. By responding "N" to this prompt (the default), you are saying that this
is not OK.
• Configure your application with authorization. For information about configuring authorization, see
Controlling access to API Gateway APIs (p. 174).
• Respond to this question with "Y" to indicate that you are OK with deploying an application that has
an API Gateway API configured without authorization.
• 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
206
AWS Serverless Application Model Developer Guide
Deploying gradually
Properties:
Handler: index.handler
Runtime: nodejs12.x
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
• 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
207
AWS Serverless Application Model Developer Guide
Deploying gradually
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.
208
AWS Serverless Application Model Developer Guide
Working with logs
Topics
• Working with logs (p. 209)
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:
209
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.
210
AWS Serverless Application Model Developer Guide
Prerequisites
The application that you want to publish must be one that you've defined using AWS SAM. You also need
to have tested it locally and/or in the AWS Cloud. The application's deployment package and AWS SAM
template are the inputs to the following procedure steps.
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. 214).
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
211
AWS Serverless Application Model Developer Guide
Publishing a new application
{
"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. 214).
sam package \
--template-file template.yaml \
212
AWS Serverless Application Model Developer Guide
Step 3: Publish the application
--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.
To update an application that you've previously published, you publish the application using the same
process as above. You provide the same application name that you originally published it with, but with
a new SemanticVersion value. You also provide the application name and SematicVersion number in the
Metadata section of the AWS SAM template file.
For example, if you published an application with the name SampleApp and SematicVersion 1.0.0,
to update that application, the AWS SAM template must have application name SampleApp, and the
SematicVersion can be 1.0.1 (or anything different from 1.0.0).
Additional topics
• AWS SAM template Metadata section properties (p. 214)
213
AWS Serverless Application Model Developer Guide
Metadata section 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])?$";
SpdxLicenseId String FALSE A valid license identifier. To view the list of valid license
identifiers, see SPDX License List on the Software
Package Data Exchange (SPDX) website.
214
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.
SemanticVersion String FALSE The semantic version of the application. For the
Semantic Versioning specification, see the Semantic
Versioning website.
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
215
AWS Serverless Application Model Developer Guide
Example
• 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
• 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
216
AWS Serverless Application Model Developer Guide
Process DynamoDB events
Topics
• Process DynamoDB events (p. 217)
• Process Amazon S3 events (p. 219)
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
Note that gh: in the command above gets expanded to the GitHub url https://github.com/.
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.
217
AWS Serverless Application Model Developer Guide
Step 3: Package the application
sam local generate-event dynamodb update | sam local invoke --event - ReadDynamoDBEvent
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.
218
AWS Serverless Application Model Developer Guide
Next steps
Next steps
The AWS SAM GitHub repository contains additional example applications for you to download and
experiment with. To access this repository, see AWS SAM example applications.
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/):
219
AWS Serverless Application Model Developer Guide
Step 2: Package the application
• 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.
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.
220
AWS Serverless Application Model Developer Guide
Step 4: Test the application locally
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.
• 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.
Next steps
The AWS SAM GitHub repository contains additional example applications for you to download and
experiment with. To access this repository, see AWS SAM example applications.
221
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
• AWS Serverless Application Model (AWS SAM) specification (p. 24)
• AWS SAM CLI command reference (p. 223)
• AWS SAM policy templates (p. 245)
• Telemetry in the AWS SAM CLI (p. 286)
• Permissions (p. 288)
222
AWS Serverless Application Model Developer Guide
AWS SAM CLI command reference
Topics
• sam build (p. 223)
• sam deploy (p. 225)
• sam init (p. 229)
• sam local generate-event (p. 231)
• sam local invoke (p. 233)
• sam local start-api (p. 234)
• sam local start-lambda (p. 236)
• sam logs (p. 238)
• sam package (p. 240)
• sam publish (p. 241)
• sam validate (p. 242)
sam build
Builds a serverless application, and prepares it for subsequent steps in your workflow, like locally testing
the application, or deploying it to the AWS Cloud.
The sam build command processes your AWS SAM template file, application code, and any applicable
language-specific files and dependencies, and copies build artifacts in the format and location expected
by subsequent steps in your workflow. You specify dependencies in a manifest file that you include in
your application, such as requirements.txt for Python functions, or package.json for Node.js
functions.
The format of your application's build artifacts depends on its package type. You specify your AWS
Lambda function's package type with the PackageType property. The options are:
• Zip – A .zip file archive, which contains your application code and its dependencies. If you package
your code as a .zip file archive, you must specify a Lambda runtime for your function.
• Image – A container image, which includes the base operating system, the runtime, and extensions, in
addition to your application code and its dependencies.
For more information about Lambda package types, see Lambda deployment packages in the AWS
Lambda Developer Guide.
If a resource includes a Metadata resource attribute with a BuildMethod entry, sam build builds that
resource according to the value of the BuildMethod entry. Valid values for BuildMethod are identifiers
for a Lambda runtime or makefile:
• Lambda runtime identifier. Build the resource against a Lambda runtime. For the list of supported
runtime identifiers, see AWS Lambda runtimes.
• makefile. You must have a makefile that includes a build target named build-resource-
logical-id. In this case, sam build executes the commands of the build target.
To build layers and custom runtimes, you can also use the Metadata resource attribute with a
BuildMethod entry. For information about building layers, see Building layers (p. 188). For information
about building custom runtimes, see Building custom runtimes (p. 189).
223
AWS Serverless Application Model Developer Guide
sam build
For serverless function resources that have the Image package type, use the Metadata resource
attribute to configure Docker image settings that are required to build a container image. For more
information about building container images, see Building applications (p. 186).
To see an end-to-end example that uses this command, including locally testing and deploying to the
AWS Cloud, see Tutorial: Deploying a Hello World application (p. 12). The sam build command is part
of Step 2: Build your application (p. 15).
Usage:
Examples:
To use this command, update your SAM template to specify the path
to your function's source code in the resource's Code or CodeUri property.
Options:
Option Description
-b, --build-dir The path to a folder where the built artifacts are stored. This directory
DIRECTORY and all of its content are removed with this option.
-s, --base-dir Resolves relative paths to the Lambda function's source code with
DIRECTORY respect to this folder. Use this option if the AWS SAM template and
your source code aren't in the same 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 a Lambda-like
Docker container.
-m, --manifest PATH The path to a custom dependency manifest file (for example,
package.json) to use instead of the default.
-t, --template-file, The path and file name of AWS SAM template file [default:
--template PATH template.[yaml|yml]].
224
AWS Serverless Application Model Developer Guide
sam deploy
Option Description
--skip-pull-image Specifies whether the command should skip pulling down the latest
Docker image for the Lambda runtime.
--docker-network TEXT Specifies the name or ID of an existing Docker network that Lambda
Docker containers should connect to, along with the default bridge
network. If not specified, the Lambda containers connect only to the
default bridge Docker network.
--parallel Enabled parallel builds. Use this flag to build your AWS SAM template's
functions and layers in parallel. By default, the functions and layers are
built in sequence.
--cached Enable cached builds. Use this flag to reuse build artifacts that have
not changed from previous builds. AWS SAM evaluates whether you
have made any changes to files in your project directory. Note: AWS
SAM does not evaluate whether changes have been made to third party
modules that your project depends on, where you have not provided
a specific version. For example, if your Python function includes a
requirements.txt file with the entry requests=1.x, and the latest
request module version changes from 1.1 to 1.2, AWS SAM does not
pull the latest version until you run a non-cached build.
--cache-dir The folder where the cache artifacts are stored when --cached is
specified. The default cache directory is .aws-sam/cache.
--profile TEXT The specific profile from your credential file that gets AWS credentials.
--region TEXT The AWS Region to deploy to. For example, us-east-1.
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
--debug Turns on debug logging to print debug messages that the AWS SAM CLI
generates, and to display timestamps.
sam deploy
Deploys an AWS SAM application.
This command 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 optionally saves these options in a configuration file in your project directory. When
you perform subsequent deployments of your application using sam deploy, the AWS SAM CLI retrieves
the required parameters from the configuration file.
Objects declared in the Parameters section of the AWS SAM template file appear as additional
interactive mode prompts. You're prompted to provide values for each parameter. For examples of these
225
AWS Serverless Application Model Developer Guide
sam deploy
objects and the corresponding prompts, see the Examples of additional interactive prompts section later
in this topic.
Serverless applications that you configure with code signing generate more interactive mode prompts.
You're asked whether you want your code to be signed, and if so, you're prompted to enter signing
profile names and owners. For examples of these prompts, see the Examples of additional interactive
prompts section later in this topic.
For more information about settings that are optionally stored when specifying the --guided
parameter, see AWS SAM CLI configuration file (p. 243).
Deploying AWS Lambda functions through AWS CloudFormation requires an Amazon Simple Storage
Service (Amazon S3) bucket for the Lambda deployment package. The AWS SAM CLI creates and
manages this Amazon S3 bucket for you.
Usage:
Options:
Option Description
-g, --guided Specify this flag to have AWS SAM use prompts to guide you through the
deployment.
-t, --template-file, The path and file name where your AWS SAM template is located.
--template PATH Default: template.[yaml|yml].
--stack-name TEXT (Required) The name of the AWS CloudFormation stack that 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.
--s3-bucket TEXT The URI of the Amazon S3 bucket where this command uploads your
AWS CloudFormation template. This is required to deploy templates that
are larger than 51,200 bytes.
--s3-prefix TEXT The prefix added to the names of the artifacts that are uploaded to the
Amazon S3 bucket. The prefix name is a path name (folder name) for the
Amazon S3 bucket.
--image-repository The name of the Amazon Elastic Container Registry (Amazon ECR)
TEXT repository where this command uploads your function's image. Required
for functions declared with the Image package type.
--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
226
AWS Serverless Application Model Developer Guide
sam deploy
Option Description
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 operation returns an InsufficientCapabilities
error.
--region TEXT The AWS Region to deploy to. For example, us-east-1.
--profile TEXT The specific profile from your credential file that gets AWS credentials.
--kms-key-id TEXT The ID of an AWS Key Management Service (AWS KMS) key used to
encrypt artifacts that are at rest in the Amazon S3 bucket.
--force-upload Specify this flag to upload artifacts even if they match existing artifacts
in the Amazon S3 bucket. Matching artifacts are overwritten.
--no-execute- Indicates whether to execute the changeset. Specify this flag if you
changeset want to view your stack changes before executing the changeset. This
command creates an AWS CloudFormation changeset and then exits
without executing the changeset. To execute the changeset, run the
same command without this flag.
--role-arn TEXT The Amazon Resource Name (ARN) of an IAM role that AWS
CloudFormation assumes when executing the changeset.
--fail-on-empty- Specify whether to return a non-zero exit code if there are no changes to
changeset | --no- be made to the stack. The default behavior is to return a non-zero exit
fail-on-empty- code.
changeset
--confirm-changeset Prompt to confirm whether the AWS SAM CLI deploys the computed
| --no-confirm- changeset.
changeset
--use-json Output JSON for the AWS CloudFormation template. The default output
is YAML.
--notification-arns A list of Amazon Simple Notification Service (Amazon SNS) topic ARNs
LIST that AWS CloudFormation associates with the stack.
--tags LIST 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.
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
227
AWS Serverless Application Model Developer Guide
sam deploy
Option Description
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
--no-progressbar Do not display a progress bar when uploading artifacts to Amazon S3.
--debug Turns on debug logging to print debug message generated by the AWS
SAM CLI and display timestamps.
Examples
Parameters
Here is an example object declared in the Parameters section, and the corresponding prompt that
appears when using sam deploy --guided.
Parameters:
MyPar:
Type: String
Default: MyParVal
Code signing
Here is an example function configured with code signing.
Resources:
HelloWorld:
Type: AWS::Serverless::Function
Properties:
CodeUri: hello_world/
Handler: app.lambda_handler
Runtime: python3.7
CodeSigningConfigArn: arn:aws:lambda:us-east-1:111122223333:code-signing-
config:csc-12e12345db1234567
228
AWS Serverless Application Model Developer Guide
sam init
#Signing profile details for layer 'MyLayer', which is used by functions {'HelloWorld'}
Signing Profile Name:
Signing Profile Owner Account ID (optional):
sam init
Initializes a serverless application with an AWS SAM template. The template provides a folder structure
for your AWS Lambda functions, and is connected to a event sources such as APIs, Amazon Simple
Storage Service (Amazon S3) buckets, or Amazon DynamoDB tables. This application includes everything
that you need to get started and to eventually extend it into a production-scale application.
For some sample applications, you can choose the package type of the application, either Zip or Image.
For more information about Lambda package types, see Lambda deployment packages in the AWS
Lambda Developer Guide.
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 are prompted for the additional required
information.
Examples:
Options:
229
AWS Serverless Application Model Developer Guide
sam init
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
file, path).
For Git repositories, you must use the location of the root of the
repository.
For local paths, the template must be in either .zip file or Cookiecutter
format.
--package-type [Zip | The package type of the example application. Zip creates a .zip file
Image] archive, and Image creates a container image.
-r, --runtime The Lambda runtime of your application. This option applies only when
[python2.7 | ruby2.5 the package type is Zip.
| ruby2.7 | java8
| python3.7 | This parameter is required if --no-interactive is specified, --image-
dotnetcore2.0 type is specified as Zip, and --location is not specified.
| nodejs10.x
| nodejs12.x |
dotnetcore2.1 |
dotnetcore1.0 |
python3.6 | go1.x]
--base-image [amazon/ The base image of your application. This option applies only when the
nodejs12.x-base | package type is Image.
amazon/nodejs10.x-
base | amazon/ This parameter is required if --no-interactive is specified, --image-
python3.8-base | type is specified as Image, and --location is not specified.
amazon/python3.7-base
| amazon/python3.6-
base | amazon/
python2.7-base |
amazon/ruby2.7-base
| amazon/ruby2.5-base
| amazon/go1.x-base |
amazon/java11-base |
amazon/java8.al2-base
| amazon/java8-base |
amazon/dotnetcore3.1-
base | amazon/
dotnetcore2.1-base]
-o, --output-dir PATH The location where the initialized application is output.
230
AWS Serverless Application Model Developer Guide
sam local generate-event
Option Description
--app-template TEXT The identifier of the managed application template that you want to
use. If you're not sure, call sam init without options for an interactive
workflow.
This parameter is available only in AWS SAM CLI version 0.30.0 and later.
Specifying this parameter with an earlier version results in an error.
--no-input Disables Cookiecutter prompting and accepts the vcfdefault values that
are defined in the template configuration.
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
--debug Turns on debug logging to print debug messages that the AWS SAM CLI
generates, and to display timestamps.
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:
231
AWS Serverless Application Model Developer Guide
sam local generate-event
# 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 -
e - <function logical id>
Options:
Option Description
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
Commands:
• alexa-skills-kit
• alexa-smart-home
• apigateway
• batch
• cloudformation
• cloudfront
• cloudwatch
• codecommit
• codepipeline
• cognito
• config
• dynamodb
• kinesis
• lex
• rekognition
• s3
• ses
• sns
• sqs
• stepfunctions
232
AWS Serverless Application Model Developer Guide
sam local invoke
This is useful for developing serverless functions that handle asynchronous events, such as Amazon
Simple Storage Service (Amazon S3) or Amazon Kinesis events. It can also be useful if you want to
compose a script of test cases. You can pass in the event body using the --event parameter. The
runtime output (for example, logs) is output to stderr, and the Lambda function result is output to
stdout.
AWS SAM CLI support for Lambda extensions (Preview)
To locally test a serverless application that uses Lambda extensions, set the
ENABLE_LAMBDA_EXTENSIONS_PREVIEW environment variable to "1". For example:
ENABLE_LAMBDA_EXTENSIONS_PREVIEW=1 sam local invoke
For more information about Lambda extensions, see Using AWS Lambda extensions in the AWS
Lambda Developer Guide.
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, no event is
assumed. To input JSON from stdin, you must pass in the value '-'.
-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
variable files, see Environment Variable File (p. 193).
-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 is mounted into the Lambda container.
-v, --docker-volume- The location of the base directory where the AWS SAM file exists. If
basedir 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.
233
AWS Serverless Application Model Developer Guide
sam local start-api
Option Description
-l, --log-file TEXT The log file to send runtime logs to.
--layer-cache-basedir Specifies the location basedir where the layers that your template uses
DIRECTORY are downloaded to.
--skip-pull-image Specifies whether the AWS SAM CLI should skip pulling down the latest
Docker image for the Lambda runtime.
--force-image-build Specifies whether the AWS SAM CLI should rebuild the image used for
invoking Lambda functions with layers.
--profile TEXT The specific profile from your credential file that gets AWS credentials.
--region TEXT The AWS Region to deploy to. For example, us-east-1.
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
--debug Turns on debug logging to print debug messages that the AWS SAM CLI
generates, and to display timestamps.
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.
To see an end-to-end example that uses this command, see Tutorial: Deploying a Hello World
application (p. 12). The sam local start-api command is part of Step 4: (Optional) Test your
application locally (p. 18).
AWS SAM CLI support for Lambda extensions (Preview)
To locally test a serverless application that uses Lambda extensions, set the
ENABLE_LAMBDA_EXTENSIONS_PREVIEW environment variable to "1". For example:
234
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.
--warm-containers Optional. Specifies how AWS SAM CLI manages containers for each
[EAGER | LAZY] function.
EAGER: Containers for all functions are loaded at startup and persist
between invocations.
LAZY: Containers are only loaded when each function is first invoked.
Those containers persist for additional invocations.
--debug-function Optional. Specifies the Lambda function to apply debug options to when
--warm-containers is specified. This parameter applies to --debug-
port, --debugger-path, and --debug-args.
-v, --docker-volume- The location of the base directory where the AWS SAM file exists. If
basedir 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
235
AWS Serverless Application Model Developer Guide
sam local start-lambda
Option Description
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.
--profile TEXT The specific profile from your credential file that gets AWS credentials.
--region TEXT The AWS Region to deploy to. For example, us-east-1.
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
--debug Turns on debug logging to print debug message generated by the AWS
SAM CLI and display timestamps.
Usage:
Examples:
# SETUP
236
AWS Serverless Application Model Developer Guide
sam local start-lambda
# ------
# 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.
-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.
--warm-containers Optional. Specifies how AWS SAM CLI manages containers for each
[EAGER | LAZY] function.
EAGER: Containers for all functions are loaded at startup and persist
between invocations.
237
AWS Serverless Application Model Developer Guide
sam logs
Option Description
LAZY: Containers are only loaded when each function is first invoked.
Those containers persist for additional invocations.
--debug-function Optional. Specifies the Lambda function to apply debug options to when
--warm-containers is specified. This parameter applies to --debug-
port, --debugger-path, and --debug-args.
-v, --docker-volume- The location of the base directory where the AWS SAM file exists. If
basedir 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.
--profile TEXT The specific profile from your credential file that gets AWS credentials.
--region TEXT The AWS Region to deploy to. For example, us-east-1.
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
--debug Turns on debug logging to print debug message generated by the AWS
SAM CLI and display timestamps.
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.
238
AWS Serverless Application Model Developer Guide
sam logs
Usage:
Examples:
# 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 The specific profile from your credential file that gets AWS credentials.
--region TEXT The AWS Region to deploy to. For example, us-east-1.
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
239
AWS Serverless Application Model Developer Guide
sam package
Option Description
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
--debug Turns on debug logging to print debug message generated by the AWS
SAM CLI and display timestamps.
sam package
Packages an AWS SAM application. This command creates a .zip file of your code and dependencies,
and uploads the file to Amazon Simple Storage Service (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. 225) now implicitly performs the functionality of sam package. You can use
the sam deploy (p. 225) command directly to package and deploy your application.
Usage:
Options:
Option Description
-t, --template-file, The path and file name where your AWS SAM template is located.
--template PATH Default: template.[yaml|yml].
--s3-bucket TEXT (Required) The name of the Amazon S3 bucket where this command
uploads your AWS CloudFormation template.
--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. This only applies for functions declared with Zip package type.
--image-repository The URI of the Amazon Elastic Container Registry (Amazon ECR)
TEXT repository where this command uploads your function's image. Required
for functions declared with the Image package type.
--kms-key-id TEXT The ID of an AWS Key Management Service (AWS KMS) key used to
encrypt artifacts that are at rest in the Amazon S3 bucket.
--output-template- The path to the file where the command writes the packaged template.
file PATH If you don't specify a path, the command writes the template to the
standard output.
240
AWS Serverless Application Model Developer Guide
sam publish
Option Description
--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.
--profile TEXT The specific profile from your credential file that gets AWS credentials.
--region TEXT The AWS Region to deploy to. For example, us-east-1.
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
--no-progressbar Do not display a progress bar when uploading artifacts to Amazon S3.
--debug Turns on debug logging to print debug message generated by the AWS
SAM CLI and display timestamps.
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. 211).
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
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. 211).
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:
241
AWS Serverless Application Model Developer Guide
sam validate
Examples:
# To publish an application
sam publish --template packaged.yaml --region us-east-1
Options:
Option Description
--profile TEXT The specific profile from your credential file that gets AWS credentials.
--region TEXT The AWS Region to deploy to. For example, us-east-1.
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
--debug Turns on debug logging to print debug message generated by the AWS
SAM CLI and display timestamps.
sam validate
Verifies whether an AWS SAM template file is valid.
Usage:
Options:
Option Description
--profile TEXT The specific profile from your credential file that gets AWS credentials.
--region TEXT The AWS Region to deploy to. For example, us-east-1.
--config-file PATH The path and file name of the configuration file containing default
parameter values to use. The default value is "samconfig.toml" in the
root of the project directory. For more information about configuration
files, see AWS SAM CLI configuration file (p. 243).
242
AWS Serverless Application Model Developer Guide
AWS SAM CLI configuration file
Option Description
--config-env TEXT The environment name specifying the default parameter values in
the configuration file to use. The default value is "default". For more
information about configuration files, see AWS SAM CLI configuration
file (p. 243).
--debug Turns on debug logging to print debug message generated by the AWS
SAM CLI and display timestamps.
You can manually edit this file to set default parameters for any AWS SAM CLI command.
In addition, the sam deploy --guided command writes a subset of parameters to your configuration
file. For more details about this functionality, see Writing configurations with sam deploy --
guided (p. 244) later in this topic.
Example
Here is an example configuration file that contains seven parameters for the default environment and
the deploy command:
version=0.1
[default.deploy.parameters]
stack_name = "my-app-stack"
s3_bucket = "my-source-bucket"
s3_prefix = "my-s3-prefix"
region = "us-west-2"
confirm_changeset = true
capabilities = "CAPABILITY_IAM"
tags = "project=\"my-application\" stage=\"production\""
Tables
• The AWS SAM CLI uses TOML tables to group configuration entries by environment and command.
243
AWS Serverless Application Model Developer Guide
Writing configurations with sam deploy --guided
• The format of the table header is [environment.command.parameters]. For example, for the sam
deploy command, the configuration table header is [default.deploy.parameters].
• For subcommands, the format of the table header is
[environment.command_subcommand.parameters]. That is, delimit the command and
subcommand with _ (underscore). For example, for the sam local invoke command, the
configuration table header is [default.local_invoke.parameters].
• If any command or subcommand contains a - (hyphen) character, replace it with with _ (underscore).
For example, for the sam local start-api command, the configuration table header is
[default.local_start_api.parameters].
• The default environment name is default. You can override the default environment name using the
--config-env parameter.
• A single configuration file can contain tables for multiple environments and multiple commands/
subcommands.
Configuration entries
• Each configuration entry is a TOML key-value pair.
• The configuration key is the long-form parameter name with the - (hyphen) character replaced with _
(underscore). For the list of available parameters for each command, see the AWS SAM CLI command
reference (p. 223), or run sam command --help.
• The configuration value can take the following forms:
• For parameters that take an argument, the entry value is the argument surrounded by double
quotes. For example, region = "us-west-2".
• For multiple arguments, the arguments are space-delimited within double quotes. For example,
capabilities = "CAPABILITY_IAM CAPABILITY_NAMED_IAM".
• For arguments that are key-value pairs, the pairs are space-delimited and value of each pair is
surrounded by encoded double quotes. For example, tags = "project=\"my-application\"
stage=\"production\"".
• For toggle parameters, the value can be true or false (no quotes). For example,
confirm_changeset = true.
Precedence
• Parameter values that you provide on the command line take precedence over corresponding entries
in the configuration file. For example, if your configuration file contains the entry stack_name =
"DefaultStack" and you run the command sam deploy --stack-name MyCustomStack, then
the deployed stack name is MyCustomStack.
• For the parameter_overrides entry, both the parameter values that you provide on the command
line and entries in the configuration file take precedence over corresponding objects declared in the
Parameters section of the template file.
These prompts include the question "Save arguments to samconfig.toml [Y/n]:". If you
respond Y to this prompt, the AWS SAM CLI updates the configuration file with values for the following
parameters:
• stack_name
244
AWS Serverless Application Model Developer Guide
AWS SAM policy templates
• s3_bucket
• s3_prefix
• image_repository
• region
• confirm_changeset
• capabilities
• signing_profiles
• parameter_overrides
If you've previously written a configuration file, the AWS SAM CLI reads it and uses those parameter
values as the default values for the corresponding prompts. If you specify values on the command line
for any of these parameters, the AWS SAM CLI uses those values as the default values.
To set any parameter other than those previously listed, you must manually edit the configuration file.
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.
Syntax
For every policy template you specify in your AWS SAM template file, you must always specify an
object containing the policy template's placeholder values. If a policy template does not require any
placeholder values, you must specify an empty object.
YAML
MyFunction:
Type: AWS::Serverless::Function
Properties:
Policies:
- PolicyTemplateName1: # Policy template with placeholder value
Key1: Value1
- PolicyTemplateName2: {} # Policy template with no placeholder value
245
AWS Serverless Application Model Developer Guide
Examples
Examples
Example 1: Policy template with placeholder values
The following example shows that the SQSPollerPolicy (p. 251) policy template expects a QueueName
as a resource. The AWS SAM template retrieves the name of the "MyQueue" Amazon SQS queue, which
you can create in the same application or requested as a parameter to the application.
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:
- CloudWatchPutMetricPolicy: {}
SQSPollerPolicy (p.Gives
251) permission to poll an Amazon Simple
Queue Service (Amazon SQS) queue.
LambdaInvokePolicy
Gives
(p. 251)
permission to invoke an AWS Lambda
function, alias, or version.
CloudWatchDescribeAlarmHistoryPolicy
Gives permission to describe
(p. 252)CloudWatch
alarm history.
CloudWatchPutMetricPolicy
Gives permission
(p. 252) to send metrics to
CloudWatch.
246
AWS Serverless Application Model Developer Guide
Policy template table
EC2DescribePolicy (p.
Gives
252)
permission to describe Amazon Elastic
Compute Cloud (Amazon EC2) instances.
DynamoDBCrudPolicy
Gives
(p.create,
252) read, update, and delete
permissions to an Amazon DynamoDB table.
DynamoDBReadPolicy
Gives(p.read-only
253) permission to a DynamoDB
table.
DynamoDBWritePolicy
Gives(p.write-only
254) permission to a DynamoDB
table.
DynamoDBReconfigurePolicy
Gives permission
(p. 255)to reconfigure a DynamoDB
table.
SESSendBouncePolicy
Gives
(p.SendBounce
255) permission to an Amazon
Simple Email Service (Amazon SES) identity.
ElasticsearchHttpPostPolicy
Gives POST(p. permission
255) to Amazon
Elasticsearch Service.
AMIDescribePolicy (p.
Gives
258)
permission to describe Amazon
Machine Images (AMIs).
CloudFormationDescribeStacksPolicy
Gives permission to(p.describe
258) AWS
CloudFormation stacks.
RekognitionDetectOnlyPolicy
Gives permission
(p. 259)
to detect faces, labels, and
text.
RekognitionNoDataAccessPolicy
Gives permission
(p. 259)
to compare and detect faces
and labels.
RekognitionReadPolicy
Gives(p.permission
259) to list and search faces.
RekognitionWriteOnlyAccessPolicy
Gives permission(p.
to260)
create collection and
index faces.
SQSSendMessagePolicy
Gives(p.
permission
260) to send message to an
Amazon SQS queue.
SNSPublishMessagePolicy
Gives permission
(p. 261) to publish a message to an
Amazon Simple Notification Service (Amazon
SNS) topic.
VPCAccessPolicy (p.Gives
261) access to create, delete, describe, and
detach elastic network interfaces.
247
AWS Serverless Application Model Developer Guide
Policy template table
DynamoDBStreamReadPolicy
Gives permission
(p. 261)
to describe and read
DynamoDB streams and records.
KinesisStreamReadPolicy
Gives permission
(p. 262) to list and read an Amazon
Kinesis stream.
KinesisCrudPolicy (p.
Gives
264)permission to create, publish, and
delete an Amazon Kinesis stream.
KMSDecryptPolicy (p.
Gives
264)
permission to decrypt with an AWS Key
Management Service (AWS KMS) key.
KMSEncryptPolicy (p.
Gives
265)
permission to encrypt with an AWS Key
Management Service (AWS KMS) key.
PollyFullAccessPolicy
Gives
(p. 265)
full access permission to Amazon Polly
lexicon resources.
S3FullAccessPolicy Gives
(p. 266)
full access permission to act on the
objects in an Amazon S3 bucket.
CodePipelineLambdaExecutionPolicy
Gives permission for
(p.a267)
Lambda function
invoked by CodePipeline to report the status
of the job.
ServerlessRepoReadWriteAccessPolicy
Gives permission to(p.
create
267)and list
applications in the AWS Serverless
Application Repository service.
EC2CopyImagePolicy
Gives
(p. 267)
permission to copy Amazon EC2
images.
AWSSecretsManagerRotationPolicy
Gives permission(p.
to 268)
rotate a secret in AWS
Secrets Manager.
AWSSecretsManagerGetSecretValuePolicy
Gives permission to get(p.
the269)
secret value for
the specified AWS Secrets Manager secret.
CodePipelineReadOnlyPolicy
Gives read(p.
permission
269) to get details about a
CodePipeline pipeline.
CloudWatchDashboardPolicy
Gives permissions
(p. 269) to put metrics to operate
on CloudWatch dashboards.
RekognitionFacesManagementPolicy
Gives permission to
(p.add,
270)delete, and search
faces in an Amazon Rekognition collection.
RekognitionFacesPolicy
Gives(p.
permission
270) to compare and detect faces
and labels.
RekognitionLabelsPolicy
Gives (p.
permission
270) to detect object and
moderation labels.
248
AWS Serverless Application Model Developer Guide
Policy template table
DynamoDBBackupFullAccessPolicy
Gives read and write
(p. 271)
permission to
DynamoDB on-demand backups for a table.
DynamoDBRestoreFromBackupPolicy
Gives permission to(p.
restore
271) a DynamoDB
table from backup.
ComprehendBasicAccessPolicy
Gives permission
(p. 272)
for detecting entities, key
phrases, languages, and sentiments.
MobileAnalyticsWriteOnlyAccessPolicy
Gives write-only permission
(p. 273) to put event data
for all application resources.
PinpointEndpointAccessPolicy
Gives permission
(p. 273)
to get and update
endpoints for an Amazon Pinpoint
application.
FirehoseWritePolicyGives
(p. 273)
permission to write to a Kinesis Data
Firehose delivery stream.
FirehoseCrudPolicyGives
(p. 274)
permission to create, write, update,
and delete a Kinesis Data Firehose delivery
stream.
EKSDescribePolicy (p.
Gives
274)
permission to describe or list Amazon
EKS clusters.
CostExplorerReadOnlyPolicy
Gives read-only
(p. 274)
permission to the read-only
Cost Explorer APIs for billing history.
OrganizationsListAccountsPolicy
Gives read-only
(p.permission
275) to list child
account names and IDs.
SESBulkTemplatedCrudPolicy
Gives permission
(p. 275)
to send email, templated
email, templated bulk emails and verify
identity.
SESEmailTemplateCrudPolicy
Gives permission
(p. 276)
to create, get, list, update
and delete Amazon SES email templates.
FilterLogEventsPolicy
Gives
(p. permission
276) to filter CloudWatch Logs
events from a specified log group.
SSMParameterReadPolicy
Gives permission
(p. 276) to access a parameters
from an Amazon EC2 Systems Manager
(SSM) parameter store to load secrets in this
account.
StepFunctionsExecutionPolicy
Gives permission
(p. 277)
to start a Step Functions
state machine execution.
CodeCommitCrudPolicy
Gives(p.
permissions
277) to create/read/update/
delete objects within a specific CodeCommit
repository.
CodeCommitReadPolicy
Gives (p.
permissions
279) to read objects within a
specific CodeCommit repository.
AthenaQueryPolicyGives
(p. 280)
permissions to execute Athena queries.
249
AWS Serverless Application Model Developer Guide
Troubleshooting
TextractDetectAnalyzePolicy
Gives access
(p. to
281)
detect and analyze
documents with Amazon Textract.
TextractGetResultPolicy
Gives(p.
access
281)to get detected and analyzed
documents from Amazon Textract.
EventBridgePutEventsPolicy
Gives permissions
(p. 281) to send events to
EventBridge.
ElasticMapReduceModifyInstanceFleetPolicy
Gives permission to list details
(p. 282)
and modify
capacities for instance fleets within a cluster.
ElasticMapReduceSetTerminationProtectionPolicy
Gives permission to set termination
(p. 282)
protection for a cluster.
ElasticMapReduceModifyInstanceGroupsPolicy
Gives permission to list details
(p. and
282)modify
settings for instance groups within a cluster.
ElasticMapReduceCancelStepsPolicy
Gives permission to
(p.cancel
283) a pending step or
steps in a running cluster.
ElasticMapReduceTerminateJobFlowsPolicy
Gives permission to shut (p.
down283)
a cluster.
ElasticMapReduceAddJobFlowStepsPolicy
Gives permission to add(p.
new284)
steps to a
running cluster.
SageMakerCreateEndpointPolicy
Gives permission
(p. 284)
to create an endpoint in
SageMaker.
SageMakerCreateEndpointConfigPolicy
Gives permission to create
(p. 285)
an endpoint
configuration in SageMaker.
EcsRunTaskPolicy (p.
Gives
285)permission to start a new task for a
task definition.
EFSWriteAccessPolicy
Gives
(p. permission
285) to mount an Amazon EFS
file system with write access.
Troubleshooting
SAM CLI error: "Must specify valid parameter values for policy
template '<policy-template-name>'"
When executing sam build, you see the following error:
This means that you did not pass an empty object when declaring a policy template that does not have
any placeholder values.
To fix this, declare the policy like the following example for CloudWatchPutMetricPolicy (p. 252).
250
AWS Serverless Application Model Developer Guide
Policy template list
MyFunction:
Policies:
- CloudWatchPutMetricPolicy: {}
SQSPollerPolicy
Gives permission to poll an Amazon Simple Queue Service (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 an AWS 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"
}
}
251
AWS Serverless Application Model Developer Guide
Policy template list
]
}
}
]
CloudWatchDescribeAlarmHistoryPolicy
Gives permission to describe Amazon CloudWatch alarm history.
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudwatch:DescribeAlarmHistory"
],
"Resource": "*"
}
]
CloudWatchPutMetricPolicy
Gives permission to send metrics to CloudWatch.
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudwatch:PutMetricData"
],
"Resource": "*"
}
]
EC2DescribePolicy
Gives permission to describe Amazon Elastic Compute Cloud (Amazon EC2) instances.
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeRegions",
"ec2:DescribeInstances"
],
"Resource": "*"
}
]
DynamoDBCrudPolicy
Gives create, read, update, and delete permissions to an Amazon DynamoDB table.
252
AWS Serverless Application Model Developer Guide
Policy template list
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:GetItem",
"dynamodb:DeleteItem",
"dynamodb:PutItem",
"dynamodb:Scan",
"dynamodb:Query",
"dynamodb:UpdateItem",
"dynamodb:BatchWriteItem",
"dynamodb:BatchGetItem",
"dynamodb:DescribeTable",
"dynamodb:ConditionCheckItem"
],
"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"
}
}
]
}
]
}
]
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": [
253
AWS Serverless Application Model Developer Guide
Policy template list
"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"
}
}
]
}
]
}
]
DynamoDBWritePolicy
Gives write-only permission to a DynamoDB table.
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:BatchWriteItem"
],
"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"
}
}
]
}
]
}
]
254
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 Simple Email Service (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.
255
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 read objects in an Amazon Simple Storage Service (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"
}
}
]
}
]
}
]
256
AWS Serverless Application Model Developer Guide
Policy template list
S3WritePolicy
Gives write permission to write objects into an Amazon S3 bucket.
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:PutObjectAcl",
"s3:PutLifecycleConfiguration"
],
"Resource": [
{
"Fn::Sub": [
"arn:${AWS::Partition}:s3:::${bucketName}",
{
"bucketName": {
"Ref": "BucketName"
}
}
]
},
{
"Fn::Sub": [
"arn:${AWS::Partition}:s3:::${bucketName}/*",
{
"bucketName": {
"Ref": "BucketName"
}
}
]
}
]
}
]
S3CrudPolicy
Gives create, read, update, and delete permission to act on the 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}",
257
AWS Serverless Application Model Developer Guide
Policy template list
{
"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/
*"
}
}
]
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/*"
}
}
]
258
AWS Serverless Application Model Developer Guide
Policy template list
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"
}
}
]
}
}
]
RekognitionReadPolicy
Gives permission to list and search faces.
"Statement": [
{
"Effect": "Allow",
"Action": [
"rekognition:ListCollections",
"rekognition:ListFaces",
"rekognition:SearchFaces",
"rekognition:SearchFacesByImage"
259
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"
}
}
]
}
}
]
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"
}
}
]
}
}
]
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"
}
}
260
AWS Serverless Application Model Developer Guide
Policy template list
]
}
}
]
SNSPublishMessagePolicy
Gives permission to publish a message to an Amazon Simple Notification Service (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": [
"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",
261
AWS Serverless Application Model Developer Guide
Policy template list
"dynamodb:GetShardIterator"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}/stream/${streamName}",
{
"tableName": {
"Ref": "TableName"
},
"streamName": {
"Ref": "StreamName"
}
}
]
}
},
{
"Effect": "Allow",
"Action": [
"dynamodb:ListStreams"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/
${tableName}/stream/*",
{
"tableName": {
"Ref": "TableName"
}
}
]
}
}
]
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": [
"kinesis:DescribeStream",
"kinesis:DescribeStreamSummary",
"kinesis:GetRecords",
"kinesis:GetShardIterator"
],
"Resource": {
"Fn::Sub": [
262
AWS Serverless Application Model Developer Guide
Policy template list
"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:SendRawEmail",
"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"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:sns:${AWS::Region}:${AWS::AccountId}:${topicName}*",
{
"topicName": {
263
AWS Serverless Application Model Developer Guide
Policy template list
"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:DescribeStreamSummary",
"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 Key Management Service (AWS KMS) key. Note that keyId
must be an AWS KMS key ID, and not a key alias.
"Statement": [
{
"Action": "kms:Decrypt",
"Effect": "Allow",
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:kms:${AWS::Region}:${AWS::AccountId}:key/${keyId}",
{
264
AWS Serverless Application Model Developer Guide
Policy template list
"keyId": {
"Ref": "KeyId"
}
}
]
}
}
]
KMSEncryptPolicy
Gives permission to encrypt with an AWS KMS key. Note that keyId must be an AWS KMS key ID, and not
a key alias.
"Statement": [
{
"Action": "kms:Encrypt",
"Effect": "Allow",
"Resource": {
"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",
265
AWS Serverless Application Model Developer Guide
Policy template list
"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 act on the objects in an Amazon S3 bucket.
"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}",
{
266
AWS Serverless Application Model Developer Guide
Policy template list
"bucketName": {
"Ref": "BucketName"
}
}
]
}
]
}
]
CodePipelineLambdaExecutionPolicy
Gives permission for a Lambda function invoked by AWS CodePipeline to report the status of the job.
"Statement": [
{
"Effect": "Allow",
"Action": [
"codepipeline:PutJobSuccessResult",
"codepipeline:PutJobFailureResult"
],
"Resource": "*"
}
]
ServerlessRepoReadWriteAccessPolicy
Gives permission to create and list applications in the AWS Serverless Application Repository (AWS SAM)
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": [
267
AWS Serverless Application Model Developer Guide
Policy template list
{
"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.
"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": "*"
}
]
268
AWS Serverless Application Model Developer Guide
Policy template list
AWSSecretsManagerGetSecretValuePolicy
Gives permission to get the secret value for the specified AWS Secrets Manager secret.
"Statement": [
{
"Effect": "Allow",
"Action": [
"secretsmanager:GetSecretValue"
],
"Resource": {
"Fn::Sub": [
"${secretArn}",
{
"secretArn": {
"Ref": "SecretArn"
}
}
]
}
}
]
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": [
269
AWS Serverless Application Model Developer Guide
Policy template list
"cloudwatch:GetDashboard",
"cloudwatch:ListDashboards",
"cloudwatch:PutDashboard",
"cloudwatch:ListMetrics"
],
"Resource": "*"
}
]
RekognitionFacesManagementPolicy
Gives permission to add, delete, and search faces in an Amazon Rekognition collection.
"Statement": [{
"Effect": "Allow",
"Action": [
"rekognition:IndexFaces",
"rekognition:DeleteFaces",
"rekognition:SearchFaces",
"rekognition:SearchFacesByImage",
"rekognition:ListFaces"
],
"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.
270
AWS Serverless Application Model Developer Guide
Policy template list
"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}",
{
"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": [{
271
AWS Serverless Application Model Developer Guide
Policy template list
"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": {
"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": "*"
}
]
272
AWS Serverless Application Model Developer Guide
Policy template list
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": [
"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}",
{
273
AWS Serverless Application Model Developer Guide
Policy template list
"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"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:firehose:${AWS::Region}:
${AWS::AccountId}:deliverystream/${deliveryStreamName}",
{
"deliveryStreamName": {
"Ref": "DeliveryStreamName"
}
}
]
}
}
]
EKSDescribePolicy
Gives permission to describe or list Amazon Elastic Kubernetes Service (Amazon EKS) clusters.
"Statement": [
{
"Effect": "Allow",
"Action": [
"eks:DescribeCluster",
"eks:ListClusters"
],
"Resource": "*"
}
]
CostExplorerReadOnlyPolicy
Gives read-only permission to the read-only AWS Cost Explorer (Cost Explorer) APIs for billing history.
274
AWS Serverless Application Model Developer Guide
Policy template list
"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"
],
"Resource": "*"
}]
SESBulkTemplatedCrudPolicy
Gives permission to send Amazon SES email, templated email, and templated bulk emails and to 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"
}
}
]
}
}
]
275
AWS Serverless Application Model Developer Guide
Policy template list
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 CloudWatch Logs events from a specified log group.
"Statement": [
{
"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 parameters from an Amazon EC2 Systems Manager (SSM) parameter store
to load secrets in this account.
Note
If you are not using default key, you will also need the KMSDecryptPolicy policy.
"Statement": [
{
"Effect": "Allow",
"Action": [
"ssm:DescribeParameters"
],
"Resource": "*"
276
AWS Serverless Application Model Developer Guide
Policy template list
},
{
"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": [
{
"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, and delete objects within a specific CodeCommit repository.
"Statement": [
{
"Effect": "Allow",
"Action": [
"codecommit:GitPull",
"codecommit:GitPush",
"codecommit:CreateBranch",
"codecommit:DeleteBranch",
277
AWS Serverless Application Model Developer Guide
Policy template list
"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",
"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"
278
AWS Serverless Application Model Developer Guide
Policy template list
}
}
]
}
}
]
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",
"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"
}
}
]
}
}
]
279
AWS Serverless Application Model Developer Guide
Policy template list
AthenaQueryPolicy
Gives permissions to execute Athena queries.
"Statement": [
{
"Effect": "Allow",
"Action": [
"athena:ListWorkGroups",
"athena:GetExecutionEngine",
"athena:GetExecutionEngines",
"athena:GetNamespace",
"athena:GetCatalogs",
"athena:GetNamespaces",
"athena:GetTables",
"athena:GetTable"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"athena:StartQueryExecution",
"athena:GetQueryResults",
"athena:DeleteNamedQuery",
"athena:GetNamedQuery",
"athena:ListQueryExecutions",
"athena:StopQueryExecution",
"athena:GetQueryResultsStream",
"athena:ListNamedQueries",
"athena:CreateNamedQuery",
"athena:GetQueryExecution",
"athena:BatchGetNamedQuery",
"athena:BatchGetQueryExecution",
"athena:GetWorkGroup"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:athena:${AWS::Region}:${AWS::AccountId}:workgroup/
${workgroupName}",
{
"workgroupName": {
"Ref": "WorkGroupName"
}
}
]
}
}
]
TextractPolicy
Gives full access to Amazon Textract.
"Statement": [
{
"Effect": "Allow",
280
AWS Serverless Application Model Developer Guide
Policy template list
"Action": [
"textract:*"
],
"Resource": "*"
}
]
TextractDetectAnalyzePolicy
Gives access to detect and analyze documents with Amazon Textract.
"Statement": [
{
"Effect": "Allow",
"Action": [
"textract:DetectDocumentText",
"textract:StartDocumentTextDetection",
"textract:StartDocumentAnalysis",
"textract:AnalyzeDocument"
],
"Resource": "*"
}
]
TextractGetResultPolicy
Gives access to get detected and analyzed documents from Amazon Textract.
"Statement": [
{
"Effect": "Allow",
"Action": [
"textract:GetDocumentTextDetection",
"textract:GetDocumentAnalysis"
],
"Resource": "*"
}
]
EventBridgePutEventsPolicy
Gives permissions to send events to Amazon EventBridge.
"Statement": [
{
"Effect": "Allow",
"Action": "events:PutEvents",
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:event-bus/
${eventBusName}",
{
"eventBusName": {
"Ref": "EventBusName"
}
281
AWS Serverless Application Model Developer Guide
Policy template list
}
]
}
}
]
ElasticMapReduceModifyInstanceFleetPolicy
Gives permission to list details and modify capacities for instance fleets within a cluster.
"Statement": [
{
"Action": [
"elasticmapreduce:ModifyInstanceFleet",
"elasticmapreduce:ListInstanceFleets"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:
${AWS::AccountId}:cluster/${clusterId}",
{
"clusterId": {
"Ref": "ClusterId"
}
}
]
},
"Effect": "Allow"
}
]
ElasticMapReduceSetTerminationProtectionPolicy
Gives permission to set termination protection for a cluster.
"Statement": [
{
"Action": "elasticmapreduce:SetTerminationProtection",
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:
${AWS::AccountId}:cluster/${clusterId}",
{
"clusterId": {
"Ref": "ClusterId"
}
}
]
},
"Effect": "Allow"
}
]
ElasticMapReduceModifyInstanceGroupsPolicy
Gives permission to list details and modify settings for instance groups within a cluster.
282
AWS Serverless Application Model Developer Guide
Policy template list
"Statement": [
{
"Action": [
"elasticmapreduce:ModifyInstanceGroups",
"elasticmapreduce:ListInstanceGroups"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:
${AWS::AccountId}:cluster/${clusterId}",
{
"clusterId": {
"Ref": "ClusterId"
}
}
]
},
"Effect": "Allow"
}
]
ElasticMapReduceCancelStepsPolicy
Gives permission to cancel a pending step or steps in a running cluster.
"Statement": [
{
"Action": "elasticmapreduce:CancelSteps",
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:
${AWS::AccountId}:cluster/${clusterId}",
{
"clusterId": {
"Ref": "ClusterId"
}
}
]
},
"Effect": "Allow"
}
]
ElasticMapReduceTerminateJobFlowsPolicy
Gives permission to shut down a cluster.
"Statement": [
{
"Action": "elasticmapreduce:TerminateJobFlows",
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:
${AWS::AccountId}:cluster/${clusterId}",
{
283
AWS Serverless Application Model Developer Guide
Policy template list
"clusterId": {
"Ref": "ClusterId"
}
}
]
},
"Effect": "Allow"
}
]
ElasticMapReduceAddJobFlowStepsPolicy
Gives permission to add new steps to a running cluster.
"Statement": [
{
"Action": "elasticmapreduce:AddJobFlowSteps",
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:
${AWS::AccountId}:cluster/${clusterId}",
{
"clusterId": {
"Ref": "ClusterId"
}
}
]
},
"Effect": "Allow"
}
]
SageMakerCreateEndpointPolicy
Gives permission to create an endpoint in SageMaker.
"Statement": [
{
"Action": [
"sagemaker:CreateEndpoint"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:sagemaker:${AWS::Region}:${AWS::AccountId}:endpoint/
${endpointName}",
{
"endpointName": {
"Ref": "EndpointName"
}
}
]
},
"Effect": "Allow"
}
]
284
AWS Serverless Application Model Developer Guide
Policy template list
SageMakerCreateEndpointConfigPolicy
Gives permission to create an endpoint configuration in SageMaker.
"Statement": [
{
"Action": [
"sagemaker:CreateEndpointConfig"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:sagemaker:${AWS::Region}:${AWS::AccountId}:endpoint-
config/${endpointConfigName}",
{
"endpointConfigName": {
"Ref": "EndpointConfigName"
}
}
]
},
"Effect": "Allow"
}
]
EcsRunTaskPolicy
Gives permission to start a new task for a task definition.
"Statement": [
{
"Action": [
"ecs:RunTask"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:ecs:${AWS::Region}:${AWS::AccountId}:task-
definition/${taskDefinition}",
{
"taskDefinition": {
"Ref": "TaskDefinition"
}
}
]
},
"Effect": "Allow"
}
]
EFSWriteAccessPolicy
Gives permission to mount an Amazon EFS file system with write access.
"Statement": [
{
"Effect": "Allow",
285
AWS Serverless Application Model Developer Guide
AWS SAM CLI telemetry
"Action": [
"elasticfilesystem:ClientMount",
"elasticfilesystem:ClientWrite"
],
"Resource": {
"Fn::Sub": [
"arn:${AWS::Partition}:elasticfilesystem:${AWS::Region}:
${AWS::AccountId}:file-system/${FileSystem}",
{
"FileSystem": {
"Ref": "FileSystem"
}
}
]
},
"Condition": {
"StringEquals": {
"elasticfilesystem:AccessPointArn": {
"Fn::Sub": [
"arn:${AWS::Partition}:elasticfilesystem:${AWS::Region}:
${AWS::AccountId}:access-point/${AccessPoint}",
{
"AccessPoint": {
"Ref": "AccessPoint"
}
}
]
}
}
}
}
]
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. 287).
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.
export SAM_CLI_TELEMETRY=0
286
AWS Serverless Application Model Developer Guide
Disabling telemetry for your profile in all sessions
1. Run:
2. Run:
source ~/.profile
1. Run:
2. Run:
source ~/.profile
1. Run:
setx SAM_CLI_TELEMETRY 0
2. Run:
refreshenv
Learn more
The telemetry data that's collected adheres to the AWS data privacy policies. For more information, see
the following:
287
AWS Serverless Application Model Developer Guide
Permissions
• Data Privacy
Permissions
To control access to AWS resources, AWS SAM uses the same mechanisms as AWS CloudFormation.
For more information, see Controlling access with AWS Identity and Access Management in the AWS
CloudFormation User Guide.
There are three main options for granting a user permission to manage serverless applications. Each
option provides users with different levels of access control.
Depending on which option you choose, users can manage only serverless applications containing AWS
resources that they have permission to access.
For more information about granting administrator permissions to a user, see Creating your first IAM
admin user and group in the IAM User Guide.
For example, the following AWS managed policies are sufficient to deploy the sample Hello World
application (p. 12):
• AWSCloudFormationFullAccess
• IAMFullAccess
• AWSLambda_FullAccess
• AmazonAPIGatewayAdministrator
• AmazonS3FullAccess
• AmazonEC2ContainerRegistryFullAccess
For information about attaching policies to an IAM user, see Changing permissions for an IAM user in the
IAM User Guide.
288
AWS Serverless Application Model Developer Guide
Grant specific IAM permissions
The best practice with this option is to deny users the permission to create roles, including Lambda
execution roles, so they can't grant themselves escalated permissions. So, you as the administrator must
first create a Lambda execution role that will be specified in the serverless applications that users will
manage. For information about creating Lambda execution roles, see Creating an execution role in the
IAM console.
For the sample Hello World application (p. 12) the AWSLambdaBasicExecutionRole is sufficient to run
the application. After you've created a Lambda execution role, modify the AWS SAM template file of the
sample Hello World application to add the following property to the AWS::Serverless::Function
resource:
Role: lambda-execution-role-arn
With the modified Hello World application in place, the following policy statement grants sufficient
permissions for users to deploy, update, and delete the application:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "CloudFormationTemplate",
"Effect": "Allow",
"Action": [
"cloudformation:CreateChangeSet"
],
"Resource": [
"arn:aws:cloudformation:*:aws:transform/Serverless-2016-10-31"
]
},
{
"Sid": "CloudFormationStack",
"Effect": "Allow",
"Action": [
"cloudformation:CreateChangeSet",
"cloudformation:DeleteStack",
"cloudformation:DescribeChangeSet",
"cloudformation:DescribeStackEvents",
"cloudformation:DescribeStacks",
"cloudformation:ExecuteChangeSet",
"cloudformation:GetTemplateSummary"
],
"Resource": [
"arn:aws:cloudformation:*:111122223333:stack/*"
]
},
{
"Sid": "S3",
"Effect": "Allow",
"Action": [
"s3:CreateBucket",
"s3:GetObject",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::*/*"
]
},
{
"Sid": "ECRRepository",
"Effect": "Allow",
"Action": [
"ecr:BatchCheckLayerAvailability",
"ecr:BatchGetImage",
289
AWS Serverless Application Model Developer Guide
Grant specific IAM permissions
"ecr:CompleteLayerUpload",
"ecr:DescribeImages",
"ecr:DescribeRepositories",
"ecr:GetDownloadUrlForLayer",
"ecr:GetRepositoryPolicy",
"ecr:InitiateLayerUpload",
"ecr:ListImages",
"ecr:PutImage",
"ecr:SetRepositoryPolicy",
"ecr:UploadLayerPart"
],
"Resource": [
"arn:aws:ecr:*:111122223333:repository/*"
]
},
{
"Sid": "ECRAuthToken",
"Effect": "Allow",
"Action": [
"ecr:GetAuthorizationToken"
],
"Resource": [
"*"
]
},
{
"Sid": "Lambda",
"Effect": "Allow",
"Action": [
"lambda:AddPermission",
"lambda:CreateFunction",
"lambda:DeleteFunction",
"lambda:GetFunction",
"lambda:GetFunctionConfiguration",
"lambda:ListTags",
"lambda:RemovePermission",
"lambda:TagResource",
"lambda:UntagResource",
"lambda:UpdateFunctionCode",
"lambda:UpdateFunctionConfiguration"
],
"Resource": [
"arn:aws:lambda:*:111122223333:function:*"
]
},
{
"Sid": "IAM",
"Effect": "Allow",
"Action": [
"iam:AttachRolePolicy",
"iam:DeleteRole",
"iam:DetachRolePolicy",
"iam:GetRole",
"iam:PassRole",
"iam:TagRole"
],
"Resource": [
"arn:aws:iam::111122223333:role/*"
]
},
{
"Sid": "APIGateway",
"Effect": "Allow",
"Action": [
"apigateway:DELETE",
"apigateway:GET",
290
AWS Serverless Application Model Developer Guide
Important notes
"apigateway:PATCH",
"apigateway:POST",
"apigateway:PUT"
],
"Resource": [
"arn:aws:apigateway:*::*"
]
}
]
}
For more information about IAM policies, see Managing IAM policies in the IAM User Guide.
Important notes
This section contains important notes and known issues for AWS Serverless Application Model.
If you cannot upgrade to a 64-bit system, you can use the Legacy Docker Toolbox with AWS SAM CLI on
a 32-bit system. However, this will cause you to encounter certain limitations with the AWS SAM CLI.
For example, you cannot run 64-bit Docker containers on a 32-bit system. So, if your Lambda function
depends on a 64-bit natively compiled container, you will not be able to test it locally on a 32-bit system.
To install AWS SAM CLI on a 32-bit system, execute the following command:
Important
Although the pip install aws-sam-cli command also works on 64-bit Windows, we
recommend that you use the 64-bit MSI to install AWS SAM CLI on 64-bit systems.
291
AWS Serverless Application Model Developer Guide
Support for tumbling Added support for tumbling December 17, 2020
windows (p. 292) windows for DynamoDB
and Kinesis event sources
for serverless functions. For
more information, see the
TumblingWindowInSeconds
property of the Kinesis and
DynamoDB data types of the
AWS::Serverless::Function
resource type.
Support for warm Added support for warm December 16, 2020
containers (p. 292) containers when testing
locally using the AWS SAM CLI
commands sam local start-
api and sam local start-
lambda. For more information,
see the --warm-containers
option for those commands.
Support for code Added support for code signing November 23, 2020
signing (p. 292) and trusted deployments of
serverless application code.
For more information, see
Configuring code signing for
AWS SAM applications.
Support for parallel and cached Improved performance of November 10, 2020
builds (p. 292) serverless application builds by
adding two options to the sam
build command: --parallel,
which builds functions and
layers in parallel rather than
sequentially, and --cached,
which uses build artifacts from
previous builds when no changes
have been made that requires a
rebuild. For more information,
see sam build.
292
AWS Serverless Application Model Developer Guide
Support for Lambda authorizers Added support for Lambda October 27, 2020
for HTTP APIs (p. 292) authorizers for the
AWS::Serverless::HttpApi
resource type. For more
information, see Lambda
authorizer example
(AWS::Serverless::HttpApi).
Support for multiple Added support for multiple September 24, 2020
configuration files and configuration files and
environments (p. 292) environments to store default
parameter values for AWS
SAM CLI commands. For more
information, see AWS SAM CLI
configuration file.
Support for X-Ray with Step Added support for X-Ray as an September 17, 2020
Functions, and references event source for serverless state
when controlling access to machines. For more information,
APIs (p. 292) see the Tracing property of the
AWS::Serverless::StateMachine
resource type. Also added
support for references when
controlling access to APIs. For
more information, see the
ResourcePolicyStatement
data type.
293
AWS Serverless Application Model Developer Guide
Support for Amazon Added support for Amazon August 13, 2020
MSK (p. 292) MSK as an event source for
serverless functions. This allows
records in an Amazon MSK
topic to trigger your Lambda
function. For more information,
see the EventSource
and MSK data types of the
AWS::Serverless::Function
resource type.
Support for Amazon Added support for mounting June 16, 2020
EFS (p. 292) Amazon EFS file systems to
local directories. This allows
your Lambda function code
to access and modify shared
resources. For more information,
see the FileSystemConfigs
property of the
AWS::Serverless::Function
resource type.
Building layers (p. 292) Added the ability to build May 19, 2020
individual LayerVersion
resources. For more information,
see Building Layers.
Generated AWS CloudFormation Provided details about the AWS April 8, 2020
Resources (p. 292) CloudFormation resources that
AWS SAM generates and how
to reference them. For more
information, see Generated AWS
CloudFormation Resources.
294
AWS Serverless Application Model Developer Guide
AWS SAM Specification and AWS Migrated the AWS SAM November 25, 2019
SAM CLI updates (p. 292) 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. 292) 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. 292) 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. 292) command in the AWS SAM
CLI simplifies the process
for publishing serverless
applications in the AWS
Serverless Application
Repository. For more
information, see Publishing
Serverless Applications Using
the AWS SAM CLI.
Nested applications and layers Added support for nested November 29, 2018
support (p. 292) applications and layers. For more
information, see Using Nested
Applications and Working with
Layers.
295
AWS Serverless Application Model Developer Guide
Added sam build to the AWS The new sam build command November 19, 2018
SAM CLI (p. 292) in the AWS SAM CLI simplifies
the process for compiling
serverless applications with
dependencies so that you
can locally test and deploy
these applications. For more
information, see Building
Applications.
Added new installation options Added Linuxbrew (Linux), MSI November 7, 2018
for the AWS SAM CLI (p. 292) (Windows), and Homebrew
(macOS) installation options
for the AWS SAM CLI. For more
information, see Installing the
AWS SAM CLI.
New guide (p. 292) This is the first release of the October 17, 2018
AWS Serverless Application Model
Developer Guide.
296