• 沒有找到結果。

AWS Serverless Application Model Developer Guide

N/A
N/A
Protected

Academic year: 2022

Share "AWS Serverless Application Model Developer Guide"

Copied!
360
0
0

加載中.... (立即查看全文)

全文

(1)

AWS Serverless Application Model

Developer Guide

(2)

AWS Serverless Application Model: Developer Guide

Copyright © Amazon Web Services, Inc. and/or its affiliates. All rights reserved.

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.

(3)

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

macOS ... 12

Setting up AWS credentials ... 15

Using the AWS CLI ... 16

Not using the AWS CLI ... 16

Tutorial: Hello World application ... 16

Prerequisites ... 17

Step 1: Download a sample AWS SAM application ... 17

Step 2: Build your application ... 18

Step 3: Deploy your application to the AWS Cloud ... 19

Step 4: (Optional) Test your application locally ... 22

Troubleshooting ... 24

Clean up ... 26

Conclusion ... 26

Next steps ... 26

AWS SAM specification ... 27

Template anatomy ... 27

YAML ... 28

Template sections ... 28

Next steps ... 29

Globals ... 29

Resource and property reference ... 33

AWS::Serverless::Api ... 33

AWS::Serverless::Application ... 65

AWS::Serverless::Function ... 68

AWS::Serverless::HttpApi ... 134

AWS::Serverless::LayerVersion ... 154

AWS::Serverless::SimpleTable ... 157

AWS::Serverless::StateMachine ... 160

Resource attributes ... 180

Exceptions ... 180

Intrinsic functions ... 181

Generated resources ... 181

Referencing generated AWS CloudFormation resources ... 181

Generated AWS CloudFormation resource scenarios ... 182

AWS::Serverless::Api ... 183

AWS::Serverless::Application ... 184

AWS::Serverless::Function ... 185

AWS::Serverless::HttpApi ... 188

AWS::Serverless::LayerVersion ... 190

AWS::Serverless::SimpleTable ... 190

AWS::Serverless::StateMachine ... 190

API Gateway extensions ... 191

Authoring ... 193

Validating AWS SAM template files ... 193

Working with layers ... 193

Including layers in your application ... 194

How layers are cached locally ... 194

(4)

Using nested applications ... 195

Defining a nested application from the AWS Serverless Application Repository ... 196

Defining a nested application from the local file system ... 197

Deploying nested applications ... 197

Controlling access to APIs ... 197

Choosing a mechanism to control access ... 199

Customizing error responses ... 199

Examples ... 199

Lambda authorizer examples ... 200

IAM permission example ... 202

Amazon Cognito user pool example ... 202

API key example ... 203

Resource policy example ... 204

OAuth 2.0/JWT authorizer example ... 204

Customized response example ... 205

Orchestrating applications ... 206

Example ... 206

More information ... 207

Code signing ... 207

Example ... 207

Providing signing profiles with sam deploy --guided ... 209

Building ... 210

Building applications ... 210

Building a .zip file archive ... 210

Building a container image ... 211

Container environment variable file ... 211

Examples ... 212

Building Node.js Lambda functions with esbuild (Preview) ... 213

Building layers ... 215

Examples ... 212

Building custom runtimes ... 217

Examples ... 217

Testing and debugging ... 219

Invoking functions locally ... 219

Environment variable file ... 220

Layers ... 220

Running API Gateway locally ... 220

Layers ... 222

Integrating with automated tests ... 222

Generating sample event payloads ... 223

Step-through debugging Lambda functions locally ... 223

Using AWS Toolkits ... 224

Running AWS SAM locally in debug mode ... 225

Passing additional runtime debug arguments ... 225

Deploying ... 227

Deploying using CI/CD systems ... 227

Deploying using the AWS SAM CLI ... 227

Troubleshooting deployments using the AWS SAM CLI ... 228

AWS SAM CLI error: "Security Constraints Not Satisfied" ... 24

Gradual deployments ... 228

Modify existing pipelines ... 228

AWS CodePipeline ... 229

Bitbucket Pipelines ... 229

Jenkins ... 230

GitLab CI/CD ... 230

GitHub Actions ... 231

Generating starter pipelines ... 231

(5)

AWS CodePipeline ... 232

Jenkins, GitLab CI/CD, GitHub Actions, Bitbucket Pipelines ... 233

Customizing starter pipelines ... 235

Example projects ... 235

Example files ... 236

Monitoring ... 237

Working with logs ... 237

Fetching logs by AWS CloudFormation stack ... 237

Fetching logs by Lambda function name ... 237

Tailing logs ... 237

Viewing logs for a specific time range ... 237

Filtering logs ... 237

Error highlighting ... 238

JSON pretty printing ... 238

Publishing ... 239

Prerequisites ... 239

Publishing a new application ... 240

Step 1: Add a Metadata section to the AWS SAM template ... 240

Step 2: Package the application ... 240

Step 3: Publish the application ... 241

Step 4: Share the application (optional) ... 241

Publishing a new version of an existing application ... 241

Additional topics ... 242

Metadata section properties ... 242

Properties ... 242

Use cases ... 243

Example ... 244

Example applications ... 245

Process DynamoDB events ... 245

Before you begin ... 245

Step 1: Initialize the application ... 245

Step 2: Test the application locally ... 245

Step 3: Package the application ... 246

Step 4: Deploy the application ... 246

Next steps ... 247

Process Amazon S3 events ... 247

Before you begin ... 247

Step 1: Initialize the application ... 247

Step 2: Package the application ... 248

Step 3: Deploy the application ... 248

Step 4: Test the application locally ... 249

Next steps ... 249

AWS CDK ... 250

Getting started ... 250

Prerequisites ... 250

Creating and locally testing an AWS CDK application ... 250

Locally testing ... 252

Example ... 253

Building ... 253

Example ... 254

Deploying ... 254

Accelerate (Preview) ... 255

Getting started ... 255

Prerequisites ... 255

Getting started tutorial ... 255

Deploying ... 257

Examples ... 260

(6)

Monitoring ... 260

sam logs ... 260

sam traces ... 261

AWS SAM reference ... 263

AWS SAM specification ... 263

AWS SAM CLI command reference ... 263

AWS SAM policy templates ... 263

Topics ... 263

AWS SAM CLI command reference ... 264

sam build ... 264

sam delete ... 269

sam deploy ... 270

sam init ... 274

sam local generate-event ... 277

sam local invoke ... 278

sam local start-api ... 280

sam local start-lambda ... 283

sam logs ... 285

sam package ... 287

sam pipeline bootstrap ... 289

sam pipeline init ... 290

sam publish ... 291

sam validate ... 292

AWS SAM CLI configuration file ... 292

Example ... 293

Configuration file rules ... 293

Writing configurations with sam deploy --guided ... 295

AWS SAM policy templates ... 295

Syntax ... 296

Examples ... 296

Policy template table ... 297

Troubleshooting ... 301

Policy template list ... 301

Image repositories ... 338

Image repository URIs ... 338

Examples ... 339

Deploying gradually ... 339

AWS SAM CLI telemetry ... 341

Disabling telemetry for a session ... 342

Disabling telemetry for your profile in all sessions ... 342

Types of information collected ... 342

Learn more ... 343

Permissions ... 343

Grant administrator permissions ... 343

Attach necessary AWS managed policies ... 343

Grant specific IAM permissions ... 344

Important notes ... 346

Installing AWS SAM CLI on 32-bit Windows ... 347

Document history ... 348

(7)

What is the AWS Serverless

Application Model (AWS SAM)?

The AWS Serverless Application Model (AWS SAM) is an open-source framework that you can use to build serverless applications on AWS.

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. 27).

 

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. 263).

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. 16) 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.

Benefits of using AWS SAM

Because AWS SAM integrates with other AWS services, creating serverless applications with AWS SAM provides the following benefits:

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.

 

(8)

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.

Next step

Getting started with AWS SAM (p. 3)

(9)

Getting started with AWS SAM

To get started with AWS SAM, use the AWS SAM CLI to create a serverless application that you can package and deploy in the AWS Cloud. You can run the application both in the AWS Cloud or locally on your development host.

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. 15)

• Tutorial: Deploying a Hello World application (p. 16)

Installing the AWS SAM CLI

AWS SAM provides you with a command line tool, the AWS SAM CLI, that makes it easy for you to create and manage serverless applications. You need to install and configure a few things in order to use the AWS SAM CLI.

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. 10)

• Installing the AWS SAM CLI on macOS (p. 12)

Installing the AWS SAM CLI on Linux

The AWS SAM command line interface (CLI) is supported on 64-bit versions of recent distributions of CentOS, Fedora, Ubuntu, and Amazon Linux 2. To install the AWS SAM CLI, you must extract or "unzip"

the downloaded package. If your operating system doesn't have the built-in unzip command, use an equivalent.

To install and configure the prerequisites for using the AWS SAM CLI on your Linux host, follow these steps:

1. Create an AWS account.

2. Configure AWS Identity and Access Management (IAM) permissions and AWS credentials.

3. Install Docker. Note: Docker is a prerequisite only for testing your application locally or using the -- use-container option.

4. Install the AWS SAM CLI.

Step 1: Create an AWS account

If you don't already have an AWS account, see aws.amazon.com and choose Create an AWS Account. For detailed instructions, see How do I create and activate a new AWS account?

(10)

Step 2: Configure IAM permissions and AWS credentials

The IAM user that you use with AWS SAM must have sufficient permissions to make necessary AWS service calls and manage AWS resources. The simplest way to ensure that a user has sufficient permissions is to grant administrator privileges to them. For more information, see Creating your first IAM admin user and group in the IAM User Guide.

NoteIf you don't want to grant administrator privileges to users who use the AWS Command Line Interface (AWS CLI), you can grant restricted sets of permissions to them. For more information, see Permissions (p. 343).

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. 15).

Step 3: Install Docker (optional)

NoteDocker is a prerequisite only for testing your application locally and for building deployment packages using the --use-container option. If you don't plan to use these features initially, you can skip this section or install Docker at a later time.

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.

