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

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

教程:部署 Hello World 应用程序

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

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

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

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

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

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

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

  • Amazon API Gateway — 您将用来调用函数的 API 终端节点。

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

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

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


			在向 API Gateway 端点发送 GET 请求时,会调用 Lambda 函数。

先决条件

确认您是否已完成以下内容:

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

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

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

    $ sam init
  2. CAmazon SAM LI 将指导您初始化新应用程序。配置以下内容:

    1. 选择 “Amazon快速启动模板” 以选择起始模板。

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

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

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

    5. 在本教程中,选择不使用亚马逊 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]: 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]: Project name [sam-app]:
  3. CAmazon SAM LI 下载您的起始模板并在您的本地计算机上创建应用程序项目目录结构。以下是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 SAMCLI 会创建一个.aws-sam目录并在那里组织你的函数依赖关系、项目代码和项目文件。

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

    $ sam build
    注意

    如果您的本地计算机Python上没有,请改用该sam build --use-container 命令。Amazon SAMCLI 将创建一个包含您的函数的运行时和依赖项的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 函数代码和依赖项。CAmazon SAM LI 为应用程序中的每个函数创建一个目录。

  • 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 云。CAmazon SAM LI 将执行以下操作:

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

  • 将应用程序文件上传到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 Web Services 区域用于将您的Amazon CloudFormation堆栈部署到。有关更多信息,请参阅 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]: AWS Region [us-west-2]: #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]: #Preserves the state of previously provisioned resources when an operation fails Disable rollback [y/N]: HelloWorldFunction may not have authorization defined, Is this okay? [y/N]: y Save arguments to configuration file [Y/n]: SAM configuration file [samconfig.toml]: SAM configuration environment [default]:
  3. CAmazon SAM LI 通过执行以下操作来部署您的应用程序:

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

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

    • Amazon CloudFormation配置您的资源。

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

    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:513423067560: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::513423067560: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:513423067560: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 CLIsam sync --watch 命令将本地更改同步到Amazon Web Services 云。

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

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

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

    $ 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::513423067560: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:513423067560: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 函数代码。CAmazon SAM LI 将自动检测到此更改并将您的应用程序同步到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. CAmazon SAM LI 会检测您的更改并将您的应用程序同步到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!"}

步骤 6:(可选)在本地测试应用程序

注意

此步骤是可选的,因为它需要在本地计算机Docker上执行。

重要

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

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

您将执行以下操作:

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

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

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

    $ sam local invoke
  2. CAmazon SAM LI 创建本地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 SAMCLI 为您的 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"}

步骤 7:从Amazon Web Services 云

在此步骤中,您可以使用Amazon SAM CLIsam delete 命令从中删除您的应用程序Amazon Web Services 云。

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

    $ sam delete
  2. CAmazon SAM LI 将要求您确认。然后,它将删除您的应用程序的 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 SAMCLI 纠正

了解更多信息

要继续了解Amazon SAM,请参阅以下资源: