教程:部署 Hello World 应用程序 - Amazon Serverless Application Model
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

教程:部署 Hello World 应用程序

在本教程中,您将使用 Amazon Serverless Application Model 命令行界面 (Amazon SAM CLI) 来完成以下操作:

  • 初始化、构建和部署示例 Hello World 应用程序。

  • 进行本地更改并同步到 Amazon CloudFormation。

  • 在 Amazon Web Services 云 中测试您的应用程序。

  • (可选)在开发主机上执行本地测试。

  • 从 Amazon Web Services 云 中删除示例应用程序。

示例 Hello World 应用程序实现了基本的 API 后端。它由以下资源组成:

  • Amazon API Gateway – 将用于调用函数的 API 端点。

  • Amazon Lambda– 处理 HTTP API GET 请求并返回 hello world 消息的函数。

  • Amazon Identity and Access Management(IAM) 角色 – 为服务提供安全交互的权限。

下图显示此应用程序的组件:


			向 API 网关端点发送 GET 请求时调用的 Lambda 函数的图表

先决条件

确认您是否已完成以下操作:

第 1 步:初始化示例 Hello World 应用程序

在此步骤中,您将使用 Amazon SAM CLI 在本地计算机上创建示例 Hello World 应用程序项目。

初始化示例 Hello World 应用程序
  1. 在命令行中,从您选择的起始目录运行以下内容:

    $ sam init
  2. Amazon SAM CLI 将指导您完成新应用程序的初始化。配置以下内容:

    1. 选择Amazon快速入门模板以选择起始模板。

    2. 选择 Hello World 示例模板并下载。

    3. 使用 Python 运行时系统和 zip 包类型。

    4. 在本教程中,请选择退出 Amazon X-Ray 跟踪。若要了解更多信息,请参阅《Amazon X-Ray 开发人员指南》中的什么是 Amazon X-Ray?

    5. 在本教程中,请选择退出使用 Amazon CloudWatch 应用程序见解进行监控。要了解更多信息,请参阅《亚马逊 CloudWatch 用户指南》中的 “亚马逊 CloudWatch 应用程序见解”。

    6. 将应用程序命名为 sam-app

    使用 Amazon SAM CLI 交互式流程:

    • 方括号 ([ ]) 表示默认值。将答案留空以选择默认值。

    • 输入 y 以选择,输入 n 以选择

    以下是 sam init 交互式流程的示例:

    $ sam init ... Which template source would you like to use? 1 - AWS Quick Start Templates 2 - Custom Template Location Choice: 1 Choose an AWS Quick Start application template 1 - Hello World Example 2 - Multi-step workflow 3 - Serverless API 4 - Scheduled task 5 - Standalone function 6 - Data processing 7 - Hello World Example With Powertools 8 - Infrastructure event management 9 - Serverless Connector Hello World Example 10 - Multi-step workflow with Connectors 11 - Lambda EFS example 12 - DynamoDB Example 13 - Machine Learning Template: 1 Use the most popular runtime and package type? (Python and zip) [y/N]: y Would you like to enable X-Ray tracing on the function(s) in your application? [y/N]: ENTER Would you like to enable monitoring using CloudWatch Application Insights? For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER Project name [sam-app]: ENTER
  3. Amazon SAM CLI 下载您的起始模板并在您的本地计算机上创建应用程序项目目录结构。下面是 Amazon SAM CLI 输出的一个示例:

    Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)
    
        -----------------------
        Generating application:
        -----------------------
        Name: sam-app
        Runtime: python3.9
        Architectures: x86_64
        Dependency Manager: pip
        Application Template: hello-world
        Output Directory: .
        Configuration file: sam-app/samconfig.toml
    
        Next steps can be found in the README file at sam-app/README.md
    
    
    Commands you can use next
    =========================
    [*] Create pipeline: cd sam-app && sam pipeline init --bootstrap
    [*] Validate SAM template: cd sam-app && sam validate
    [*] Test Function in the Cloud: cd sam-app && sam sync --stack-name {stack-name} --watch
  4. 在命令行中,移至新创建的 sam-app 目录。以下是 Amazon SAM CLI 所创建内容的示例:

    $ cd sam-app $ tree ├── README.md ├── __init__.py ├── events │ └── event.json ├── hello_world │ ├── __init__.py │ ├── app.py │ └── requirements.txt ├── samconfig.toml ├── template.yaml └── tests ├── __init__.py ├── integration │ ├── __init__.py │ └── test_api_gateway.py ├── requirements.txt └── unit ├── __init__.py └── test_handler.py 6 directories, 14 files

    需要重点介绍的一些重要文件:

    • hello_world/app.py – 包含您的 Lambda 函数代码。

    • hello_world/requirements.txt – 包含您的 Lambda 函数所需的任何 Python 依赖项。

    • samconfig.toml – 应用程序的配置文件,用于存储 Amazon SAM CLI 使用的默认参数。

    • template.yaml – 包含您的应用程序基础设施代码的 Amazon SAM 模板。

现在,您的本地计算机上有了编写完整的无服务器应用程序!

第 2 步:构建应用程序

在此步骤中,您将使用 Amazon SAM CLI 来构建应用程序并准备部署。在构建时,Amazon SAM CLI 会创建一个 .aws-sam 目录并在其中整理函数依赖项、项目代码和项目文件。

要构建应用程序
  • sam-app 项目目录,在命令行中运行以下命令:

    $ sam build
    注意

    如果您的本地计算机上没有 Python,请改用 sam build --use-container 命令。Amazon SAM CLI 将创建一个包含函数运行时系统和依赖项的 Docker 容器。此命令要求本地计算机上有 Docker。要安装 Docker,请参阅 安装 Docker

    下面是 Amazon SAM CLI 输出的一个示例:

    $ sam build Starting Build use cache Manifest file is changed (new hash: 3298f1304...d4d421) or dependency folder (.aws-sam/deps/4d3dfad6-a267-47a6-a6cd-e07d6fae318c) is missing for (HelloWorldFunction), downloading dependencies and copying/building source Building codeuri: /Users/.../Demo/sam-tutorial1/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction Running PythonPipBuilder:CleanUp Running PythonPipBuilder:ResolveDependencies Running PythonPipBuilder:CopySource Running PythonPipBuilder:CopySource Build Succeeded Built Artifacts : .aws-sam/build Built Template : .aws-sam/build/template.yaml Commands you can use next ========================= [*] Validate SAM template: sam validate [*] Invoke Function: sam local invoke [*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch [*] Deploy: sam deploy --guided

    以下是 Amazon SAM CLI 创建的 .aws-sam 目录的简短示例:

    .aws-sam
    ├── build
    │   ├── HelloWorldFunction
    │   │   ├── __init__.py
    │   │   ├── app.py
    │   │   └── requirements.txt
    │   └── template.yaml
    └── build.toml

需要重点介绍的一些重要文件:

  • build/HelloWorldFunction – 包含您的 Lambda 函数代码和依赖项。Amazon SAM CLI 为应用程序中的每个函数创建一个目录。

  • build/template.yaml – 包含部署时 Amazon CloudFormation 引用的 Amazon SAM 模板副本。

  • build.toml – 用于存储构建和部署应用程序时 Amazon SAM CLI 引用的默认参数值的配置文件。

您现在已准备好将应用程序部署到 Amazon Web Services 云。

第 3 步:将应用程序部署到 Amazon Web Services 云

注意

此步骤要求 Amazon 凭证配置。有关更多信息,请参阅Amazon SAM先决条件中的第 5 步:使用 Amazon CLI 配置 Amazon 凭证

在此步骤中,您将使用 Amazon SAM CLI 将应用程序部署到 Amazon Web Services 云。Amazon SAM CLI 将执行以下操作:

  • 指导您配置应用程序设置以进行部署。

  • 将应用程序文件上载到 Amazon Simple Storage Service (Amazon S3)。

  • 将您的 Amazon SAM 模板转换为 Amazon CloudFormation 模板。然后,它会将您的模板上传到 Amazon CloudFormation 服务以配置您的 Amazon 资源。

部署 应用程序
  1. sam-app 项目目录,在命令行中运行以下命令:

    $ sam deploy --guided
  2. 按照 Amazon SAM CLI 交互式流程配置您的应用程序设置。配置以下内容:

    1. Amazon CloudFormation 堆栈名称 – 堆栈是可作为单个单元管理的一系列 Amazon 资源。要了解更多信息,请参阅《Amazon CloudFormation 用户指南》中的使用堆栈

    2. 要将您的 Amazon CloudFormation 堆栈部署到的 Amazon Web Services 区域。有关更多信息,请参阅《Amazon CloudFormation 用户指南》中的 Amazon CloudFormation 端点

    3. 在本教程中,请取消选择在部署前确认更改

    4. 允许创建 IAM 角色 – 这允许 Amazon SAM 创建 API Gateway 资源和 Lambda 函数资源进行交互所必需的 IAM 角色。

    5. 在本教程中,请取消选择禁用回滚

    6. HelloWorldFunction 未定义授权即允许 — 显示此消息是因为您的 API Gateway 端点已配置为无需授权即可公开访问。由于这是您的 Hello World 应用程序的预期配置,因此请允许 Amazon SAM CLI 继续。有关配置授权的更多信息,请参阅 控制 API Gateway API 访问权限

    7. 将参数保存到配置文件 – 这将使用您的部署首选项更新应用程序的 samconfig.toml 文件。

    8. 选择默认配置文件名称

    9. 选择默认配置环境

    下面是一个 sam deploy --guided 交互式流程的示例输出:

    $ sam-app sam deploy --guided Configuring SAM deploy ====================== Looking for config file [samconfig.toml] : Found Reading default arguments : Success Setting default arguments for 'sam deploy' ========================================= Stack Name [sam-app]: ENTER AWS Region [us-west-2]: ENTER #Shows you resources changes to be deployed and require a 'Y' to initiate deploy Confirm changes before deploy [Y/n]: n #SAM needs permission to be able to create roles to connect to the resources in your template Allow SAM CLI IAM role creation [Y/n]: ENTER #Preserves the state of previously provisioned resources when an operation fails Disable rollback [y/N]: ENTER HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y Save arguments to configuration file [Y/n]: ENTER SAM configuration file [samconfig.toml]: ENTER SAM configuration environment [default]: ENTER
  3. Amazon SAM CLI 通过执行以下操作部署您的应用程序:

    • Amazon SAM CLI 创建一个 Amazon S3 存储桶并上传您的 .aws-sam 目录。

    • Amazon SAM CLI 将您的 Amazon SAM 模板转换为 Amazon CloudFormation 并将其上传到 Amazon CloudFormation 服务。

    • Amazon CloudFormation 配置您的资源。

    在部署期间,Amazon SAM CLI 会显示您的进度。下面是一个示例输出:

    Looking for resources needed for deployment:
    
        Managed S3 bucket: aws-sam-cli-managed-default-samclisourcebucket-1a4x26zbcdkqr
        A different default S3 bucket can be set in samconfig.toml
    
        Parameter "stack_name=sam-app" in [default.deploy.parameters] is defined as a global parameter [default.global.parameters].
        This parameter will be only saved under [default.global.parameters] in /Users/.../Demo/sam-tutorial1/sam-app/samconfig.toml.
    
        Saved arguments to config file
        Running 'sam deploy' for future deployments will use the parameters saved above.
        The above parameters can be changed by modifying samconfig.toml
        Learn more about samconfig.toml syntax at
        https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-config.html
    
    File with same data already exists at sam-app/da3c598813f1c2151579b73ad788cac8, skipping upload
    
        Deploying with following values
        ===============================
        Stack name                   : sam-app
        Region                       : us-west-2
        Confirm changeset            : False
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisourcebucket-1a4x26zbcdkqr
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}
    
    Initiating deployment
    =====================
    
    File with same data already exists at sam-app/2bebf67c79f6a743cc5312f6dfc1efee.template, skipping upload
    
    
    Waiting for changeset to be created..
    
    CloudFormation stack changeset
    ---------------------------------------------------------------------------------------------------------------------------------------------
    Operation                           LogicalResourceId                   ResourceType                        Replacement
    ---------------------------------------------------------------------------------------------------------------------------------------------
    * Modify                            HelloWorldFunction                  AWS::Lambda::Function               False
    * Modify                            ServerlessRestApi                   AWS::ApiGateway::RestApi            False
    - Delete                            AwsSamAutoDependencyLayerNestedSt   AWS::CloudFormation::Stack          N/A
                                        ack
    ---------------------------------------------------------------------------------------------------------------------------------------------
    
    
    Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1678917603/22e05525-08f9-4c52-a2c4-f7f1fd055072
    
    
    2023-03-15 12:00:16 - Waiting for stack create/update to complete
    
    CloudFormation events from stack operations (refresh every 0.5 seconds)
    ---------------------------------------------------------------------------------------------------------------------------------------------
    ResourceStatus                      ResourceType                        LogicalResourceId                   ResourceStatusReason
    ---------------------------------------------------------------------------------------------------------------------------------------------
    UPDATE_IN_PROGRESS                  AWS::Lambda::Function               HelloWorldFunction                  -
    UPDATE_COMPLETE                     AWS::Lambda::Function               HelloWorldFunction                  -
    UPDATE_COMPLETE_CLEANUP_IN_PROGRE   AWS::CloudFormation::Stack          sam-app                             -
    SS
    DELETE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                            ack
    DELETE_COMPLETE                     AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                            ack
    UPDATE_COMPLETE                     AWS::CloudFormation::Stack          sam-app                             -
    ---------------------------------------------------------------------------------------------------------------------------------------------
    
    CloudFormation outputs from deployed stack
    ----------------------------------------------------------------------------------------------------------------------------------------------
    Outputs
    ----------------------------------------------------------------------------------------------------------------------------------------------
    Key                 HelloWorldFunctionIamRole
    Description         Implicit IAM Role created for Hello World function
    Value               arn:aws:iam::012345678910:role/sam-app-HelloWorldFunctionRole-15GLOUR9LMT1W
    
    Key                 HelloWorldApi
    Description         API Gateway endpoint URL for Prod stage for Hello World function
    Value               https://<restapiid>.execute-api.us-west-2.amazonaws.com/Prod/hello/
    
    Key                 HelloWorldFunction
    Description         Hello World Lambda Function ARN
    Value               arn:aws:lambda:us-west-2:012345678910:function:sam-app-HelloWorldFunction-yQDNe17r9maD
    ----------------------------------------------------------------------------------------------------------------------------------------------
    
    
    Successfully created/updated stack - sam-app in us-west-2

您的应用程序现已部署并在 Amazon Web Services 云 中运行!

第 4 步:运行应用程序

在此步骤中,您将向 API 端点发送 GET 请求并查看 Lambda 函数输出。

获取您的 API 端点值
  1. 从上一步 Amazon SAM CLI 显示的信息中,找到 Outputs 部分。在该部分找到您的 HelloWorldApi 资源以查找 HTTP 端点值。下面是一个示例输出:

    ----------------------------------------------------------------------------------------------------------------------------------------------
    Outputs
    ----------------------------------------------------------------------------------------------------------------------------------------------
    ...
    Key                 HelloWorldApi
    Description         API Gateway endpoint URL for Prod stage for Hello World function
    Value               https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/
    ...
    ----------------------------------------------------------------------------------------------------------------------------------------------
  2. 或者,您可以使用 sam list endpoints --output json 命令获取此信息。下面是一个示例输出:

    $ sam list endpoints --output json 2023-03-15 12:39:19 Loading policies from IAM... 2023-03-15 12:39:25 Finished loading policies from IAM. [ { "LogicalResourceId": "HelloWorldFunction", "PhysicalResourceId": "sam-app-HelloWorldFunction-yQDNe17r9maD", "CloudEndpoint": "-", "Methods": "-" }, { "LogicalResourceId": "ServerlessRestApi", "PhysicalResourceId": "ets1gv8lxi", "CloudEndpoint": [ "https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod", "https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Stage" ], "Methods": [ "/hello['get']" ] } ]
要调用函数
  • 使用浏览器或命令行向 API 端点发送 GET 请求。以下是使用 curl 命令的示例。

    $ curl https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/ {"message": "hello world"}

第 5 步:在 Amazon Web Services 云 中与您的函数进行交互

在此步骤中,您将使用 Amazon SAM CLI 在 Amazon Web Services 云 中调用 Lambda 函数。

要调用云端的 Lambda 函数
  1. 记下上一步中函数的 LogicalResourceId。它应该是 HelloWorldFunction

  2. sam-app 项目目录,在命令行中运行以下命令:

    $ sam remote invoke HelloWorldFunction --stack-name sam-app
  3. Amazon SAM CLI 在云端调用您的函数并返回响应。下面是一个示例输出:

    $ sam remote invoke HelloWorldFunction --stack-name sam-app Invoking Lambda Function HelloWorldFunction START RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9 Version: $LATEST END RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9 REPORT RequestId: d5ef494b-5f45-4086-86fd-d7322fa1a1f9 Duration: 6.62 ms Billed Duration: 7 ms Memory Size: 128 MB Max Memory Used: 67 MB Init Duration: 164.06 ms {"statusCode":200,"body":"{\"message\":\"hello world\"}"}%

第 6 步:修改应用程序并将其同步到 Amazon Web Services 云