If you're using Amazon Linux 2, follow these steps to install Docker:

1. Update the installed packages and package cache on your instance.

sudo yum update -y

2. Install the most recent Docker Community Edition package.

sudo amazon-linux-extras install docker 3. Start the Docker service.

sudo service docker start

4. Add the ec2-user to the docker group so that you can run Docker commands without using sudo.

sudo usermod -a -G docker ec2-user

5. Pick up the new docker group permissions by logging out and logging back in again. To do this, close your current SSH terminal window and reconnect to your instance in a new one. Your new SSH session should have the appropriate docker group permissions.

6. Verify that the ec2-user can run Docker commands without using sudo.

(11)

docker ps

You should see the following output, confirming that Docker is installed and running:

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

NoteOn Linux, to build and run Lambda functions with a different instruction set architecture than your host machine, you must take additional steps to configure Docker. For example, to run arm64 functions on an x86_64 machine, you can run the following command to configure the Docker daemon: docker run --rm --privileged multiarch/qemu-user-static -- reset -p yes.

If you run into issues installing Docker, see the Troubleshooting (p. 7) section later in this guide. Or, see the Troubleshooting section of Post-installation steps for Linux on the Docker Docs website.

Step 4: Install the AWS SAM CLI

To install the AWS SAM CLI, on follow these steps:

x86_64

1. Download the AWS SAM CLI zip file to a directory of your choice.

2. Verify the integrity and authenticity of the downloaded installer files by generating a hash value using the following command:

sha256sum aws-sam-cli-linux-x86_64.zip

The output should look like the following example:

<64-character SHA256 hash value> aws-sam-cli-linux-x86_64.zip

Compare the 64-character SHA256 hash value with the one for your desired AWS SAM CLI version in the AWS SAM CLI release notes on GitHub.

3. Unzip the installation files into the sam-installation/ subdirectory.

unzip aws-sam-cli-linux-x86_64.zip -d sam-installation 4. Install the AWS SAM CLI.

sudo ./sam-installation/install 5. Verify the installation.

sam --version

On successful installation, you should see output like the following:

SAM CLI, version 1.18.0

(12)

ARM

1. Use pip to install the AWS SAM CLI.

pip install aws-sam-cli 2. Verify the installation.

sam --version

On successful installation, you should see output like the following:

SAM CLI, version 1.18.0

You're now ready to start development.

Upgrading

To upgrade the AWS SAM CLI, perform the same steps as in the Install the AWS SAM CLI section earlier in this topic, but add the --update option to the install command, as follows:

sudo ./sam-installation/install --update

Uninstalling

To uninstall the AWS SAM CLI, you must delete the symlink and installation directory by running the following commands:

1. Locate the symlink and install paths.

• Find the symlink using the which command:

which sam

The output shows the path where the AWS SAM binaries are located, for example:

/usr/local/bin/sam

• Find the directory that the symlink points to using the ls command:

ls -l /usr/local/bin/sam

In the following example, the installation directory is /usr/local/aws-sam-cli.

lrwxrwxrwx 1 ec2-user ec2-user 49 Oct 22 09:49 /usr/local/bin/sam -> /usr/local/aws- sam-cli/current/bin/sam

2. Delete the symlink.

sudo rm /usr/local/bin/sam

(13)

sudo rm -rf /usr/local/aws-sam-cli

Nightly build

A nightly build of the AWS SAM CLI is available for you to install. Once installed, you can use the nightly build using the sam-nightly command. You can install and use both the production and nightly build versions of the AWS SAM CLI at the same time.

The nightly build contains a pre-release version of AWS SAM CLI code that may be less stable than the production version. Note that the nightly build does not contain pre-release version of the build image, so building a serverless application with the --use-container option uses the latest production version of the build image.

The nightly build is available with this download link: AWS SAM CLI nightly build. To install the nightly build version of the AWS SAM CLI, perform the same steps as in the Step 4: Install the AWS SAM CLI (p. 5) section earlier in this topic, but use the nightly build download link instead. You can find the hash values for the nightly build installer files in the AWS SAM CLI release notes for nightly builds on GitHub.

To verify you have installed the nightly build version, run the sam-nightly --version command. The output of this command is in the form 1.X.Y.dev<YYYYMMDDHHmm>, for example:

SAM CLI, version 1.20.0.dev202103151200

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 have to reboot your instance. If you receive this error, try rebooting your instance.

Shell error: "command not found"

If you receive this error, your shell can't locate the AWS SAM CLI executable in the path. Verify the location of the directory where you installed the AWS SAM CLI executable, and then verify that the directory is on your path.

AWS SAM CLI error: "/lib64/libc.so.6: version `GLIBC_2.14' not found (required by /usr/local/aws-sam-cli/dist/libz.so.1)"

If you receive this error, you're using an unsupported version of Linux, and the built-in glibc version is out of date. Try either of the following:

• Upgrade your Linux host to the 64-bit version of a recent distribution of CentOS, Fedora, Ubuntu, or Amazon Linux 2.

