教學課程:部署 Hello World 應用程式 - AWS Serverless Application Model

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

教學課程:部署 Hello World 應用程式

在本自學課程中,您將使用AWS Serverless Application Model指令行介面 (AWS SAMCLI) 完成以下作業:

  • 初始化、建置和部署範例 Hello World 應用程式。

  • 進行本機變更並同步至AWS CloudFormation。

  • 在中測試您的應用程式AWS 雲端。

  • 或者,在您的開發主機上執行本機測試。

  • 從中刪除範例應用程式AWS 雲端。

您好世界應用程式範例會實作基本的 API 後端。它由以下資源組成:

  • Amazon API Gateway — 您將用來調用函數的 API 端點。

  • AWS Lambda— 處理 HTTP API GET 要求並傳回hello world訊息的函數。

  • AWS Identity and Access Management(IAM) 角色 — 為服務佈建許可以安全地互動。

下圖顯示此應用程式的組件:


			當您將 GET 要求傳送至 API Gateway 端點時叫用的 Lambda 函數圖表。

必要條件

確認您已完成下列項目:

步驟 1:初始化範例 Hello World 應用程式

在此步驟中,您將使用在AWS SAMCLI本機電腦上建立範例 Hello World 應用程式專案。

若要初始化範例 Hello World 應用程式
  1. 在命令行中,從您選擇的起始目錄運行以下命令:

    $ sam init
  2. AWS SAMCLI將引導您完成初始化新的應用程式。設定下列項目:

    1. 選取「AWS快速入門範本」以選擇起始範本。

    2. 選擇你好世界範例範本並下載。

    3. 使用Python執行階段和zip套件類型。

    4. 在本教學課程中,請選擇退出AWS X-Ray追蹤。若要深入瞭解,請參閱什麼是AWS X-Ray?AWS X-Ray開發人員指南中。

    5. 在本教學課程中,請選擇退出使 CloudWatch 用 Amazon 應用程式洞察進行監控。若要進一步了解,請參閱 Amazon CloudWatch 使用者指南中的 Amazon 應用 CloudWatch 程式深入解析。

    6. 將您的應用程序命名為 sam-app

    若要使用AWS SAMCLI互動式流程:

    • 括號 ([ ]) 表示預設值。將您的答案留空,以選取預設值。

    • 輸入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. 會下AWS SAMCLI載您的起始範本,並在本機電腦上建立應用程式專案目錄結構。以下是AWS SAMCLI輸出的範例:

    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目錄。下面是什麼創建的一個例子:AWS SAMCLI

    $ 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— 應用程式的組態檔案,儲存使用的預設參數AWS SAMCLI。

    • template.yaml— 包含應用程式基礎結構程式碼的AWS SAM範本。

您現在在本機電腦上擁有完全撰寫的無伺服器應用程式!

步驟 2:建置您的應用程式

在此步驟中,您可AWS SAMCLI以使用建置應用程式並準備部署。當您建置時,AWS SAMCLI會建立一個.aws-sam目錄,並在該處組織函式相依性、專案程式碼和專案檔案。

建立您的應用程式
  • 在命令行中,從sam-app項目目錄中運行以下命令:

    $ sam build
    注意

    如果您的本地計算機Python上沒有,請改用sam build --use-container 命令。AWS SAMCLI將會建立包含函式執行階段和相依性的Docker容器。此指令需要Docker在本機電腦上使用。若要安裝Docker,請參閱安裝 Docker

    以下是AWS SAMCLI輸出的範例:

    $ 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

    以下是 AWS SAM CLI 建立之目.aws-sam錄的簡短範例:

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

要突出顯示的一些重要文件:

  • build/HelloWorldFunction— 包含您的 Lambda 函數程式碼和相依性。AWS SAMCLI會為應用程式中的每個函數建立一個目錄。

  • build/template.yaml— 包含部署AWS CloudFormation時參考的AWS SAM範本副本。

  • build.toml— 儲存建置和部署應用程式AWS SAMCLI時所參考的預設參數值的組態檔案。

您現在可以將應用程式部署到AWS 雲端.

步驟 3:將您的應用程式部署到 AWS 雲端

注意

此步驟需要設定AWS認證。如需詳細資訊,請參閱 AWS SAM 先決條件 中的 步驟 5:使用設AWS CLI定AWS認證

在此步驟中,您可AWS SAMCLI以使用將應用程式部署到AWS 雲端. AWS SAMCLI將執行以下操作:

  • 引導您設定用於部署的應用程式設定。

  • 將您的應用程式檔案上傳到亞馬遜簡易儲存服務 (Amazon S3)。

  • 將AWS SAM範本轉換為AWS CloudFormation範本。然後,它將您的模板上傳到AWS CloudFormation服務以佈建您的AWS資源。