在此步骤中,您将使用 Amazon SAM CLI sam sync --watch 命令将本地更改同步到 Amazon Web Services 云。

使用 sam 同步
  1. sam-app 项目目录,在命令行中运行以下命令:

    $ sam sync --watch
  2. Amazon SAM CLI 提示您确认正在同步开发堆栈。由于 sam sync --watch 命令会自动将本地更改实时部署到 Amazon Web Services 云 中,因此我们建议仅在开发环境中使用。

    Amazon SAM CLI 在开始监控本地更改之前会执行初始部署。下面是一个示例输出:

    $ sam sync --watch The SAM CLI will use the AWS Lambda, Amazon API Gateway, and AWS StepFunctions APIs to upload your code without performing a CloudFormation deployment. This will cause drift in your CloudFormation stack. **The sync command should only be used against a development stack**. Confirm that you are synchronizing a development stack. Enter Y to proceed with the command, or enter N to cancel: [Y/n]: y Queued infra sync. Waiting for in progress code syncs to complete... Starting infra sync. Manifest is not changed for (HelloWorldFunction), running incremental build Building codeuri: /Users/.../Demo/sam-tutorial1/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction Running PythonPipBuilder:CopySource Build Succeeded Successfully packaged artifacts and wrote output template to file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpq3x9vh63. Execute the following command to deploy the packaged template sam deploy --template-file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpq3x9vh63 --stack-name <YOUR STACK NAME> Deploying with following values =============================== Stack name : sam-app Region : us-west-2 Disable rollback : False Deployment s3 bucket : aws-sam-cli-managed-default-samclisourcebucket-1a4x26zbcdkqr Capabilities : ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"] Parameter overrides : {} Signing Profiles : null Initiating deployment ===================== 2023-03-15 13:10:05 - Waiting for stack create/update to complete CloudFormation events from stack operations (refresh every 0.5 seconds) --------------------------------------------------------------------------------------------------------------------------------------------- ResourceStatus ResourceType LogicalResourceId ResourceStatusReason --------------------------------------------------------------------------------------------------------------------------------------------- UPDATE_IN_PROGRESS AWS::CloudFormation::Stack sam-app Transformation succeeded CREATE_IN_PROGRESS AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedSt - ack CREATE_IN_PROGRESS AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedSt Resource creation Initiated ack CREATE_COMPLETE AWS::CloudFormation::Stack AwsSamAutoDependencyLayerNestedSt - ack UPDATE_IN_PROGRESS AWS::Lambda::Function HelloWorldFunction - UPDATE_COMPLETE AWS::Lambda::Function HelloWorldFunction - UPDATE_COMPLETE_CLEANUP_IN_PROGRE AWS::CloudFormation::Stack sam-app - SS UPDATE_COMPLETE AWS::CloudFormation::Stack sam-app - --------------------------------------------------------------------------------------------------------------------------------------------- CloudFormation outputs from deployed stack ---------------------------------------------------------------------------------------------------------------------------------------------- Outputs ---------------------------------------------------------------------------------------------------------------------------------------------- Key HelloWorldFunctionIamRole Description Implicit IAM Role created for Hello World function Value arn:aws:iam::012345678910:role/sam-app-HelloWorldFunctionRole-15GLOUR9LMT1W Key HelloWorldApi Description API Gateway endpoint URL for Prod stage for Hello World function Value https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/ Key HelloWorldFunction Description Hello World Lambda Function ARN Value arn:aws:lambda:us-west-2:012345678910:function:sam-app-HelloWorldFunction-yQDNe17r9maD ---------------------------------------------------------------------------------------------------------------------------------------------- Stack update succeeded. Sync infra completed. Infra sync completed. CodeTrigger not created as CodeUri or DefinitionUri is missing for ServerlessRestApi.