• Follow the instructions for Installing the AWS SAM CLI on Linux using Homebrew (p. 8).

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:

(14)

• Tutorial: Deploying a Hello World application (p. 16) – Step-by-step instructions to download, build, and deploy a simple serverless application.

• AWS SAM example applications and patterns – Sample applications and patterns from community authors that you can further experiment with.

Installing the AWS SAM CLI on Linux using Homebrew

To install the AWS SAM CLI on Linux, you can use the Homebrew package manager. For more information about Homebrew, see Homebrew on Linux on the Homebrew Documentation website.

NoteInstalling Homebrew changes your environment's default Python version to the one that Homebrew installs.

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.

Install Homebrew

After successfully installing Git, to install Homebrew, run the following command:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/

install.sh)"

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 Red Hat.

test -d ~/.linuxbrew && eval $(~/.linuxbrew/bin/brew shellenv)

test -d /home/linuxbrew/.linuxbrew && eval $(/home/linuxbrew/.linuxbrew/bin/brew shellenv) test -r ~/.bash_profile && echo "eval \$($(brew --prefix)/bin/brew shellenv)"

>>~/.bash_profile

echo "eval \$($(brew --prefix)/bin/brew shellenv)" >>~/.profile

Verify that Homebrew is installed.

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)

Install the AWS SAM CLI using Homebrew

To install the AWS SAM CLI using Homebrew, run the following commands:

brew tap aws/tap

brew install aws-sam-cli Verify the installation.

sam --version

(15)

On successful installation of the AWS SAM CLI, you should see output like the following:

SAM CLI, version 1.35.0

Upgrading the AWS SAM CLI using Homebrew

To upgrade the AWS SAM CLI using Homebrew, replace install with upgrade as follows:

brew upgrade aws-sam-cli

Nightly build using Homebrew

A nightly build of the AWS SAM CLI is available for you to install. Once installed, you can use the nightly build using the sam-nightly command. You can install and use both the production and nightly build versions of the AWS SAM CLI at the same time.

The nightly build contains a pre-release version of AWS SAM CLI code that may be less stable than the production version. Note that the nightly build does not contain pre-release version of the build image, so building a serverless application with the --use-container option uses the latest production version of the build image.

To install the nightly build version of the AWS SAM CLI, run the following commands:

brew tap aws/tap

brew install aws-sam-cli-nightly

To verify you have installed the nightly build version, run the sam-nightly --version command. The output of this command is in the form 1.X.Y.dev<YYYYMMDDHHmm>, for example:

SAM CLI, version 1.20.0.dev202103151200

Troubleshooting

Installing Homebrew message: "Enter your password to install to /home/linuxbrew/.linuxbrew"

During the Install Homebrew step, by default you're prompted to provide a password. However, you might not want to set up a password for the current user, for example, when you're setting up a non- interactive environment like CI/CD systems.

If you don't want to set up a password for the current user, you can install Homebrew in non-interactive mode by setting the environment variable CI=1. For example:

CI=1 /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/

install.sh)"

Installing AWS SAM CLI error: "The following formulae cannot be installed from bottles and must be built from source. pkg-config, gdbm, [email protected], ncurses, xz and [email protected]"

If you see this error while installing the AWS SAM CLI, you don't have the gcc module installed. Install the gcc module for your Linux distribution.

# for Amazon Linux, Amazon Linux 2, CentOS and Red Hat:

sudo yum install gcc

# for Debian and Ubuntu:

sudo apt-get update

(16)

sudo apt-get install gcc

After installing the gcc module, run the commands in the Install the AWS SAM CLI using Homebrew section again.

Shell error: "command not found"

If you receive this error, your shell can't locate the AWS SAM CLI executable in the PATH. Verify the location of the directory where you installed the AWS SAM CLI executable, and then verify that the directory is on your PATH.

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

Installing the AWS SAM CLI on Windows

Follow these steps to install and configure the prerequisites for using the AWS SAM command line interface (CLI) on your Windows host:

1. Create an AWS Identity and Access Management (AWS) account.

2. Configure IAM permissions and AWS credentials.

3. Install Docker. Note: Docker is a prerequisite only for testing your application locally or using the -- use-container option.

4. Install the AWS SAM CLI.

Step 1: Create an AWS account

If you don't already have an AWS account, see aws.amazon.com and choose Create an AWS Account. For detailed instructions, see Create and Activate an AWS Account.

Step 2: Configure IAM permissions and AWS credentials

The IAM user that you use with AWS SAM must have sufficient permissions to make necessary AWS service calls and manage AWS resources. The simplest way to ensure that a user has sufficient permissions is to grant administrator privileges to them. For more information, see Creating your first IAM admin user and group in the IAM User Guide.

NoteIf you don't want to grant administrator privileges to users who use the AWS Command Line Interface (AWS CLI), you can grant restricted sets of permissions to them. For more information, see Permissions (p. 343).

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. 15).

Step 3: Install Docker (optional)