部署您的 應用程式
  1. 在命令行中,從sam-app項目目錄中運行以下命令:

    $ sam deploy --guided
  2. 遵循AWS SAMCLI互動式流程來設定您的應用程式設定。設定下列項目:

    1. AWS CloudFormation堆疊名稱 — 堆疊是您可以作為單一單元來管理的AWS資源集合。若要深入瞭解,請參閱使用AWS CloudFormation者指南中的使用堆疊

    2. AWS 區域要將您的AWS CloudFormation堆疊部署到. 如需詳細資訊,請參閱AWS CloudFormation使用指南中的AWS CloudFormation端點

    3. 在本教學課程中,請在部署前選擇退出確認變更

    4. 允許 IAM 角色建立 — 這可讓您AWS SAM建立 API Gateway 資源和 Lambda 函數資源進行互動所需的 IAM 角色。

    5. 在本教學課程中,請選擇不停用復原功能

    6. HelloWorldFunction 未定義授權即允許 — 顯示此訊息是因為您的 API Gateway 端點設定為可公開存取,未經授權。由於這是您 Hello World 應用程式的預定組態,因此請允許AWS SAMCLI繼續。如需有關配置授權的詳細資訊,請參閱控制對 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. 透過執行下列動作來AWS SAMCLI部署您的應用程式:

    • AWS SAMCLI創建一個 Amazon S3 存儲桶並上傳您的.aws-sam目錄。

    • 將您的AWS SAM模板AWS SAMCLI轉換為AWS CloudFormation並將其上傳到AWS CloudFormation服務。

    • AWS CloudFormation提供您的資源。

    在部署期間,會AWS 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: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

您的應用程式現在已部署並在AWS 雲端!

步驟 4:執行您的應用程式

在此步驟中,您將向 API 端點傳送 GET 請求,並查看您的 Lambda 函數輸出。

取得您的 API 端點值
  1. 從上一個步驟AWS SAMCLI中顯示的資訊中,找出該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']" ] } ]
調用你的函數
  • 使用瀏覽器或命令列,將 GET 要求傳送至您的 API 端點。以下是使用 curl 命令的示例:

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

第 5 步:與您的功能進行交互 AWS 雲端

在此步驟中,您可以使AWS SAMCLI用在中叫用您的 Lambda 函數AWS 雲端。

若要在雲端中叫用 Lambda 函數
  1. 記下上一步LogicalResourceId中的功能。它應該是HelloWorldFunction

  2. 在命令行中,從sam-app項目目錄中運行以下命令:

    $ sam remote invoke HelloWorldFunction --stack-name sam-app
  3. 會在雲端AWS SAMCLI叫用您的函式並傳回回應。下面是一個示例輸出:

    $ 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:修改您的應用程序並將其同步到 AWS 雲端

在此步驟中,您可以使用AWS SAMCLIsam sync --watch指令將本機變更同步至AWS 雲端.

若要使用 sam 同步
  1. 在命令行中,從sam-app項目目錄中運行以下命令:

    $ sam sync --watch
  2. 系AWS SAMCLI統會提示您確認是否正在同步開發堆疊。由於該sam sync --watch命令會即時自動將本機變更部署到,因此我們建議僅用於開發環境。AWS 雲端

    會在開始監視本機變更之前AWS 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::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 函數程式碼。AWS SAMCLI會自動偵測此變更,並將您的應用程式同步至AWS 雲端.

若要修改和同步您的應用程式
  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. 會AWS SAMCLI偵測您的變更,並將您的應用程式同步到AWS 雲端. 下面是一個示例輸出:

    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. 若要驗證您的變更,請再次傳送 GET 要求至您的 API 端點。

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

步驟 7:(可選)在本地測試您的應用程序

注意

此步驟是可選的,因為它需要Docker在本地計算機上。

重要

若要使用進AWS SAMCLI行本機測試,您必須已Docker安裝並設定。如需詳細資訊,請參閱 安裝 Docker

在此步驟中,您可以使用AWS SAMCLIsam local命令在本機測試應用程式。若要完成此操作,會使用AWS SAMCLI建立本端環境Docker。此本機環境會模擬 Lambda 函數的雲端式執行環境。

您可執行下列項目:

  1. 為您的 Lambda 函數建立本機環境並呼叫它。

  2. 在本機託管您的 HTTP API 端點,並使用它來叫用您的 Lambda 函數。

若要在本機叫用 Lambda 函數
  1. 在命令行中,從sam-app項目目錄中運行以下命令:

    $ sam local invoke
  2. 會AWS SAMCLI建立本機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. 會為您的 Lambda 函數AWS SAMCLI建立本機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. 使用瀏覽器或命令列,將 GET 要求傳送至本機 API 端點。以下是使用 curl 命令的示例:

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

步驟 8:從中刪除您的應用程序 AWS 雲端

在此步驟中,您可以使用AWS SAMCLIsam delete指令從中刪除您的應用程式AWS 雲端。

若要從中刪除您的應用程式 AWS 雲端
  1. 在命令行中,從sam-app項目目錄中運行以下命令:

    $ sam delete
  2. AWS SAMCLI將要求您確認。然後,它將刪除您應用程序的 Amazon S3 存儲桶和AWS 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

故障診斷

若要疑難排解 AWS SAMCLI,請參閱AWS SAMCLI疑難排

進一步了解

若要繼續學習AWS SAM,請參閱下列資源:

  • 完整的AWS SAM工作坊 — 旨在教您AWS SAM提供許多主要功能的工作坊。

  • 與 SAM 的會話 — 由我們的AWS無伺服器開發人員倡導團隊建立的影片系列,內容包括 AWS SAM

  • 無伺服器 Land — 整合無AWS伺服器的最新資訊、部落格、影片、程式碼和學習資源的網站。