接下来,您将修改 Lambda 函数代码。Amazon SAM CLI 将自动检测此更改,并将应用程序同步到 Amazon Web Services 云。

修改和同步应用程序
  1. 在选定 IDE 中打开 sam-app/hello_world/app.py 文件。

  2. 更改 message 然后保存文件。以下是 示例:

    import json ... def lambda_handler(event, context): ... return { "statusCode": 200, "body": json.dumps({ "message": "hello everyone!", ... }), }
  3. Amazon SAM CLI 会检测您的更改并将应用程序同步到 Amazon Web Services 云。下面是一个示例输出:

    Syncing Lambda Function HelloWorldFunction...
    Manifest is not changed for (HelloWorldFunction), running incremental build
    Building codeuri: /Users/.../Demo/sam-tutorial1/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
    Running PythonPipBuilder:CopySource
    Finished syncing Lambda Function HelloWorldFunction.
  4. 要验证您的更改,请再次向 API 端点发送 GET 请求。

    $ curl https://ets1gv8lxi.execute-api.us-west-2.amazonaws.com/Prod/hello/ {"message": "hello everyone!"}

第 7 步:(可选)在本地测试应用程序

注意

此步骤是可选的,因为它要求本地计算机上有 Docker。

重要

要使用 Amazon SAM CLI 进行本地测试,必须已安装并配置 Docker。有关更多信息,请参阅 安装 Docker

在此步骤中,您将使用 Amazon SAM CLI sam local 命令在本地测试应用程序。为此,Amazon SAM CLI 使用 Docker 创建本地环境。此本地环境模拟基于云的 Lambda 函数执行环境。

您将执行以下操作:

  1. 为 Lambda 函数创建本地环境并调用它。

  2. 在本地托管您的 HTTP API 端点,并使用它调用 Lambda 函数。