NoteDocker is a prerequisite only for testing your application locally and for building deployment packages using the --use-container option. If you don't plan to use these features initially, you can skip this section or install Docker at a later time.

(17)

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.

• If you're using Windows 10 in Hyper-V mode, see Docker File Sharing.

• To share drives on older versions of Windows, see Add Shared Directories.

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.

Step 4: Install the AWS SAM CLI

Windows Installer (MSI) files are the package installer files for the Windows operating system.

Follow these steps to install the AWS SAM CLI using the MSI file.

1. Install the AWS SAM CLI 64-bit.

NoteIf you operate on 32-bit system, see Installing AWS SAM CLI on 32-bit Windows (p. 347).

2. Verify the installation.

After completing the installation, verify it by opening a new command prompt or PowerShell prompt. You should be able to invoke sam from the command line.

sam --version

You should see output like the following after successful installation of the AWS SAM CLI:

SAM CLI, version 1.35.0

3. Install Git.

(18)

To download sample applications using the sam init command, you must also install Git. For instructions, see Installing Git.

You're now ready to start development.

Uninstalling

To uninstall the AWS SAM CLI using Windows Settings, follow these steps:

1. From the Start menu, search for "Add or remove programs".

2. Select the entry named AWS SAM Command Line Interface and choose Uninstall to launch the uninstaller.

3. Confirm that you want to uninstall the AWS SAM CLI.

Nightly build

A nightly build of the AWS SAM CLI is available for you to install. Once installed, you can use the nightly build using the sam-nightly command. You can install and use both the production and nightly build versions of the AWS SAM CLI at the same time.

The nightly build contains a pre-release version of AWS SAM CLI code that may be less stable than the production version. Note that the nightly build does not contain pre-release version of the build image, so building a serverless application with the --use-container option uses the latest production version of the build image.

The nightly build is available with this download link: AWS SAM CLI nightly build. To install the nightly build version of the AWS SAM CLI, perform the same steps as in the Step 4: Install the AWS SAM CLI (p. 11) section earlier in this topic, but use the nightly build download link instead.

To verify you have installed the nightly build version, run the sam-nightly --version command. The output of this command is in the form 1.X.Y.dev<YYYYMMDDHHmm>, for example:

SAM CLI, version 1.20.0.dev202103151200

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. 16) – Step-by-step instructions to download, build, and deploy a simple serverless application.

• AWS SAM example applications and patterns – Sample applications and patterns from community authors that you can further experiment with.

Installing the AWS SAM CLI on macOS

Follow these steps to install and configure the prerequisites for using the AWS SAM command line interface (CLI) on your macOS host:

1. Create an AWS account.

2. Configure AWS Identity and Access Management (IAM) permissions and AWS credentials.

(19)

3. Install Docker. Note: Docker is a prerequisite only for testing your application locally or using the -- use-container option

4. Install Homebrew.

5. Install the AWS SAM CLI.

Step 1: Create an AWS account

If you don't already have an AWS account, see aws.amazon.com and choose Create an AWS Account. For detailed instructions, see How do I create and activate a new AWS account?

Step 2: Configure IAM permissions and AWS credentials

The IAM user that you use with AWS SAM must have sufficient permissions to make necessary AWS service calls and manage AWS resources. The simplest way to ensure that a user has sufficient permissions is to grant administrator privileges to them. For more information, see Creating your first IAM admin user and group in the IAM User Guide.

Note

If you don't want to grant administrator privileges to users who use the AWS Command Line Interface (AWS CLI), you can grant restricted sets of permissions to them. For more information, see Permissions (p. 343).

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. 15).

Step 3: Install Docker (optional)

NoteDocker is a prerequisite only for testing your application locally and for building deployment packages using the --use-container option. If you don't plan to use these features initially, you can skip this section or install Docker at a later time.

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.

(20)

Step 4: Install Homebrew

The recommended approach for installing the AWS SAM CLI on macOS is to use the Homebrew package manager. For more information about Homebrew, see Homebrew Documentation.

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:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/

install.sh)"

Verify that Homebrew is installed:

brew --version

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)

Step 5: Install the AWS SAM CLI

Follow these steps to install the AWS SAM CLI using Homebrew:

brew tap aws/tap

brew install aws-sam-cli

Verify the installation:

sam --version

You should see output like the following after successful installation of the AWS SAM CLI:

SAM CLI, version 1.35.0

You're now ready to start development.

Upgrading

To upgrade the AWS SAM CLI, using Homebrew, run the following command:

brew upgrade aws-sam-cli

(21)

Uninstalling

To uninstall the AWS SAM CLI, using Homebrew, run the following command:

brew uninstall aws-sam-cli

Nightly build

A nightly build of the AWS SAM CLI is available for you to install. Once installed, you can use the nightly build using the sam-nightly command. You can install and use both the production and nightly build versions of the AWS SAM CLI at the same time.

The nightly build contains a pre-release version of AWS SAM CLI code that may be less stable than the production version. Note that the nightly build does not contain pre-release version of the build image, so building a serverless application with the --use-container option uses the latest production version of the build image.

To install the nightly build version of the AWS SAM CLI, run the following commands:

brew tap aws/tap

brew install aws-sam-cli-nightly

To verify you have installed the nightly build version, run the sam-nightly --version command. The output of this command is in the form 1.X.Y.dev<YYYYMMDDHHmm>, for example:

SAM CLI, version 1.20.0.dev202103151200

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. 16) – Step-by-step instructions to download, build, and deploy a simple serverless application.

• AWS SAM example applications and patterns – Sample applications and patterns from community authors that you can further experiment with.

Setting up AWS credentials

The AWS SAM command line interface (CLI) requires you to set AWS credentials so that it can make calls to AWS services on your behalf. For example, the AWS SAM CLI makes calls to Amazon S3 and AWS CloudFormation.

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.

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:

(22)

Using the AWS CLI

If you have the AWS CLI installed, use the aws configure command and follow the prompts:

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

Not using the AWS CLI

If you don't have the AWS CLI installed, you can either create a credentials file or set environment variables:

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 This file should contain lines in the following format:

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

To set these variables on Linux or macOS, use the export command:

export AWS_ACCESS_KEY_ID=your_access_key_id

export AWS_SECRET_ACCESS_KEY=your_secret_access_key

To set these variables on Windows, use the set command:

set AWS_ACCESS_KEY_ID=your_access_key_id

set AWS_SECRET_ACCESS_KEY=your_secret_access_key

Tutorial: Deploying a Hello World application

In this guide, you download, build, and deploy a sample Hello World application using AWS SAM. You then test the application in the AWS Cloud, and optionally test it locally on your development host.

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.

The following diagram shows the components of this application:

(23)

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.

#Step 1 - Download a sample application sam init

#Step 2 - Build your application cd sam-app

sam build

#Step 3 - Deploy your application sam deploy --guided

Prerequisites

This guide assumes that you've completed the steps for your operating system in Installing the AWS SAM CLI (p. 3), including:

1. Creating an AWS account.

2. Configuring AWS Identity and Access Management (IAM) permissions.

3. Installing Docker. Note: Docker is a prerequisite only for testing your application locally.

4. Installing Homebrew. Note: Homebrew is a prerequisite only for Linux and macOS.

5. Installing the AWS SAM command line interface (CLI). Note: Make sure that you have version 1.13.0 or later. Check the version by running the sam --version command.

Step 1: Download a sample AWS SAM application

Command to run:

sam init

(24)

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

Next steps can be found in the README file at ./sam-app/README.md

What AWS SAM is doing:

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

NoteThese project directory contents are created when you choose one of the Python runtimes and the Hello World Example.

There are three especially important files:

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

Step 2: Build your application

Command to run:

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:

(25)

sam build Example output:

Build Succeeded

Built Artifacts : .aws-sam/build

Built Template : .aws-sam/build/template.yaml Commands you can use next

=========================

[*] Invoke Function: sam local invoke [*] Deploy: sam deploy --guided

What AWS SAM is doing:

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.

You can see the following top-level tree under .aws-sam:

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

Step 3: Deploy your application to the AWS Cloud

Command to run:

sam deploy --guided

Follow the on-screen prompts. To accept the default options provided in the interactive experience, respond with Enter.

NoteFor 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 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. 197).

Example output:

(26)

Deploying with following values ===============================

Stack name : sam-app Region : us-east-1 Confirm changeset : False Deployment s3 bucket : sam-bucket

Capabilities : ["CAPABILITY_IAM"]

Parameter overrides : {}

Initiating deployment =====================

Waiting for changeset to be created..

CloudFormation stack changeset

--- Operation LogicalResourceId

ResourceType

--- + Add

HelloWorldFunctionHelloWorldPermissionProd AWS::Lambda::Permission

+ Add ServerlessRestApiDeployment47fc2d5f9d AWS::ApiGateway::Deployment

+ Add ServerlessRestApiProdStage AWS::ApiGateway::Stage

+ Add ServerlessRestApi AWS::ApiGateway::RestApi

* Modify HelloWorldFunctionRole AWS::IAM::Role

* Modify HelloWorldFunction AWS::Lambda::Function

--- 2019-11-21 14:33:24 - Waiting for stack create/update to complete

CloudFormation events from changeset

--- ResourceStatus ResourceType

LogicalResourceId ResourceStatusReason

--- UPDATE_IN_PROGRESS AWS::IAM::Role

HelloWorldFunctionRole -

UPDATE_COMPLETE AWS::IAM::Role HelloWorldFunctionRole -

UPDATE_IN_PROGRESS AWS::Lambda::Function HelloWorldFunction -

UPDATE_COMPLETE AWS::Lambda::Function HelloWorldFunction -

CREATE_IN_PROGRESS AWS::ApiGateway::RestApi ServerlessRestApi -

CREATE_COMPLETE AWS::ApiGateway::RestApi ServerlessRestApi -

CREATE_IN_PROGRESS AWS::ApiGateway::RestApi ServerlessRestApi Resource creation Initiated

CREATE_IN_PROGRESS AWS::ApiGateway::Deployment ServerlessRestApiDeployment47fc2d5 Resource creation Initiated