要在本地调用 Lambda 函数
  1. sam-app 项目目录,在命令行中运行以下命令:

    $ sam local invoke
  2. Amazon SAM CLI 创建本地 Docker 容器并调用您的函数。下面是一个示例输出:

    $ sam local invoke Invoking app.lambda_handler (python3.9) Local image was not found. Removing rapid images for repo public.ecr.aws/sam/emulation-python3.9 Building image..................... Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64. Mounting /Users/.../Demo/sam-tutorial1/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container START RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6 Version: $LATEST END RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6 REPORT RequestId: b046db01-2a00-415d-af97-35f3a02e9eb6 Init Duration: 1.01 ms Duration: 633.45 ms Billed Duration: 634 ms Memory Size: 128 MB Max Memory Used: 128 MB {"statusCode": 200, "body": "{\"message\": \"hello world\"}"}
在本地托管 API
  1. sam-app 项目目录,在命令行中运行以下命令:

    $ sam local start-api
  2. Amazon SAM CLI 为您的 Lambda 函数创建一个本地 Docker 容器,并创建一个本地 HTTP 服务器来模拟您的 API 端点。下面是一个示例输出:

    $ sam local start-api Initializing the lambda functions containers. Local image is up-to-date Using local image: public.ecr.aws/lambda/python:3.9-rapid-x86_64. Mounting /Users/.../Demo/sam-tutorial1/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container Containers Initialization is done. Mounting HelloWorldFunction at http://127.0.0.1:3000/hello [GET] 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. If you used sam build before running local commands, you will need to re-run sam build for the changes to be picked up. You only need to restart SAM CLI if you update your AWS SAM template 2023-03-15 14:25:21 WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:3000 2023-03-15 14:25:21 Press CTRL+C to quit
  3. 使用浏览器或命令行,向本地 API 端点发送 GET 请求。以下是使用 curl 命令的示例。

    $ curl http://127.0.0.1:3000/hello {"message": "hello world"}

第 8 步:从中 Amazon Web Services 云 删除应用程序

在此步骤中,您将使用 Amazon SAM CLI sam delete 命令从 Amazon Web Services 云 中删除应用程序。

从 Amazon Web Services 云 中删除您的应用程序
  1. sam-app 项目目录,在命令行中运行以下命令:

    $ sam delete
  2. Amazon SAM CLI 会请您确认。然后,它将删除您应用程序的 Amazon S3 存储桶和 Amazon CloudFormation 堆栈。下面是一个示例输出:

    $ sam delete Are you sure you want to delete the stack sam-app in the region us-west-2 ? [y/N]: y Are you sure you want to delete the folder sam-app in S3 which contains the artifacts? [y/N]: y - Deleting S3 object with key c6ce8fa8b5a97dd022ecd006536eb5a4 - Deleting S3 object with key 5d513a459d062d644f3b7dd0c8b56a2a.template - Deleting S3 object with key sam-app/2bebf67c79f6a743cc5312f6dfc1efee.template - Deleting S3 object with key sam-app/6b208d0e42ad15d1cee77d967834784b.template - Deleting S3 object with key sam-app/da3c598813f1c2151579b73ad788cac8 - Deleting S3 object with key sam-app/f798cdd93cee188a71d120f14a035b11 - Deleting Cloudformation stack sam-app Deleted successfully

故障排除

要对 Amazon SAM CLI 进行故障排除,请参阅 Amazon SAM CLI 故障排除

了解更多信息

要进一步了解 Amazon SAM 的更多信息,请参阅以下资源:

  • 完整 Amazon SAM 研讨会 - 旨在指导您使用 Amazon SAM 提供的许多主要功能的研讨会。

  • 使用 SAM 的会话 - 由 Amazon 无服务器开发人员支持团队制作的关于使用 Amazon SAM 的视频系列。

  • Serverless Land – 汇集了关于 Amazon 无服务器项目的最新信息、博客、视频、代码和学习资源的网站。