f9d CREATE_IN_PROGRESS AWS::Lambda::Permission HelloWorldFunctionHelloWorldPermis Resource creation Initiated

sionProd CREATE_IN_PROGRESS AWS::Lambda::Permission

HelloWorldFunctionHelloWorldPermis -

sionProd CREATE_IN_PROGRESS AWS::ApiGateway::Deployment

ServerlessRestApiDeployment47fc2d5 -

f9d

(27)

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 -

--- Stack sam-app outputs:

--- OutputKey-Description OutputValue

--- HelloWorldFunctionIamRole - Implicit IAM Role created for Hello World

arn:aws:iam::123456789012:role/sam-app-

function HelloWorldFunctionRole-104VTJ0TST7M0

HelloWorldApi - API Gateway endpoint URL for Prod stage for Hello World https://0ks2zue0zh.execute-api.us-east-1.amazonaws.com/Prod/hello/

function

HelloWorldFunction - Hello World Lambda Function ARN arn:aws:lambda:us-east-1:123456789012:function:sam-app-

HelloWorldFunction-1TY92MJX0BXU5

--- Successfully created/updated stack - sam-app in us-east-1

What AWS SAM is doing:

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:

{"message": "hello world"}

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. 24) section later in this tutorial.

(28)

Step 4: (Optional) Test your application locally

When you're developing your application, you might find it useful to test locally. The AWS SAM CLI provides the sam local command to run your application using Docker containers that simulate the execution environment of Lambda. There are two options to do this:

• Host your API locally

• Invoke your Lambda function directly

This step describes both options.

Host your API locally

Command to run:

sam local start-api Example output:

2019-07-12 15:27:58 Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET]

2019-07-12 15:27:58 You can now browse to the above endpoints to invoke your functions.

You do not need to restart/reload SAM CLI while working on your functions, changes will be reflected instantly/automatically. You only need to restart SAM CLI if you update your AWS SAM template

2019-07-12 15:27:58 * Running on http://127.0.0.1:3000/ (Press CTRL+C to quit) Fetching lambci/lambda:python3.7 Docker container

image...

2019-07-12 15:28:56 Mounting /<working-development-path>/sam-app/.aws-sam/build/

HelloWorldFunction as /var/task:ro,delegated inside runtime container START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72

REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 4.42 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB

2019-07-12 15:28:58 No Content-Type given. Defaulting to 'application/json'.

2019-07-12 15:28:58 127.0.0.1 - - [12/Jul/2019 15:28:58] "GET /hello HTTP/1.1" 200 -

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:

2019-07-12 15:29:57 Invoking app.lambda_handler (python3.7)

2019-07-12 15:29:57 Found credentials in shared credentials file: ~/.aws/credentials Fetching lambci/lambda:python3.7 Docker container image...

2019-07-12 15:29:58 Mounting /<working-development-path>/sam-app/.aws-sam/build/

HelloWorldFunction as /var/task:ro,delegated inside runtime container START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72

REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 7.92 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB

(29)

{"statusCode":200,"body":"{\"message\": \"hello world\"}"}

What AWS SAM is doing:

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.

Invoke your Lambda function directly

Command to run:

sam local invoke "HelloWorldFunction" -e events/event.json Example output:

2019-07-01 14:08:42 Found credentials in shared credentials file: ~/.aws/credentials 2019-07-01 14:08:42 Invoking app.lambda_handler (python3.7)

Fetching lambci/lambda:python3.7 Docker container

image...

2019-07-01 14:09:39 Mounting /<working-development-path>/sam-app/.aws-sam/build/

HelloWorldFunction as /var/task:ro,delegated inside runtime container START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72

REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.51 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB

{"statusCode":200,"body":"{\"message\": \"hello world\"}"}

What AWS SAM is doing:

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 events/event.json Example output:

< "body": "", ---

> "body": "{\"message\": \"hello world\"}", 4,6c4,6

< "path": "/hello", < "httpMethod": "GET", < "isBase64Encoded": true,

(30)

---

> "path": "/path/to/resource", > "httpMethod": "POST", > "isBase64Encoded": false, 11c11

< "proxy": "/hello"

--- > "proxy": "/path/to/resource"

56c56

< "path": "/prod/hello", ---

> "path": "/prod/path/to/resource", 58c58

< "httpMethod": "GET", --- > "httpMethod": "POST",

Troubleshooting

AWS SAM CLI error: "Security Constraints Not Satisfied"

When running sam deploy --guided, you're 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:

Error: Security Constraints Not Satisfied

The prompt is informing you that the application you're about to deploy might have an Amazon API Gateway API configured without authorization. By responding N to this prompt, you're saying that this is not OK.

To fix this, you have the following options:

• Configure your application with authorization. For information about configuring authorization, see Controlling access to API Gateway APIs (p. 197).

• Respond to this question with Y to indicate that you're OK with deploying an application that has an API Gateway API configured without authorization.

AWS SAM CLI error: "no such option: --app-template"

When executing sam init, you see the following error:

Error: no such option: --app-template

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.

AWS SAM CLI error: "no such option: --guided"

When executing sam deploy, you see the following error:

(31)

Error: no such option: --guided

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.

AWS SAM CLI error: "Failed to create managed resources: Unable to locate credentials"

When executing sam deploy, you see the following error:

Error: Failed to create managed resources: Unable to locate credentials

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. 15).

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.

Curl error: "Missing Authentication Token"

When trying to invoke the API Gateway endpoint, you see the following error:

{"message":"Missing Authentication Token"}

This means that you've attempted to send a request to the correct domain, but the URI isn't recognizable. To fix this, verify the full URL, and update the curl command with the correct URL.

Curl error: "curl: (6) Could not resolve: ..."

When trying to invoke the API Gateway endpoint, you see the following error:

curl: (6) Could not resolve: endpointdomain (Domain name not found)

(32)

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.

When done, the status of the stack changes to DELETE_COMPLETE.

Alternatively, you can delete the AWS CloudFormation stack by running the following AWS CLI command:

aws cloudformation delete-stack --stack-name sam-app --region region

Verify the deleted stack

For both methods of deleting the AWS CloudFormation stack, you can verify that it was deleted by going to the AWS CloudFormation console. In the left navigation pane, choose Stacks, and then in the dropdown list next to the search box, choose Deleted. You should see your stack's name in the list of deleted stacks.

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.

To help you get started, you can download any of the example applications from the AWS Serverless Application Repository Examples repository on GitHub.

(33)

AWS Serverless Application Model (AWS SAM) specification

You use the AWS SAM specification to define your serverless application. This section provides details for the AWS SAM template sections, resources types, resource properties, data types, resource attributes, intrinsic functions, and API Gateway extensions that you can use in AWS SAM templates.

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. 27)

• AWS SAM resource and property reference (p. 33)

• Resource attributes (p. 180)

• Intrinsic functions (p. 181)

• Generated AWS CloudFormation resources (p. 181)

• API Gateway extensions (p. 191)

AWS SAM template anatomy

An AWS SAM template file closely follows the format of an AWS CloudFormation template file, which is described in Template anatomy in the AWS CloudFormation User Guide. The primary differences between AWS SAM template files and AWS CloudFormation template files are the following:

Transform declaration. The declaration Transform: AWS::Serverless-2016-10-31 is required for AWS SAM template files. This declaration identifies an AWS CloudFormation template file as an AWS SAM template file. For more information about transforms, see Transform in the AWS CloudFormation User Guide.

Globals section. The Globals section is unique to AWS SAM. It defines properties that are common to all your serverless functions and APIs. All the AWS::Serverless::Function,

AWS::Serverless::Api, and AWS::Serverless::SimpleTable resources inherit the properties that are defined in the Globals section. For more information about this section, see Globals section of the AWS SAM template (p. 29).

Resources section. In AWS SAM templates the Resources section can contain a combination of AWS CloudFormation resources and AWS SAM resources. For more information about AWS CloudFormation resources, see AWS resource and property types reference in the AWS CloudFormation User Guide. For more information about AWS SAM resources, see AWS SAM resource and property reference (p. 33).

Parameters section. Objects that are declared in the Parameters section cause the sam deploy -- guided command to present additional prompts to the user. For examples of declared objects and the corresponding prompts, see sam deploy (p. 270) in the AWS SAM CLI command reference.

All other sections of an AWS SAM template file correspond to the AWS CloudFormation template file section of the same name.

(34)

YAML

The following example shows a YAML-formatted template fragment.

Transform: AWS::Serverless-2016-10-31 Globals:

set of globals Description:

String Metadata:

template metadata Parameters:

set of parameters Mappings:

set of mappings Conditions:

set of conditions Resources:

set of resources Outputs:

set of outputs

Template sections

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. 29)

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)

A text string that describes the template.

This section corresponds directly with the Description section of AWS CloudFormation templates.

參考文獻

相關文件

If the best number of degrees of freedom for pure error can be specified, we might use some standard optimality criterion to obtain an optimal design for the given model, and

The Model-Driven Simulation (MDS) derives performance information based on the application model by analyzing the data flow, working set, cache utilization, work- load, degree

„ A socket is a file descriptor that lets an application read/write data from/to the network. „ Once configured the

According to Ho (2003), Canto Pop “has developed since the early 1970s with a demand from Hong Kong audiences for popular music in their own dialect, Cantonese. Cantonese is one

AWS中絕大多數的資料、備份、機器配 置,甚至是異地備份。Code Spaces表 示,這樣的情況已讓該公司無法再繼續 運作.

To illustrate how LINDO can be used to solve a preemptive goal programming problem, let’s look at the Priceler example with our original set of priorities (HIM followed by LIP

Key Successful Factors of Health Care Industry Management from the Resource Based Approach --- An Application of Strategic Matrix Method.. Student: Yu-Min Su Advisor:

Instead of the conventional discrete model using an equivalent mass and spring, a continuous geometrical model of the finite element method is utilized to the dynamic analysis of