

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

# 使用 部署您的應用程式和資源 AWS SAM
<a name="serverless-deploying"></a>

部署您的應用程式會在 AWS 雲端佈建和設定您的 AWS 資源，讓您的應用程式在 雲端中執行。 AWS SAM 會使用您在執行 **sam build**命令時建立的[CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/) AWS SAM 建置成品做為部署無伺服器應用程式的標準輸入。

使用 AWS SAM，您可以手動部署無伺服器應用程式，也可以自動化部署。若要自動化部署，您可以使用 AWS SAM 管道搭配您選擇的持續整合和持續部署 (CI/CD) 系統。您的部署管道是一系列自動執行的步驟，用於發行無伺服器應用程式的新版本。

本節中的主題提供自動化和手動部署的指引。若要手動部署應用程式，您可以使用 AWS SAM CLI 命令。若要自動化部署，請參閱本節中的主題。它們專門提供使用管道和 CI/CD 系統自動化部署的深入內容。這包括產生入門管道、設定自動化、疑難排解部署、使用 OpenID Connect (OIDC) 使用者身分驗證，以及在部署時上傳本機檔案。

**Topics**
+ [使用 部署簡介 AWS SAM](using-sam-cli-deploy.md)
+ [使用 部署應用程式的選項 AWS SAM](deploying-options.md)
+ [使用 CI/CD 系統和管道搭配 部署 AWS SAM](deploying-cicd-overview.md)
+ [使用 sam sync 同步至 的簡介 AWS 雲端](using-sam-cli-sync.md)

# 使用 部署簡介 AWS SAM
<a name="using-sam-cli-deploy"></a>

使用 AWS Serverless Application Model Command Line Interface (AWS SAM CLI) `sam deploy`命令將您的無伺服器應用程式部署到 AWS 雲端。
+ 如需 的簡介 AWS SAM CLI，請參閱 [什麼是 AWS SAM CLI？](what-is-sam-overview.md#what-is-sam-cli)。
+ 如需`sam deploy`命令選項的清單，請參閱 [sam deploy](sam-cli-command-reference-sam-deploy.md)。
+ 如需在典型開發工作流程`sam deploy`期間使用 的範例，請參閱 [步驟 3：將您的應用程式部署到 AWS 雲端](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-deploy)。

**Topics**
+ [先決條件](#using-sam-cli-deploy-prerequisites)
+ [使用 sam 部署來部署應用程式](#using-sam-cli-deploy-deploying)
+ [最佳實務](#using-sam-cli-deploy-best)
+ [sam 部署的選項](#using-sam-cli-deploy-options)
+ [疑難排解](#using-sam-cli-deploy-troubleshooting)
+ [範例](#using-sam-cli-deploy-examples)
+ [進一步了解](#using-sam-cli-deploy-learn)

## 先決條件
<a name="using-sam-cli-deploy-prerequisites"></a>

若要使用 `sam deploy`，請完成下列步驟來 AWS SAM CLI安裝 ：
+ [AWS SAM 先決條件](prerequisites.md).
+ [安裝 AWS SAM CLI](install-sam-cli.md).

使用 之前`sam deploy`，我們建議您對下列項目有基本的了解：
+ [設定 AWS SAM CLI](using-sam-cli-configure.md).
+ [在 中建立您的應用程式 AWS SAM](using-sam-cli-init.md).
+ [使用 建置 簡介 AWS SAM](using-sam-cli-build.md).

## 使用 sam 部署來部署應用程式
<a name="using-sam-cli-deploy-deploying"></a>

當您第一次部署無伺服器應用程式時，請使用 `--guided`選項。 AWS SAM CLI 將引導您完成互動式流程，以設定應用程式的部署設定。

**使用互動式流程部署應用程式**

1. 移至專案的根目錄。這與 AWS SAM 範本的位置相同。

   ```
   $ cd sam-app
   ```

1. 執行以下命令：

   ```
   $ sam deploy --guided
   ```

1. 在互動式流程期間， AWS SAM CLI會提示您設定應用程式部署設定的選項。

   括號 (`[ ]`) 表示預設值。將您的答案保留空白以選取預設值。預設值是從下列組態檔案取得：
   + `~/.aws/config` – 您的一般 AWS 帳戶設定。
   + `~/.aws/credentials` – AWS 您的帳戶登入資料。
   + `<project>/samconfig.toml` – 專案的組態檔案。

   回答 AWS SAM CLI提示以提供值。例如，您可以`y`針對**是**、`n`**否**或字串值輸入 。

   會將您的回應 AWS SAM CLI寫入專案的 `samconfig.toml` 檔案。對於後續部署，您可以使用 `sam deploy`來使用這些設定值進行部署。若要重新設定這些值，請`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]: ENTER
           #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
   ```

1. 接著， AWS SAM CLI會將您的應用程式部署到 AWS 雲端。在部署期間，進度會顯示在命令提示中。以下是部署的主要階段：
   + 對於具有封裝為 .zip 檔案封存之 AWS Lambda 函數的應用程式， AWS SAM CLI會壓縮套件並將其上傳至 Amazon Simple Storage Service (Amazon S3) 儲存貯體。如有必要， AWS SAM CLI會建立新的儲存貯體。
   + 對於使用 Lambda 函數套件做為容器映像的應用程式， AWS SAM CLI會將映像上傳至 Amazon Elastic Container Registry (Amazon ECR)。如有必要， AWS SAM CLI會建立新的儲存庫。
   +  AWS SAM CLI 會建立 AWS CloudFormation 變更集，並將您的應用程式部署到 CloudFormation 做為堆疊。
   + 會使用 Lambda AWS SAM CLI函數的新`CodeUri`值來修改已部署的 AWS SAM 範本。

   以下是部署輸出的範例 AWS SAM CLI：

   ```
           Looking for resources needed for deployment:
   
           Managed S3 bucket: aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
           A different default S3 bucket can be set in samconfig.toml and auto resolution of buckets turned off by setting resolve_s3=False
   
           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/.../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
   
           Uploading to sam-app-zip/da3c598813f1c2151579b73ad788cac8  262144 / 619839  (42.29%)Uploading to sam-app-zip/da3c598813f1c2151579b73ad788cac8  524288 / 619839  (84.58%)Uploading to sam-app-zip/da3c598813f1c2151579b73ad788cac8  619839 / 619839  (100.00%)
   
           Deploying with following values
           ===============================
           Stack name                   : sam-app
           Region                       : us-west-2
           Confirm changeset            : True
           Disable rollback             : False
           Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
           Capabilities                 : ["CAPABILITY_IAM"]
           Parameter overrides          : {}
           Signing Profiles             : {}
   
   Initiating deployment
   =====================
   
           Uploading to sam-app-zip/be84c20f868068e4dc4a2c11966edf2d.template  1212 / 1212  (100.00%)
   
   
   Waiting for changeset to be created..
   
   CloudFormation stack changeset
   -------------------------------------------------------------------------------------------------
   Operation                LogicalResourceId        ResourceType             Replacement            
   -------------------------------------------------------------------------------------------------
   + Add                    HelloWorldFunctionHell   AWS::Lambda::Permissio   N/A                    
                            oWorldPermissionProd     n                                               
   + Add                    HelloWorldFunctionRole   AWS::IAM::Role           N/A                    
   + Add                    HelloWorldFunction       AWS::Lambda::Function    N/A                    
   + Add                    ServerlessRestApiDeplo   AWS::ApiGateway::Deplo   N/A                    
                            yment47fc2d5f9d          yment                                           
   + Add                    ServerlessRestApiProdS   AWS::ApiGateway::Stage   N/A                    
                            tage                                                                     
   + Add                    ServerlessRestApi        AWS::ApiGateway::RestA   N/A                    
                                                     pi                                              
   -------------------------------------------------------------------------------------------------
   
   
   Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1680559234/d9f58a77-98bc-41cd-b9f4-433a5a450d7a
   
   
   Previewing CloudFormation changeset before deployment
   ======================================================
   Deploy this changeset? [y/N]: y
   
   2023-04-03 12:00:50 - Waiting for stack create/update to complete
   
   CloudFormation events from stack operations (refresh every 5.0 seconds)
   -------------------------------------------------------------------------------------------------
   ResourceStatus           ResourceType             LogicalResourceId        ResourceStatusReason   
   -------------------------------------------------------------------------------------------------
   CREATE_IN_PROGRESS       AWS::IAM::Role           HelloWorldFunctionRole   -                      
   CREATE_IN_PROGRESS       AWS::IAM::Role           HelloWorldFunctionRole   Resource creation      
                                                                              Initiated              
   CREATE_COMPLETE          AWS::IAM::Role           HelloWorldFunctionRole   -                      
   CREATE_IN_PROGRESS       AWS::Lambda::Function    HelloWorldFunction       -                      
   CREATE_IN_PROGRESS       AWS::Lambda::Function    HelloWorldFunction       Resource creation      
                                                                              Initiated              
   CREATE_COMPLETE          AWS::Lambda::Function    HelloWorldFunction       -                      
   CREATE_IN_PROGRESS       AWS::ApiGateway::RestA   ServerlessRestApi        -                      
                            pi                                                                       
   CREATE_IN_PROGRESS       AWS::ApiGateway::RestA   ServerlessRestApi        Resource creation      
                            pi                                                Initiated              
   CREATE_COMPLETE          AWS::ApiGateway::RestA   ServerlessRestApi        -                      
                            pi                                                                       
   CREATE_IN_PROGRESS       AWS::Lambda::Permissio   HelloWorldFunctionHell   -                      
                            n                        oWorldPermissionProd                            
   CREATE_IN_PROGRESS       AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   -                      
                            yment                    yment47fc2d5f9d                                 
   CREATE_IN_PROGRESS       AWS::Lambda::Permissio   HelloWorldFunctionHell   Resource creation      
                            n                        oWorldPermissionProd     Initiated              
   CREATE_IN_PROGRESS       AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   Resource creation      
                            yment                    yment47fc2d5f9d          Initiated              
   CREATE_COMPLETE          AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   -                      
                            yment                    yment47fc2d5f9d                                 
   CREATE_IN_PROGRESS       AWS::ApiGateway::Stage   ServerlessRestApiProdS   -                      
                                                     tage                                            
   CREATE_IN_PROGRESS       AWS::ApiGateway::Stage   ServerlessRestApiProdS   Resource creation      
                                                     tage                     Initiated              
   CREATE_COMPLETE          AWS::ApiGateway::Stage   ServerlessRestApiProdS   -                      
                                                     tage                                            
   CREATE_COMPLETE          AWS::Lambda::Permissio   HelloWorldFunctionHell   -                      
                            n                        oWorldPermissionProd                            
   CREATE_COMPLETE          AWS::CloudFormation::S   sam-app-zip              -                      
                            tack                                                                     
   -------------------------------------------------------------------------------------------------
   
   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-zip-                                 
   HelloWorldFunctionRole-11ZOGSCG28H0M                                                            
   
   Key                 HelloWorldApi                                                               
   Description         API Gateway endpoint URL for Prod stage for Hello World function            
   Value               https://njzfhdmls0.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-XPqNX4TBu7qn                                                                 
   -------------------------------------------------------------------------------------------------
   
   
   Successfully created/updated stack - sam-app-zip in us-west-2
   ```

1. 若要檢視已部署的應用程式，請執行下列動作：

   1. 使用 URL 直接開啟 CloudFormation 主控台 https：//[https://console.aws.amazon.com/cloudformation](https://console.aws.amazon.com/cloudformation/)。

   1. 選取**堆疊**。

   1. 依應用程式名稱識別您的堆疊並選取它。

### 在部署之前驗證變更
<a name="using-sam-cli-deploy-deploying-changes"></a>

您可以設定 AWS SAM CLI以顯示 CloudFormation 變更集，並在部署之前要求確認。

**在部署之前確認變更**

1. 在 期間`sam deploy --guided`，輸入 **Y** 在部署之前確認變更。

   ```
   #Shows you resources changes to be deployed and require a 'Y' to initiate deploy
   Confirm changes before deploy [Y/n]: Y
   ```

   或者，您可以使用下列內容修改`samconfig.toml`檔案：

   ```
   [default.deploy]
   [default.deploy.parameters]
   confirm_changeset = true
   ```

1. 在部署期間， AWS SAM CLI會要求您在部署之前確認變更。以下是範例：

   ```
   Waiting for changeset to be created..
   
   CloudFormation stack changeset
   -------------------------------------------------------------------------------------------------
   Operation                LogicalResourceId        ResourceType             Replacement            
   -------------------------------------------------------------------------------------------------
   + Add                    HelloWorldFunctionHell   AWS::Lambda::Permissio   N/A                    
                            oWorldPermissionProd     n                                               
   + Add                    HelloWorldFunctionRole   AWS::IAM::Role           N/A                    
   + Add                    HelloWorldFunction       AWS::Lambda::Function    N/A                    
   + Add                    ServerlessRestApiDeplo   AWS::ApiGateway::Deplo   N/A                    
                            yment47fc2d5f9d          yment                                           
   + Add                    ServerlessRestApiProdS   AWS::ApiGateway::Stage   N/A                    
                            tage                                                                     
   + Add                    ServerlessRestApi        AWS::ApiGateway::RestA   N/A                    
                                                     pi                                              
   -------------------------------------------------------------------------------------------------
   
   Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1680559234/d9f58a77-98bc-41cd-b9f4-433a5a450d7a
   Previewing CloudFormation changeset before deployment
   ======================================================
   Deploy this changeset? [y/N]: y
   ```

### 在部署期間指定其他參數
<a name="using-sam-cli-deploy-deploying-params"></a>

您可以指定部署時要設定的其他參數值。您可以透過修改 AWS SAM 範本並在部署期間設定參數值來執行此操作。

**指定其他參數**

1. 修改 AWS SAM 範本的 `Parameters`區段。以下是範例：

   ```
   AWSTemplateFormatVersion: '2010-09-09'
   Transform: AWS::Serverless-2016-10-31
   ...
   Globals:
   ...
   Parameters:
     DomainName:
       Type: String
       Default: example
       Description: Domain name
   ```

1. 執行 `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-zip]: ENTER
           AWS Region [us-west-2]: ENTER
           Parameter DomainName [example]: ENTER
   ```

### 為您的 Lambda 函數設定程式碼簽署
<a name="using-sam-cli-deploy-deploying-signing"></a>

您可以在部署時為 Lambda 函數設定程式碼簽署。您可以透過修改 AWS SAM 範本並在部署期間設定程式碼簽署來執行此操作。

**設定程式碼簽署**

1. 在 AWS SAM 範本`CodeSigningConfigArn`中指定 。以下是範例：

   ```
   AWSTemplateFormatVersion: '2010-09-09'
   Transform: AWS::Serverless-2016-10-31
   ...
   Resources:
     HelloWorldFunction:
       Type: AWS::Serverless::Function
       Properties:
         CodeUri: hello_world/
         Handler: app.lambda_handler
         Runtime: python3.7
         CodeSigningConfigArn: arn:aws:lambda:us-east-1:111122223333:code-signing-config:csc-12e12345db1234567
   ```

1. 執行 `sam deploy --guided`。 AWS SAM CLI 將提示您設定程式碼簽署。以下是輸出範例：

   ```
   #Found code signing configurations in your function definitions
   Do you want to sign your code? [Y/n]: ENTER
   #Please provide signing profile details for the following functions & layers
   #Signing profile details for function 'HelloWorld'
   Signing Profile Name: 
   Signing Profile Owner Account ID (optional):
   #Signing profile details for layer 'MyLayer', which is used by functions {'HelloWorld'}
   Signing Profile Name: 
   Signing Profile Owner Account ID (optional):
   ```

## 最佳實務
<a name="using-sam-cli-deploy-best"></a>
+ 使用 時`sam deploy`， AWS SAM CLI會部署位於 `.aws-sam`目錄中的應用程式建置成品。當您變更應用程式的原始檔案時，請執行 `sam build`以在部署之前更新`.aws-sam`目錄。
+ 第一次部署應用程式時，請使用 `sam deploy --guided`來設定部署設定。對於後續部署，您可以使用 `sam deploy`搭配設定的 設定進行部署。

## sam 部署的選項
<a name="using-sam-cli-deploy-options"></a>

以下是 常用的選項`sam deploy`。如需所有選項的清單，請參閱 [sam deploy](sam-cli-command-reference-sam-deploy.md)。

### 使用引導式互動式流程來部署您的應用程式
<a name="using-sam-cli-deploy-options-guided"></a>

使用 `--guided`選項，透過互動式流程來設定應用程式的部署設定。以下是範例：

```
$ sam deploy --guided
```

您應用程式的部署設定會儲存在專案的 `samconfig.toml`檔案中。如需詳細資訊，請參閱 [設定專案設定](using-sam-cli-configure.md#using-sam-cli-configure-project)。

## 疑難排解
<a name="using-sam-cli-deploy-troubleshooting"></a>

若要疑難排解 AWS SAM CLI，請參閱 [AWS SAM CLI 故障診斷](sam-cli-troubleshooting.md)。

## 範例
<a name="using-sam-cli-deploy-examples"></a>

### 部署 Hello World 應用程式，其中包含封裝為 .zip 檔案封存檔的 Lambda 函數
<a name="using-sam-cli-deploy-examples-example1"></a>

如需範例，請參閱 Hello World 應用程式教學[步驟 3：將您的應用程式部署到 AWS 雲端](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-deploy)中的 。

### 部署 Hello World 應用程式，其中包含封裝為容器映像的 Lambda 函數
<a name="using-sam-cli-deploy-examples-example2"></a>

首先，我們使用 `sam init` 來建立 Hello World 應用程式。在互動式流程中，我們會選擇`Python3.9`執行時間和`Image`套件類型。

```
$ 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
        ...
Template: 1

Use the most popular runtime and package type? (Python and zip) [y/N]:  ENTER

Which runtime would you like to use?
        1 - aot.dotnet7 (provided.al2)
        ...
        15 - nodejs12.x
        16 - python3.9
        17 - python3.8
        ...
Runtime: 16

What package type would you like to use?
        1 - Zip
        2 - Image
Package type: 2

Based on your selections, the only dependency manager available is pip.
We will proceed copying the template using pip.
...
Project name [sam-app]: ENTER

    -----------------------
    Generating application:
    -----------------------
    Name: sam-app
    Base Image: amazon/python3.9-base
    Architectures: x86_64
    Dependency Manager: pip
    Output Directory: .
    Configuration file: sam-app/samconfig.toml

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

接下來，我們會`cd`移至專案的根目錄，並執行 `sam build`。使用 在 AWS SAM CLI本機建置我們的 Lambda 函數Docker。

```
sam-app $ sam build
Building codeuri: /Users/.../sam-app runtime: None metadata: {'Dockerfile': 'Dockerfile', 'DockerContext': '/Users/.../sam-app/hello_world', 'DockerTag': 'python3.9-v1'} architecture: x86_64 functions: HelloWorldFunction
Building image for HelloWorldFunction function
Setting DockerBuildArgs: {} for HelloWorldFunction function
Step 1/5 : FROM public.ecr.aws/lambda/python:3.9
 ---> 0a5e3da309aa
Step 2/5 : COPY requirements.txt ./
 ---> abc4e82e85f9
Step 3/5 : RUN python3.9 -m pip install -r requirements.txt -t .
 ---> [Warning] The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
 ---> Running in 43845e7aa22d
Collecting requests
  Downloading requests-2.28.2-py3-none-any.whl (62 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.8/62.8 KB 829.5 kB/s eta 0:00:00
Collecting idna<4,>=2.5
  Downloading idna-3.4-py3-none-any.whl (61 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 61.5/61.5 KB 2.4 MB/s eta 0:00:00
Collecting charset-normalizer<4,>=2
  Downloading charset_normalizer-3.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (199 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 199.2/199.2 KB 2.1 MB/s eta 0:00:00
Collecting certifi>=2017.4.17
  Downloading certifi-2022.12.7-py3-none-any.whl (155 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 155.3/155.3 KB 10.2 MB/s eta 0:00:00
Collecting urllib3<1.27,>=1.21.1
  Downloading urllib3-1.26.15-py2.py3-none-any.whl (140 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 140.9/140.9 KB 9.1 MB/s eta 0:00:00
Installing collected packages: urllib3, idna, charset-normalizer, certifi, requests
Successfully installed certifi-2022.12.7 charset-normalizer-3.1.0 idna-3.4 requests-2.28.2 urllib3-1.26.15
Removing intermediate container 43845e7aa22d
 ---> cab8ace899ce
Step 4/5 : COPY app.py ./
 ---> 4146f3cd69f2
Step 5/5 : CMD ["app.lambda_handler"]
 ---> [Warning] The requested image's platform (linux/amd64) does not match the detected host platform (linux/arm64/v8) and no specific platform was requested
 ---> Running in f4131ddffb31
Removing intermediate container f4131ddffb31
 ---> d2f5180b2154
Successfully built d2f5180b2154
Successfully tagged helloworldfunction:python3.9-v1


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

接下來，我們會執行 `sam deploy --guided`來部署應用程式。會 AWS SAM CLI引導我們設定部署設定。然後， AWS SAM CLI會將我們的應用程式部署到 AWS 雲端。

```
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]: ENTER
        #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

        Looking for resources needed for deployment:

        Managed S3 bucket: aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
        A different default S3 bucket can be set in samconfig.toml and auto resolution of buckets turned off by setting resolve_s3=False

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

e95fc5e75742: Pushed 
d8df51e7bdd7: Pushed 
b1d0d7e0b34a: Pushed 
0071317b94d8: Pushed 
d98f98baf147: Pushed 
2d244e0816c6: Pushed 
eb2eeb1ebe42: Pushed 
a5ca065a3279: Pushed 
fe9e144829c9: Pushed 
helloworldfunction-d2f5180b2154-python3.9-v1: digest: sha256:cceb71401b47dc3007a7a1e1f2e0baf162999e0e6841d15954745ecc0c447533 size: 2206

        Deploying with following values
        ===============================
        Stack name                   : sam-app
        Region                       : us-west-2
        Confirm changeset            : True
        Disable rollback             : False
        Deployment image repository  : 
                                       {
                                           "HelloWorldFunction": "012345678910.dkr.ecr.us-west-2.amazonaws.com/samapp7427b055/helloworldfunction19d43fc4repo"
                                       }
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

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

HelloWorldFunction may not have authorization defined.
        Uploading to sam-app/682ad27c7cf7a17c7f77a1688b0844f2.template  1328 / 1328  (100.00%)


Waiting for changeset to be created..

CloudFormation stack changeset
-------------------------------------------------------------------------------------------------
Operation                LogicalResourceId        ResourceType             Replacement            
-------------------------------------------------------------------------------------------------
+ Add                    HelloWorldFunctionHell   AWS::Lambda::Permissio   N/A                    
                         oWorldPermissionProd     n                                               
+ Add                    HelloWorldFunctionRole   AWS::IAM::Role           N/A                    
+ Add                    HelloWorldFunction       AWS::Lambda::Function    N/A                    
+ Add                    ServerlessRestApiDeplo   AWS::ApiGateway::Deplo   N/A                    
                         yment47fc2d5f9d          yment                                           
+ Add                    ServerlessRestApiProdS   AWS::ApiGateway::Stage   N/A                    
                         tage                                                                     
+ Add                    ServerlessRestApi        AWS::ApiGateway::RestA   N/A                    
                                                  pi                                              
-------------------------------------------------------------------------------------------------


Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1680634124/0ffd4faf-2e2b-487e-b9e0-9116e8299ac4


Previewing CloudFormation changeset before deployment
======================================================
Deploy this changeset? [y/N]: y

2023-04-04 08:49:15 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 5.0 seconds)
-------------------------------------------------------------------------------------------------
ResourceStatus           ResourceType             LogicalResourceId        ResourceStatusReason   
-------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS       AWS::CloudFormation::S   sam-app                  User Initiated         
                         tack                                                                     
CREATE_IN_PROGRESS       AWS::IAM::Role           HelloWorldFunctionRole   -                      
CREATE_IN_PROGRESS       AWS::IAM::Role           HelloWorldFunctionRole   Resource creation      
                                                                           Initiated              
CREATE_COMPLETE          AWS::IAM::Role           HelloWorldFunctionRole   -                      
CREATE_IN_PROGRESS       AWS::Lambda::Function    HelloWorldFunction       -                      
CREATE_IN_PROGRESS       AWS::Lambda::Function    HelloWorldFunction       Resource creation      
                                                                           Initiated              
CREATE_COMPLETE          AWS::Lambda::Function    HelloWorldFunction       -                      
CREATE_IN_PROGRESS       AWS::ApiGateway::RestA   ServerlessRestApi        -                      
                         pi                                                                       
CREATE_IN_PROGRESS       AWS::ApiGateway::RestA   ServerlessRestApi        Resource creation      
                         pi                                                Initiated              
CREATE_COMPLETE          AWS::ApiGateway::RestA   ServerlessRestApi        -                      
                         pi                                                                       
CREATE_IN_PROGRESS       AWS::Lambda::Permissio   HelloWorldFunctionHell   -                      
                         n                        oWorldPermissionProd                            
CREATE_IN_PROGRESS       AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   -                      
                         yment                    yment47fc2d5f9d                                 
CREATE_IN_PROGRESS       AWS::Lambda::Permissio   HelloWorldFunctionHell   Resource creation      
                         n                        oWorldPermissionProd     Initiated              
CREATE_IN_PROGRESS       AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   Resource creation      
                         yment                    yment47fc2d5f9d          Initiated              
CREATE_COMPLETE          AWS::ApiGateway::Deplo   ServerlessRestApiDeplo   -                      
                         yment                    yment47fc2d5f9d                                 
CREATE_IN_PROGRESS       AWS::ApiGateway::Stage   ServerlessRestApiProdS   -                      
                                                  tage                                            
CREATE_IN_PROGRESS       AWS::ApiGateway::Stage   ServerlessRestApiProdS   Resource creation      
                                                  tage                     Initiated              
CREATE_COMPLETE          AWS::ApiGateway::Stage   ServerlessRestApiProdS   -                      
                                                  tage                                            
CREATE_COMPLETE          AWS::Lambda::Permissio   HelloWorldFunctionHell   -                      
                         n                        oWorldPermissionProd                            
CREATE_COMPLETE          AWS::CloudFormation::S   sam-app                  -                      
                         tack                                                                     
-------------------------------------------------------------------------------------------------

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

Key                 HelloWorldApi                                                               
Description         API Gateway endpoint URL for Prod stage for Hello World function            
Value               https://endlwiqqod.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-  
kyg6Y2iNRUPg                                                                                    
-------------------------------------------------------------------------------------------------


Successfully created/updated stack - sam-app in us-west-2
```

## 進一步了解
<a name="using-sam-cli-deploy-learn"></a>

若要進一步了解如何使用 AWS SAM CLI`sam deploy`命令，請參閱以下內容：
+ **[完成 AWS SAM 研討會：單元 3 - 手動部署](https://s12d.com/sam-ws-en-manual-deploy)** – 了解如何使用 建置、封裝和部署無伺服器應用程式 AWS SAM CLI。

# 使用 部署應用程式的選項 AWS SAM
<a name="deploying-options"></a>

使用 AWS SAM，您可以手動部署應用程式並自動化部署。使用 AWS SAM CLI 手動部署您的應用程式。若要自動化部署，請使用管道和持續整合和持續部署 (CI/CD) 系統。本節中的主題提供有關這兩種方法的資訊。

**Topics**
+ [如何使用 AWS SAM CLI 手動部署](#serverless-sam-cli-using-package-and-deploy)
+ [使用 CI/CD 系統和管道部署](#serverless-deploying-ci-cd)
+ [逐步部署](#serverless-deploying-gradual)
+ [使用 對部署進行故障診斷 AWS SAM CLI](#serverless-deploying-troubleshooting)
+ [進一步了解](#serverless-sam-cli-using-invoke-learn)

## 如何使用 AWS SAM CLI 手動部署
<a name="serverless-sam-cli-using-package-and-deploy"></a>

在本機開發和測試無伺服器應用程式之後，您可以使用 **[sam deploy](sam-cli-command-reference-sam-deploy.md)**命令部署應用程式。

若要讓 使用提示 AWS SAM 引導您完成部署，請指定 **--guided**旗標。當您指定此旗標時，**sam deploy**命令會壓縮應用程式成品、將它們上傳至 Amazon Simple Storage Service (Amazon S3) （適用於 .zip 檔案封存） 或 Amazon Elastic Container Registry (Amazon ECR) （適用於容器映像）。命令接著會將您的應用程式部署到 AWS 雲端。

**範例**：

```
# Deploy an application using prompts:
sam deploy --guided
```

## 使用 CI/CD 系統和管道部署
<a name="serverless-deploying-ci-cd"></a>

AWS SAM 可協助您使用管道和持續整合和持續部署 (CI/CD) 系統來自動化部署。 AWS SAM 可用來建立管道，並簡化無伺服器應用程式的 CI/CD 任務。多個 CI/CD 系統支援 AWS SAM 建置容器映像， AWS SAM 也為封裝部署最佳實務 AWS的多個 CI/CD 系統提供一組預設管道範本。

如需詳細資訊，請參閱[使用 CI/CD 系統和管道搭配 部署 AWS SAM](deploying-cicd-overview.md)。

## 逐步部署
<a name="serverless-deploying-gradual"></a>

如果您想要逐步部署 AWS SAM 應用程式，而不是一次全部部署，您可以指定 AWS CodeDeploy 提供的部署組態。如需詳細資訊，請參閱*AWS CodeDeploy 《 使用者指南*[》中的在 CodeDeploy 中使用部署組態](https://docs.aws.amazon.com/codedeploy/latest/userguide/deployment-configurations.html)。

如需設定 AWS SAM 應用程式以逐步部署的資訊，請參閱 [使用 逐步部署無伺服器應用程式 AWS SAM](automating-updates-to-serverless-apps.md)。

## 使用 對部署進行故障診斷 AWS SAM CLI
<a name="serverless-deploying-troubleshooting"></a>

### AWS SAM CLI 錯誤：「未滿足安全限制條件」
<a name="troubleshooting-security-constraints"></a>

執行 時**sam deploy --guided**，系統會提示您輸入問題 `HelloWorldFunction may not have authorization defined, Is this okay? [y/N]`。如果您使用 **N**（預設回應） 回應此提示，您會看到下列錯誤：

```
 
Error: Security Constraints Not Satisfied
```

提示會通知您即將部署的應用程式可能在未經授權的情況下設定 Amazon API Gateway API。透過**N**回應此提示，您表示這不行。

若要修正此問題，您有下列選項：
+ 使用授權設定您的應用程式。如需設定授權的資訊，請參閱 [使用 AWS SAM 範本控制 API 存取](serverless-controlling-access-to-apis.md)。
+ 使用 回應此問題，**Y**表示您可以部署已設定 API Gateway API 的應用程式，無需授權。

## 進一步了解
<a name="serverless-sam-cli-using-invoke-learn"></a>

如需部署無伺服器應用程式的實作範例，請參閱 The *Complete AWS SAM Workshop *中的以下內容：
+ [單元 3 - 手動部署](https://s12d.com/sam-ws-en-manual-deploy) – 了解如何使用 建置、封裝和部署無伺服器應用程式 AWS SAM CLI。
+ [單元 4 - CI/CD](https://s12d.com/sam-ws-en-cicd-deploy) – 了解如何透過建立*持續整合和交付 (CI/CD) *管道來自動化建置、套件和部署階段。

# 使用 CI/CD 系統和管道搭配 部署 AWS SAM
<a name="deploying-cicd-overview"></a>

AWS SAM 協助組織為其偏好的 CI/CD 系統建立管道，以便能夠以最少的努力實現 CI/CD 的優勢，例如加速部署頻率、縮短變更的前置時間，以及減少部署錯誤。

AWS SAM 透過建置容器映像的協助，簡化無伺服器應用程式的 CI/CD 任務。 AWS SAM 提供的映像包含 AWS SAM CLI多個支援 AWS Lambda 執行時間的 和 建置工具。這可讓您更輕鬆地使用 建置和封裝無伺服器應用程式 AWS SAM CLI。這些映像也減輕了團隊為 CI/CD 系統建立和管理自己映像的需求。如需 AWS SAM 建置容器映像的詳細資訊，請參閱[的影像儲存庫 AWS SAM](serverless-image-repositories.md)。

多個 CI/CD 系統支援 AWS SAM 建置容器映像。您應該使用的 CI/CD 系統取決於幾個因素。這些包括您的應用程式是使用單一執行時間還是多個執行時間，還是您要在容器映像內或直接在主機上建置應用程式，可以是虛擬機器 (VM) 或裸機主機。

AWS SAM 也為封裝部署最佳實務 AWS的多個 CI/CD 系統提供一組預設管道範本。這些預設管道範本使用標準 JSON/YAML 管道組態格式，而內建的最佳實務有助於執行多帳戶和多區域部署，並確認管道無法對基礎設施進行意外變更。

您有兩個主要選項可使用 AWS SAM 來部署無伺服器應用程式：1) 修改現有管道組態以使用 AWS SAM CLI 命令，或 2) 產生範例 CI/CD 管道組態，您可以將其做為自有應用程式的起點。

**Topics**
+ [什麼是管道？](#deploying-whatis-pipeline)
+ [如何在部署時 AWS SAM 上傳本機檔案](deploy-upload-local-files.md)
+ [使用 產生入門 CI/CD 管道 AWS SAM](serverless-generating-example-ci-cd.md)
+ [如何使用 自訂入門管道 AWS SAM](serverless-customizing-starter-pipelines.md)
+ [自動化 AWS SAM 應用程式的部署](serverless-deploying-modify-pipeline.md)
+ [如何搭配 AWS SAM 管道使用 OIDC 身分驗證](deploying-with-oidc.md)

## 什麼是管道？
<a name="deploying-whatis-pipeline"></a>

管道是自動執行的步驟序列，用於發行應用程式的新版本。透過 AWS SAM，您可以使用許多常見的 CI/CD 系統來部署應用程式，包括 [AWS CodePipeline](https://aws.amazon.com/codepipeline)、[Jenkins](https://www.jenkins.io/)、[GitLab CI/CD](https://docs.gitlab.com/ee/ci/) 和 [GitHub 動作](https://github.com/features/actions)。

管道範本包含 AWS 部署最佳實務，可協助多帳戶和多區域部署。開發和生產等 AWS 環境通常存在於不同的 AWS 帳戶中。這可讓開發團隊設定安全的部署管道，而不會對基礎設施進行意外變更。

您也可以提供自己的自訂管道範本，以協助跨開發團隊標準化管道。

# 如何在部署時 AWS SAM 上傳本機檔案
<a name="deploy-upload-local-files"></a>

當您將應用程式部署到 時 AWS 雲端， AWS CloudFormation 需要先將本機檔案上傳到可存取 AWS 的服務，例如 Amazon Simple Storage Service (Amazon S3)。這包括 AWS SAM 範本參考的本機檔案。為了符合此需求，當您使用 `sam deploy`或 `sam package`命令時， 會 AWS SAM CLI執行下列動作：

1. 自動將本機檔案上傳至可存取 AWS 的服務。

1. 自動更新您的應用程式範本，以參考新的檔案路徑。

**Topics**
+ [示範：使用 AWS SAM CLI上傳 Lambda 函數程式碼](#deploy-upload-local-files-demo)
+ [支援的使用案例](#deploy-upload-local-files-use)
+ [進一步了解](#deploy-upload-local-files-learn)

## 示範：使用 AWS SAM CLI上傳 Lambda 函數程式碼
<a name="deploy-upload-local-files-demo"></a>

在此示範中，我們使用 Lambda 函數的 .zip 套件類型來初始化範例 Hello World 應用程式。我們使用 AWS SAM CLI自動將 Lambda 函數程式碼上傳至 Amazon S3，並在應用程式範本中參考其新路徑。

首先，我們會執行 `sam init`來初始化 Hello World 應用程式。

```
$ 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
        ...
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]: demo

    -----------------------
    Generating application:
    -----------------------
    Name: demo
    Runtime: python3.9
    Architectures: x86_64
    Dependency Manager: pip
    Application Template: hello-world
    Output Directory: .
    Configuration file: demo/samconfig.toml
    
...
```

我們的 Lambda 函數程式碼會在專案的`hello_world`子目錄中組織。

```
demo
├── README.md
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── requirements.txt
├── template.yaml
└── tests
```

在我們的 AWS SAM 範本中，我們使用 `CodeUri` 屬性參考 Lambda 函數程式碼的本機路徑。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.9
      ...
```

接下來，我們會執行 `sam build`來建置應用程式並準備部署。

```
$ sam build
Starting Build use cache
Manifest file is changed (new hash: 3298f13049d19cffaa37ca931dd4d421) or dependency folder (.aws-sam/deps/7896875f-9bcc-4350-8adb-2c1d543627a1) is missing for (HelloWorldFunction), downloading dependencies and copying/building source
Building codeuri: /Users/.../demo/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
...
```

接下來，我們會執行 `sam deploy --guided`來部署應用程式。

```
$ 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 [demo]: 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

        Looking for resources needed for deployment:
        ...
        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 demo/da3c598813f1c2151579b73ad788cac8, skipping upload

        Deploying with following values
        ===============================
        Stack name                   : demo
        Region                       : us-west-2
        Confirm changeset            : False
        Disable rollback             : False
        Deployment s3 bucket         : aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr
        Capabilities                 : ["CAPABILITY_IAM"]
        Parameter overrides          : {}
        Signing Profiles             : {}

Initiating deployment
=====================
...
Waiting for changeset to be created..
CloudFormation stack changeset
-------------------------------------------------------------------------------------------------
Operation                LogicalResourceId        ResourceType             Replacement            
-------------------------------------------------------------------------------------------------
+ Add                    HelloWorldFunctionHell   AWS::Lambda::Permissio   N/A                    
                         oWorldPermissionProd     n                                               
+ Add                    HelloWorldFunctionRole   AWS::IAM::Role           N/A                    
...                     
-------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1680906292/1164338d-72e7-4593-a372-f2b3e67f542f

2023-04-07 12:24:58 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 5.0 seconds)
-------------------------------------------------------------------------------------------------
ResourceStatus           ResourceType             LogicalResourceId        ResourceStatusReason   
-------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS       AWS::IAM::Role           HelloWorldFunctionRole   -                      
CREATE_IN_PROGRESS       AWS::IAM::Role           HelloWorldFunctionRole   Resource creation      
                                                                           Initiated              
...                    
-------------------------------------------------------------------------------------------------
CloudFormation outputs from deployed stack
-------------------------------------------------------------------------------------------------
Outputs                                                                                         
-------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                   
Description         Implicit IAM Role created for Hello World function                          
Value               arn:aws:iam::012345678910:role/demo-HelloWorldFunctionRole-VQ4CU7UY7S2K     

Key                 HelloWorldApi                                                               
Description         API Gateway endpoint URL for Prod stage for Hello World function            
Value               https://satnon55e9.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:demo-                        
HelloWorldFunction-G14inKTmSQvK                                                                 
-------------------------------------------------------------------------------------------------
Successfully created/updated stack - demo in us-west-2
```

在部署期間， AWS SAM CLI會自動將 Lambda 函數程式碼上傳至 Amazon S3，並更新我們的範本。我們在 CloudFormation 主控台中修改的範本會反映 Amazon S3 儲存貯體路徑。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: s3://aws-sam-cli-managed-default-samclisam-s3-demo-bucket-1a4x26zbcdkqr/demo/da3c598813f1c2151579b73ad788cac8
      Handler: app.lambda_handler
      ...
```

## 支援的使用案例
<a name="deploy-upload-local-files-use"></a>

對於 AWS SAM CLI多種檔案類型、 CloudFormation 資源類型和 CloudFormation 巨集， 可以自動促進此程序。

### 檔案類型
<a name="deploy-upload-local-files-use-types"></a>

支援應用程式檔案和Docker映像。

### CloudFormation 資源類型
<a name="deploy-upload-local-files-use-resources"></a>

以下是支援的資源類型及其屬性清單：


| 資源 | Properties | 
| --- | --- | 
| AWS::ApiGateway::RestApi | BodyS3Location | 
| AWS::ApiGatewayV2::Api | BodyS3Location | 
| AWS::AppSync:FunctionConfiguration |  `CodeS3Location` `RequestMappingTemplateS3Location` `ResponseMappingTemplateS3Location`  | 
| AWS::AppSync::GraphQLSchema | DefinitionS3Location | 
| AWS::AppSync::Resolver |  `CodeS3Location` `RequestMappingTemplateS3Location` `ResponseMappingTemplateS3Location`  | 
| AWS::CloudFormation::ModuleVersion | ModulePackage | 
| AWS::CloudFormation::ResourceVersion | SchemaHandlerPackage | 
| AWS::ECR::Repository | RepositoryName | 
| AWS::ElasticBeanstalk::ApplicationVersion | SourceBundle | 
| AWS::Glue::Job | Command.ScriptLocation | 
| AWS::Lambda::Function |  `Code` `Code.ImageUri`  | 
| AWS::Lambda::LayerVersion | Content | 
| AWS::Serverless::Api | DefinitionUri | 
| AWS::Serverless::Function |  `CodeUri` `ImageUri`  | 
| AWS::Serverless::GraphQLApi |  `SchemaUri` `Function.CodeUri` `Resolver.CodeUri`  | 
| AWS::Serverless::HttpApi | DefinitionUri | 
| AWS::Serverless::LayerVersion | ContentUri | 
| AWS::Serverless::StateMachine | DefinitionUri | 
| AWS::StepFunctions::StateMachine | DefinitionS3Location | 

### CloudFormation 巨集
<a name="deploy-upload-local-files-use-macros"></a>

支援使用`AWS::Include`轉換巨集參考的檔案。

## 進一步了解
<a name="deploy-upload-local-files-learn"></a>

若要進一步了解`AWS::Include`轉換，請參閱*AWS CloudFormation 《 使用者指南*》中的 [ AWS：：Include 轉換](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/create-reusable-transform-function-snippets-and-add-to-your-template-with-aws-include-transform.html)。

若要查看在 AWS SAM 範本中使用`AWS::Include`轉換的範例，請參閱 * Serverless Land* 的 [API Gateway HTTP API to SQS](https://serverlessland.com/patterns/apigw-sqs) 模式。

# 使用 產生入門 CI/CD 管道 AWS SAM
<a name="serverless-generating-example-ci-cd"></a>

當您準備好自動化部署時，您可以使用其中一個 AWS SAM入門管道範本，為您選擇使用的 CI/CD 系統產生部署管道。您的部署管道是您設定和使用 來自動化無伺服器應用程式的部署。入門管道範本已預先設定，可協助您快速設定無伺服器應用程式的部署管道。

透過入門管道範本，您可以使用 [sam pipeline init](sam-cli-command-reference-sam-pipeline-init.md)命令在幾分鐘內產生管道。

入門管道範本使用 CI/CD 系統熟悉的 JSON/YAML 語法，並納入最佳實務，例如跨多個帳戶和區域管理成品，以及使用部署應用程式所需的最低許可量。目前，CLI AWS SAM 支援為 [AWS CodePipeline](https://aws.amazon.com/codepipeline)、[Jenkins](https://www.jenkins.io/)、[GitLab CI/CD、GitHub Actions 和 Bitbucket Pipelines 產生入門 CI/CD](https://docs.gitlab.com/ee/ci/) 管道組態。 [GitHub ](https://github.com/features/actions) [https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/](https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/)

以下是產生入門管道組態所需的高階任務：

1. **建立基礎設施資源** – 您的管道需要特定 AWS 資源，例如具有必要許可的 IAM 使用者和角色、Amazon S3 儲存貯體，以及選用的 Amazon ECR 儲存庫。

1. **將您的 Git 儲存庫與您的 CI/CD 系統連線** – 您的 CI/CD 系統需要知道哪些 Git 儲存庫會觸發管道執行。請注意，視您使用的 Git 儲存庫和 CI/CD 系統組合而定，可能不需要此步驟。

1. **產生管道組態** – 此步驟會產生入門管道組態，其中包含兩個部署階段。

1. **將您的管道組態遞交至 Git 儲存庫** – 此步驟是必要的，以確保您的 CI/CD 系統了解您的管道組態，並在遞交變更時執行。

在您產生入門管道組態並將其遞交至 Git 儲存庫之後，每當有人對該儲存庫遞交程式碼變更時，管道都會觸發自動執行。

這些步驟的順序，以及每個步驟的詳細資訊，會根據您的 CI/CD 系統而有所不同：
+ 如果您使用的是 AWS CodePipeline，請參閱 [在 AWS CodePipeline 中產生 的入門管道 AWS SAM](serverless-generating-example-ci-cd-codepipeline.md)。
+ 如果您使用的是 Jenkins、GitLab CI/CD、GitHub Actions 或 Bitbucket Pipelines，請參閱 [使用 AWS SAM 為 Jenkins、GitLab CI/CD、GitHub Actions、Bitbucket Pipelines 產生入門管道](serverless-generating-example-ci-cd-others.md)。

# 在 AWS CodePipeline 中產生 的入門管道 AWS SAM
<a name="serverless-generating-example-ci-cd-codepipeline"></a>

若要產生 的入門管道組態 AWS CodePipeline，請依此順序執行下列任務：

1. 建立基礎設施資源

1. 產生管道組態

1. 將您的管道組態遞交至 Git

1. 將您的 Git 儲存庫與您的 CI/CD 系統連線

**注意**  
下列程序使用兩個 AWS SAM CLI命令 `sam pipeline bootstrap`和 `sam pipeline init`。有兩個命令的原因是處理使用案例，其中管理員 （即需要許可來設定基礎設施 AWS 資源的使用者，例如 IAM 使用者和角色） 擁有更多許可，開發人員 （即只需要許可來設定個別管道，但不需要必要基礎設施 AWS 資源的使用者）。

## 步驟 1：建立基礎設施資源
<a name="generating-example-step-1"></a>

使用 的管道 AWS SAM 需要特定 AWS 資源，例如具有必要許可的 IAM 使用者和角色、Amazon S3 儲存貯體，以及選用的 Amazon ECR 儲存庫。您必須針對管道的每個部署階段擁有一組基礎設施資源。

您可以執行下列命令來協助進行此設定：

```
sam pipeline bootstrap
```

**注意**  
針對管道的每個部署階段執行先前的命令。

## 步驟 2：產生管道組態
<a name="generating-example-step-2"></a>

若要產生管道組態，請執行下列命令：

```
sam pipeline init
```

## 步驟 3：將您的管道組態遞交至 Git 儲存庫
<a name="generating-example-step-3"></a>

此步驟是必要的，以確保您的 CI/CD 系統知道您的管道組態，並在遞交變更時執行。

## 步驟 4：將 Git 儲存庫與您的 CI/CD 系統連線
<a name="generating-example-step-4"></a>

對於 AWS CodePipeline ，您現在可以執行下列命令來建立連線：

```
sam deploy -t codepipeline.yaml --stack-name <pipeline-stack-name> --capabilities=CAPABILITY_IAM --region <region-X>
```

如果您使用的是 GitHub 或 Bitbucket，則先前執行 **sam deploy**命令後，請依照*開發人員工具主控台使用者指南*中的更新待定連線主題中的**完成連線**步驟，完成連線。 [https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-update.html](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-update.html)此外，請存放`CodeStarConnectionArn`來自 **sam deploy**命令輸出的 複本，因為如果您想要 AWS CodePipeline 搭配 以外的其他分支使用 ，則需要它`main`。

## 設定其他分支
<a name="configuring-other-branches"></a>

根據預設， AWS CodePipeline 會使用 `main`分支 AWS SAM。如果您想要使用 以外的分支`main`，您必須再次執行 **sam deploy**命令。請注意，視您使用的 Git 儲存庫而定，您可能還需要提供 `CodeStarConnectionArn`：

```
# For GitHub and Bitbucket
sam deploy -t codepipeline.yaml --stack-name <feature-pipeline-stack-name> --capabilities=CAPABILITY_IAM --parameter-overrides="FeatureGitBranch=<branch-name> CodeStarConnectionArn=<codestar-connection-arn>"

# For AWS CodeCommit
sam deploy -t codepipeline.yaml --stack-name <feature-pipeline-stack-name> --capabilities=CAPABILITY_IAM --parameter-overrides="FeatureGitBranch=<branch-name>"
```

## 進一步了解
<a name="serverless-generating-cicd-learn"></a>

如需設定 CI/CD 管道的實作範例，請參閱*完成 AWS SAM 研討會*中的[使用 CI/CD AWS CodePipeline](https://catalog.workshops.aws/complete-aws-sam/en-US/module-4-cicd)。

# 使用 AWS SAM 為 Jenkins、GitLab CI/CD、GitHub Actions、Bitbucket Pipelines 產生入門管道
<a name="serverless-generating-example-ci-cd-others"></a>

若要產生 Jenkins、GitLab CI/CD、GitHub Actions 或 Bitbucket Pipelines 的入門管道組態，請依此順序執行下列任務：

1. 建立基礎設施資源

1. 將您的 Git 儲存庫與您的 CI/CD 系統連線

1. 建立登入資料物件

1. 產生管道組態

1. 將您的管道組態遞交至 Git 儲存庫

**注意**  
下列程序使用兩個 AWS SAM CLI命令 `sam pipeline bootstrap`和 `sam pipeline init`。有兩個命令的原因是處理使用案例，其中管理員 （即需要許可來設定基礎設施 AWS 資源的使用者，例如 IAM 使用者和角色） 擁有更多許可，開發人員 （即只需要許可來設定個別管道，但不需要必要基礎設施 AWS 資源的使用者）。

## 步驟 1：建立基礎設施資源
<a name="generating-example-step-1"></a>

使用 的管道 AWS SAM 需要特定 AWS 資源，例如具有必要許可的 IAM 使用者和角色、Amazon S3 儲存貯體，以及選用的 Amazon ECR 儲存庫。您必須針對管道的每個部署階段擁有一組基礎設施資源。

您可以執行下列命令來協助進行此設定：

```
sam pipeline bootstrap
```

**注意**  
針對管道的每個部署階段執行先前的命令。

您必須為管道的每個部署階段擷取管道使用者的 AWS 登入資料 （金鑰 ID 和私密金鑰），因為後續步驟需要這些登入資料。

## 步驟 2：將 Git 儲存庫與您的 CI/CD 系統連線
<a name="generating-example-step-2"></a>

必須將 Git 儲存庫連線至您的 CI/CD 系統，以便 CI/CD 系統能夠存取您的應用程式原始碼以進行建置和部署。

**注意**  
如果您使用下列其中一個組合，則可以略過此步驟，因為會自動為您完成連線：  
使用 GitHub 儲存庫的 GitHub 動作
使用 GitLab 儲存庫的 GitLab CI/CD
具有 Bitbucket 儲存庫的 Bitbucket 管道

若要將 Git 儲存庫與您的 CI/CD 系統連線，請執行下列其中一項操作：
+ 如果您使用的是 Jenkins，請參閱「新增分支來源」的 [Jenkins 文件](https://www.jenkins.io/doc/book/pipeline/multibranch/)。
+ 如果您使用的是 GitLab CI/CD 和 GitLab 以外的 GitLab 儲存庫，請參閱「連接外部儲存庫」的 [GitLab 文件](https://docs.gitlab.com/ee/ci/ci_cd_for_external_repos/)。

## 步驟 3：建立登入資料物件
<a name="generating-example-step-3"></a>

每個 CI/CD 系統都有自己的方法來管理 CI/CD 系統存取 Git 儲存庫所需的登入資料。

若要建立必要的登入資料物件，請執行下列其中一項操作：
+ 如果您使用的是 Jenkins，請建立儲存金鑰 ID 和私密金鑰的單一「憑證」。請遵循[使用部落格建置 Jenkins 管道 AWS SAM](https://aws.amazon.com/blogs/compute/building-a-jenkins-pipeline-with-aws-sam/)一節中的指示****。下一個步驟需要 "Credential id"。
+ 如果您使用的是 GitLab CI/CD，請建立兩個「受保護的變數」，每個金鑰 ID 和私密金鑰各一個。遵循 [GitLab 文件](https://docs.gitlab.com/ee/ci/variables/)中的指示 – 在下一個步驟中，您將需要兩個「可變金鑰」。
+ 如果您使用的是 GitHub 動作，請建立兩個「加密的秘密」，每個金鑰和私密金鑰各一個。遵循 [GitHub 文件](https://docs.github.com/en/actions/reference/encrypted-secrets)中的指示 - 下一個步驟需要兩個「秘密名稱」。
+ 如果您使用的是 Bitbucket 管道，請建立兩個「安全變數」，每個金鑰 ID 和私密金鑰各一個。遵循[變數和秘密](https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets)中的指示 - 下一個步驟需要兩個「秘密名稱」。

## 步驟 4：產生管道組態
<a name="generating-example-step-4"></a>

若要產生管道組態，請執行下列命令。您需要輸入您在上一個步驟中建立的登入資料物件：

```
sam pipeline init
```

## 步驟 5：將您的管道組態遞交至 Git 儲存庫
<a name="generating-example-step-5"></a>

此步驟是必要的，以確保您的 CI/CD 系統知道您的管道組態，並在遞交變更時執行。

## 進一步了解
<a name="serverless-generating-other-cicd-learn"></a>

如需使用 設定 CI/CD 管道的實作範例GitHub Actions，請參閱 *完成 AWS SAM 研討會*中的[使用 CI/CDGitHub](https://s12d.com/sam-ws-en-gh)。

# 如何使用 自訂入門管道 AWS SAM
<a name="serverless-customizing-starter-pipelines"></a>

身為 CI/CD 管理員，您可能想要自訂入門管道範本和相關聯的引導式提示，組織中的開發人員可以使用這些提示來建立管道組態。

建立入門範本時， AWS SAM CLI會使用 Cookiecutter 範本。如需 Cookie 切線器範本的詳細資訊，請參閱 [Cookiecutter](https://cookiecutter.readthedocs.io/en/latest/README.html)。

您也可以自訂使用 `sam pipeline init`命令建立管道組態時， AWS SAM CLI向使用者顯示的提示。若要自訂使用者提示，請執行下列動作：

1. **建立`questions.json`檔案** – `questions.json` 檔案必須位於專案儲存庫的根目錄中。這是與 `cookiecutter.json` 檔案相同的目錄。若要檢視`questions.json`檔案的結構描述，請參閱 [questions.json.schema](https://github.com/aws/aws-sam-cli/blob/2b831b29f76ac9c4e0cbcbd68b37f8f664e136d8/samcli/lib/pipeline/init/questions.json.schema)。若要檢視範例`questions.json`檔案，請參閱 [questions.json](https://github.com/aws/aws-sam-cli-pipeline-init-templates/blob/main/Jenkins/two-stage-pipeline-template/questions.json)。

1. **使用 Cookiecutter 名稱對應問題金鑰** – `questions.json` 檔案中的每個物件都需要符合 Cookiecutter 範本中名稱的金鑰。此金鑰比對是 將 AWS SAM CLI使用者提示回應映射至 Cookie 切換器範本的方式。若要查看此金鑰比對的範例，請參閱本主題稍後的 [範例檔案](#serverless-customizing-starter-pipelines-example-files)一節。

1. **建立`metadata.json`檔案** – 宣告管道在`metadata.json`檔案中的階段數。階段數目會指示 `sam pipeline init`命令要提示多少階段的資訊，或在 `--bootstrap`選項的情況下，要為其建立基礎設施資源的階段數量。若要檢視宣告具有兩個階段之管道的範例`metadata.json`檔案，請參閱 [metadata.json](https://github.com/aws/aws-sam-cli-pipeline-init-templates/blob/main/Jenkins/two-stage-pipeline-template/metadata.json)。

## 範例專案
<a name="serverless-customizing-starter-pipelines-example-projects"></a>

以下是範例專案，每個專案都包含 Cookiecutter 範本、 `questions.json` 檔案和 `metadata.json` 檔案：
+ Jenkins 範例：[兩階段 Jenkins 管道範本](https://github.com/aws/aws-sam-cli-pipeline-init-templates/tree/main/Jenkins/two-stage-pipeline-template)
+ CodePipeline 範例：[兩階段 CodePipeline 管道範本](https://github.com/aws/aws-sam-cli-pipeline-init-templates/tree/main/AWS-CodePipeline/two-stage-pipeline-template)

## 範例檔案
<a name="serverless-customizing-starter-pipelines-example-files"></a>

以下一組檔案顯示`questions.json`檔案中的問題如何與 Cookiecutter 範本檔案中的項目相關聯。請注意，這些範例是檔案程式碼片段，而不是完整檔案。若要查看完整檔案的範例，請參閱本主題前面的[範例專案](#serverless-customizing-starter-pipelines-example-projects)一節。

範例**`questions.json`**：

```
{
  "questions": [{
    "key": "intro",
    "question": "\nThis template configures a pipeline that deploys a serverless application to a testing and a production stage.\n",
    "kind": "info"
  }, {
    "key": "pipeline_user_jenkins_credential_id",
    "question": "What is the Jenkins credential ID (via Jenkins plugin \"aws-credentials\") for pipeline user access key?",
    "isRequired": true
  }, {
    "key": "sam_template",
    "question": "What is the template file path?",
    "default": "template.yaml"
  }, {
    ...
```

範例**`cookiecutter.json`**：

```
{
  "outputDir": "aws-sam-pipeline",
  "pipeline_user_jenkins_credential_id": "",
  "sam_template": "",
    ...
```

範例**`Jenkinsfile`**：

```
pipeline {
  agent any
  environment {
    PIPELINE_USER_CREDENTIAL_ID = '{{cookiecutter.pipeline_user_jenkins_credential_id}}'
    SAM_TEMPLATE = '{{cookiecutter.sam_template}}'
    ...
```

# 自動化 AWS SAM 應用程式的部署
<a name="serverless-deploying-modify-pipeline"></a>

在 中 AWS SAM，自動化 AWS SAM 應用程式部署的方式取決於您使用的 CI/CD 系統。因此，本節中的範例說明如何設定各種 CI/CD 系統，以在建置容器映像中自動化 AWS SAM 建置無伺服器應用程式。這些建置容器映像可讓您更輕鬆地使用 建置和封裝無伺服器應用程式 AWS SAM CLI。

您現有 CI/CD 管道使用 部署無伺服器應用程式的程序 AWS SAM ，會因您使用的 CI/CD 系統而略有不同。

下列主題提供設定 CI/CD 系統以在建置容器映像中 AWS SAM 建置無伺服器應用程式的範例：

**Topics**
+ [使用 AWS CodePipeline 搭配 部署 AWS SAM](deploying-using-codepipeline.md)
+ [使用 Bitbucket 管道搭配 部署 AWS SAM](deploying-using-bitbucket.md)
+ [使用 Jenkins 透過 部署 AWS SAM](deploying-using-jenkins.md)
+ [使用 GitLab CI/CD 搭配 部署 AWS SAM](deploying-using-gitlab.md)
+ [使用 GitHub 動作搭配 部署 AWS SAM](deploying-using-github.md)

# 使用 AWS CodePipeline 搭配 部署 AWS SAM
<a name="deploying-using-codepipeline"></a>

若要設定[AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)管道以自動化 AWS SAM 應用程式的建置和部署，您的 CloudFormation 範本和`buildspec.yml`檔案必須包含執行下列動作的行：

1. 參考可用映像中具有必要執行時間的建置容器映像。下列範例使用`public.ecr.aws/sam/build-nodejs20.x`建置容器映像。

1. 設定管道階段以執行必要的 AWS SAM 命令列界面 (CLI) 命令。下列範例執行兩個 AWS SAM CLI命令： **sam build**和 **sam deploy**（具有必要選項）。

此範例假設您已使用 宣告 AWS SAM 範本檔案中的所有函數和層`runtime: nodejs20.x`。

**CloudFormation 範本程式碼片段：**

```
  CodeBuildProject:
    Type: AWS::CodeBuild::Project
    Properties:
      Environment:
        ComputeType: BUILD_GENERAL1_SMALL
        Image: public.ecr.aws/sam/build-nodejs20.x
        Type: LINUX_CONTAINER
      ...
```

**`buildspec.yml` 程式碼片段：**

```
version: 0.2
phases:
  build:
    commands:
      - sam build
      - sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
```

如需不同執行時間的可用 Amazon Elastic Container Registry (Amazon ECR) 組建容器映像清單，請參閱 [的影像儲存庫 AWS SAM](serverless-image-repositories.md)。

# 使用 Bitbucket 管道搭配 部署 AWS SAM
<a name="deploying-using-bitbucket"></a>

若要設定 [Bitbucket Pipeline](https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/) 以自動化 AWS SAM 應用程式的建置和部署，您的 `bitbucket-pipelines.yml` 檔案必須包含執行下列動作的行：

1. 參考可用映像中具有必要執行時間的建置容器映像。下列範例使用`public.ecr.aws/sam/build-nodejs20.x`建置容器映像。

1. 設定管道階段以執行必要的 AWS SAM 命令列界面 (CLI) 命令。下列範例執行兩個 AWS SAM CLI命令： **sam build**和 **sam deploy**（具有必要選項）。

此範例假設您已使用 宣告 AWS SAM 範本檔案中的所有函數和層`runtime: nodejs20.x`。

```
image: public.ecr.aws/sam/build-nodejs20.x

pipelines:
  branches:
    main: # branch name
      - step:
          name: Build and Package
          script:
            - sam build
            - sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
```

如需不同執行時間的可用 Amazon Elastic Container Registry (Amazon ECR) 組建容器映像清單，請參閱 [的影像儲存庫 AWS SAM](serverless-image-repositories.md)。

# 使用 Jenkins 透過 部署 AWS SAM
<a name="deploying-using-jenkins"></a>

若要設定 [Jenkins](https://www.jenkins.io/) 管道以自動化 AWS SAM 應用程式的建置和部署，您的 `Jenkinsfile`必須包含執行下列動作的行：

1. 參考可用映像中具有必要執行時間的建置容器映像。下列範例使用`public.ecr.aws/sam/build-nodejs20.x`建置容器映像。

1. 設定管道階段以執行必要的 AWS SAM 命令列界面 (CLI) 命令。下列範例執行兩個 AWS SAM CLI命令： **sam build**和 **sam deploy**（具有必要選項）。

此範例假設您已使用 宣告 AWS SAM 範本檔案中的所有函數和層`runtime: nodejs20.x`。

```
pipeline {
    agent { docker { image 'public.ecr.aws/sam/build-nodejs20.x' } }
    stages {
        stage('build') {
            steps {
                sh 'sam build'
                sh 'sam deploy --no-confirm-changeset --no-fail-on-empty-changeset'
            }
        }
    }
}
```

如需不同執行時間的可用 Amazon Elastic Container Registry (Amazon ECR) 組建容器映像清單，請參閱 [的影像儲存庫 AWS SAM](serverless-image-repositories.md)。

# 使用 GitLab CI/CD 搭配 部署 AWS SAM
<a name="deploying-using-gitlab"></a>

若要設定 [GitLab](https://about.gitlab.com) 管道以自動化 AWS SAM 應用程式的建置和部署，您的`gitlab-ci.yml`檔案必須包含執行下列動作的行：

1. 參考可用映像中具有必要執行時間的建置容器映像。下列範例使用`public.ecr.aws/sam/build-nodejs20.x`建置容器映像。

1. 設定管道階段以執行必要的 AWS SAM 命令列界面 (CLI) 命令。下列範例執行兩個 AWS SAM CLI命令： **sam build**和 **sam deploy**（具有必要選項）。

此範例假設您已使用 宣告 AWS SAM 範本檔案中的所有函數和層`runtime: nodejs20.x`。

```
image: public.ecr.aws/sam/build-nodejs20.x
deploy:
  script:
    - sam build
    - sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
```

如需不同執行時間的可用 Amazon Elastic Container Registry (Amazon ECR) 組建容器映像清單，請參閱 [的影像儲存庫 AWS SAM](serverless-image-repositories.md)。

# 使用 GitHub 動作搭配 部署 AWS SAM
<a name="deploying-using-github"></a>

若要設定 [GitHub](https://github.com/) 管道以自動化 AWS SAM 應用程式的建置和部署，您必須先在主機上安裝 AWS SAM 命令列界面 (CLI)。您可以在 [GitHub 工作流程中使用 GitHub 動作](https://github.com/features/actions)來協助進行此設定。 GitHub 

下列範例 GitHub 工作流程會使用一系列 GitHub 動作設定 Ubuntu 主機，然後執行 AWS SAM CLI命令來建置和部署 AWS SAM 應用程式：

```
on:
  push:
    branches:
      - main
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v3
      - uses: aws-actions/setup-sam@v2
      - uses: aws-actions/configure-aws-credentials@v1
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: us-east-2
      - run: sam build --use-container
      - run: sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
```

如需不同執行時間的可用 Amazon Elastic Container Registry (Amazon ECR) 組建容器映像清單，請參閱 [的影像儲存庫 AWS SAM](serverless-image-repositories.md)。

# 如何搭配 AWS SAM 管道使用 OIDC 身分驗證
<a name="deploying-with-oidc"></a>

AWS Serverless Application Model ()AWS SAM支援 Bitbucket、GitHub Actions 和 GitLab 持續整合和持續交付 (CI/CD) 平台的 OpenID Connect (OIDC) 使用者身分驗證。透過此支援，您可以使用任何這些平台的授權 CI/CD 使用者帳戶來管理您的無伺服器應用程式管道。否則，您將需要建立和管理多個 AWS Identity and Access Management (IAM) 使用者，以控制對 AWS SAM 管道的存取。

## 使用 AWS SAM 管道設定 OIDC
<a name="deploying-with-oidc-setup"></a>

在`sam pipeline bootstrap`組態程序期間，執行下列動作以使用 AWS SAM 管道設定 OIDC。

1. 當系統提示您選擇身分提供者時，請選取 **OIDC**。

1. 接著，選取支援的 OIDC 提供者。

1. 輸入以 開頭的 OIDC 提供者 URL**https://**。
**注意**  
AWS SAM 會在產生`AWS::IAM::OIDCProvider`資源類型時參考此 URL。

1. 接著，依照提示輸入存取所選平台所需的 CI/CD 平台資訊。這些詳細資訊因平台而異，可能包括：
   + OIDC 用戶端 ID。
   + 程式碼儲存庫名稱或通用唯一識別碼 (UUID)。
   + 與儲存庫相關聯的群組或組織名稱。
   + 程式碼儲存庫所屬的 GitHub 組織。
   + GitHub 儲存庫名稱。
   + 部署將從中發生的分支。

1. AWS SAM 會顯示輸入的 OIDC 組態摘要。輸入要編輯之設定的號碼，或按 Enter 繼續。

1. 當系統提示您確認建立支援輸入的 OIDC 連線所需的資源時，請按 Y 繼續。

AWS SAM 會使用 提供的組態產生 `AWS::IAM::OIDCProvider` AWS CloudFormation 資源，以擔任管道執行角色。若要進一步了解此 CloudFormation 資源類型，請參閱*AWS CloudFormation 《 使用者指南*》中的 [AWS::IAM::OIDCProvider](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-oidcprovider.html)。

**注意**  
如果身分提供者 (IdP) 資源已存在於您的 中 AWS 帳戶， AWS SAM 會參考它，而不是建立新的資源。

## 範例
<a name="deploying-with-oidc-setup-example"></a>

以下是使用 AWS SAM 管道設定 OIDC 的範例。

```
Select a permissions provider:
    1 - IAM (default)
    2 - OpenID Connect (OIDC)
Choice (1, 2): 2
Select an OIDC provider:
    1 - GitHub Actions
    2 - GitLab
    3 - Bitbucket
Choice (1, 2, 3): 1
Enter the URL of the OIDC provider [https://token.actions.githubusercontent.com]:
Enter the OIDC client ID (sometimes called audience) [sts.amazonaws.com]:
Enter the GitHub organization that the code repository belongs to. If there is no organization enter your username instead: my-org
Enter GitHub repository name: testing
Enter the name of the branch that deployments will occur from [main]:

[3] Reference application build resources
Enter the pipeline execution role ARN if you have previously created one, or we will create one for you []:
Enter the CloudFormation execution role ARN if you have previously created one, or we will create one for you []:
Please enter the artifact bucket ARN for your Lambda function. If you do not have a bucket, we will create one for you []:
Does your application contain any IMAGE type Lambda functions? [y/N]:

[4] Summary
Below is the summary of the answers:
    1 - Account: 123456
    2 - Stage configuration name: dev
    3 - Region: us-east-1
    4 - OIDC identity provider URL: https://token.actions.githubusercontent.com
    5 - OIDC client ID: sts.amazonaws.com
    6 - GitHub organization: my-org
    7 - GitHub repository: testing
    8 - Deployment branch: main
    9 - Pipeline execution role: [to be created]
    10 - CloudFormation execution role: [to be created]
    11 - Artifacts bucket: [to be created]
    12 - ECR image repository: [skipped]
Press enter to confirm the values above, or select an item to edit the value:

This will create the following required resources for the 'dev' configuration:
    - IAM OIDC Identity Provider
    - Pipeline execution role
    - CloudFormation execution role
    - Artifact bucket
Should we proceed with the creation? [y/N]:
```

## 進一步了解
<a name="deploying-with-oidc-setup-learn-more"></a>

如需搭配 AWS SAM 管道使用 OIDC 的詳細資訊，請參閱 [sam pipeline bootstrap](sam-cli-command-reference-sam-pipeline-bootstrap.md)。

# 使用 sam sync 同步至 的簡介 AWS 雲端
<a name="using-sam-cli-sync"></a>

Command AWS Serverless Application Model Line Interface (AWS SAM CLI) `sam sync`命令提供快速將本機應用程式變更同步至 的選項 AWS 雲端。開發應用程式`sam sync`時使用 來：

1. 自動偵測本機變更並將其同步至 AWS 雲端。

1. 自訂要同步到 的本機變更 AWS 雲端。

1. 在雲端中準備您的應用程式以進行測試和驗證。

使用 `sam sync`，您可以建立快速開發工作流程，以縮短將本機變更同步至雲端進行測試和驗證所需的時間。

**注意**  
建議開發環境使用 `sam sync`命令。對於生產環境，我們建議使用或`sam deploy`設定*持續整合和交付 (CI/CD)* 管道。如需詳細資訊，請參閱 [使用 部署您的應用程式和資源 AWS SAM](serverless-deploying.md)。

`sam sync` 命令是 的一部分 AWS SAM Accelerate。 *AWS SAM Accelerate*提供工具，可讓您用來加速在 中開發和測試無伺服器應用程式的體驗 AWS 雲端。

**Topics**
+ [自動偵測本機變更並將其同步至 AWS 雲端](#using-sam-cli-sync-auto)
+ [自訂要同步到 的本機變更 AWS 雲端](#using-sam-cli-sync-customize)
+ [在雲端中準備您的應用程式以進行測試和驗證](#using-sam-cli-sync-test)
+ [sam 同步命令的選項](#using-sam-cli-sync-options)
+ [疑難排解](#using-sam-cli-sync-troubleshooting)
+ [範例](#using-sam-cli-sync-examples)
+ [進一步了解](#using-sam-cli-sync-learn)

## 自動偵測本機變更並將其同步至 AWS 雲端
<a name="using-sam-cli-sync-auto"></a>

`sam sync` 使用 `--watch`選項執行 ，以開始將您的應用程式同步至 AWS 雲端。這會執行下列動作：

1. **建置您的應用程式 ** – 此程序類似於使用 `sam build`命令。

1. **部署您的應用程式** – AWS SAM CLI AWS CloudFormation 使用預設設定將您的應用程式部署到 。使用下列預設值：

   1. AWS 登入資料和一般組態設定可在您的`.aws`使用者資料夾中找到。

   1. 在您的應用程式`samconfig.toml`檔案中找到的應用程式部署設定。

   如果找不到預設值， AWS SAM CLI會通知您並結束同步程序。

1. **注意本機變更** – AWS SAM CLI會保持執行狀態，並注意應用程式的本機變更。這是 `--watch`選項提供的內容。

   此選項預設為開啟。如需預設值，請參閱您應用程式的 `samconfig.toml` 檔案。以下是範例 檔案：

   ```
   ...
   [default.sync]
   [default.sync.parameters]
   watch = true
   ...
   ```

1. **同步本機變更至 AWS 雲端**- 當您進行本機變更時， AWS 雲端 會透過可用的最快速方法 AWS SAM CLI偵測和同步這些變更至 。視變更類型而定，可能會發生下列情況：

   1. 如果您更新的資源支援服務 AWS APIs， AWS SAM CLI將使用它來部署您的變更。這會導致快速同步，以更新 中的資源 AWS 雲端。

   1. 如果您更新的資源不支援 AWS 服務 APIs， AWS SAM CLI將執行 CloudFormation 部署。這會在 中更新您的整個應用程式 AWS 雲端。雖然速度不那麼快，但它確實讓您無法手動啟動部署。

由於 `sam sync`命令會在 中自動更新您的應用程式 AWS 雲端，因此建議僅用於開發環境。當您執行 時`sam sync`，系統會要求您確認：

```
**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]: ENTER
```

## 自訂要同步到 的本機變更 AWS 雲端
<a name="using-sam-cli-sync-customize"></a>

提供選項來自訂要同步到 的本機變更 AWS 雲端。這可以加快在雲端中查看本機變更以進行測試和驗證所需的時間。

例如，提供僅同步程式碼變更`--code`的選項，例如 AWS Lambda 函數程式碼。在開發期間，如果您特別專注於 Lambda 程式碼，這將使您快速變更到雲端進行測試和驗證。以下是範例：

```
$ sam sync --code --watch
```

若要僅同步特定 Lambda 函數或 layer 的程式碼變更，請使用 `--resource-id`選項。以下是範例：

```
$ sam sync --code --resource-id HelloWorldFunction --resource-id HelloWorldLayer
```

## 在雲端中準備您的應用程式以進行測試和驗證
<a name="using-sam-cli-sync-test"></a>

`sam sync` 命令會自動尋找可用於在 中更新應用程式的最快方法 AWS 雲端。這可以加快您的開發和雲端測試工作流程。透過利用 AWS 服務 APIs，您可以快速開發、同步和測試支援的資源。如需實作範例，請參閱*完成 AWS SAM 研討會*中的[單元 6 - AWS SAM 加速](https://s12d.com/sam-ws-en-accelerate)。

## sam 同步命令的選項
<a name="using-sam-cli-sync-options"></a>

以下是您可以用來修改`sam sync`命令的一些主要選項。如需所有選項的清單，請參閱 [sam sync](sam-cli-command-reference-sam-sync.md)。

### 執行一次性 CloudFormation 部署
<a name="using-sam-cli-sync-options-single-deploy"></a>

使用 `--no-watch`選項來關閉自動同步。以下是範例：

```
$ sam sync --no-watch
```

 AWS SAM CLI 將執行一次性 CloudFormation 部署。此命令會將 `sam build`和 `sam deploy`命令執行的動作分組在一起。

### 略過初始 CloudFormation 部署
<a name="using-sam-cli-sync-options-skip-deploy-sync"></a>

您可以自訂每次執行`sam sync`時是否需要 CloudFormation 部署。
+ 提供 `--no-skip-deploy-sync`以在每次執行`sam sync`時要求 CloudFormation 部署。這可確保您的本機基礎設施同步到 CloudFormation，防止偏離。使用此選項可為您的開發和測試工作流程增加額外的時間。
+ 提供 `--skip-deploy-sync` 讓 CloudFormation 部署成為選用。 AWS SAM CLI 會將您的本機 AWS SAM 範本與部署的 CloudFormation 範本進行比較，如果未偵測到變更， 會略過初始 CloudFormation 部署。略過 CloudFormation 部署可節省您同步本機變更至 的時間 AWS 雲端。

  如果未偵測到變更， AWS SAM CLI仍會在下列情況下執行 CloudFormation 部署：
  + 如果自上次 CloudFormation 部署以來已超過 7 天。
  + 如果偵測到大量的 Lambda 函數程式碼變更，讓 CloudFormation 部署成為更新應用程式的最快方法。

以下是範例：

```
$ sam sync --skip-deploy-sync
```

### 從巢狀堆疊同步資源
<a name="using-sam-cli-sync-options-nested-stack"></a>

**從巢狀堆疊同步資源**

1. 使用 提供根堆疊`--stack-name`。

1. 使用下列格式識別巢狀堆疊中的資源：`nestedStackId/resourceId`。

1. 使用 在巢狀堆疊中提供資源`--resource-id`。

   以下是範例：

   ```
   $ sam sync --code --stack-name sam-app --resource-id myNestedStack/HelloWorldFunction
   ```

如需建立巢狀應用程式的詳細資訊，請參閱 [在 中使用巢狀應用程式重複使用程式碼和資源 AWS SAM](serverless-sam-template-nested-applications.md)。

### 指定要更新的特定 CloudFormation 堆疊
<a name="using-sam-cli-sync-options-stack-name"></a>

若要指定要更新的特定 CloudFormation 堆疊，請提供 `--stack-name`選項。以下是範例：

```
$ sam sync --stack-name dev-sam-app
```

### 在來源資料夾中建置您的專案，以加快建置時間
<a name="using-sam-cli-sync-options-source"></a>

對於支援的執行時間和建置方法，您可以使用 `--build-in-source`選項直接在來源資料夾中建置專案。根據預設， 會在暫存目錄中 AWS SAM CLI建置，這涉及透過原始碼和專案檔案進行複製。使用 `--build-in-source`時， AWS SAM 會直接在您的來源資料夾中CLI建置，而不需要將檔案複製到暫時目錄，即可加速建置程序。

如需支援的執行時間和建置方法清單，請參閱 ` --build-in-source`。

### 指定不會啟動同步的檔案和資料夾
<a name="using-sam-cli-sync-options-exclude"></a>

使用 `--watch-exclude`選項指定更新時不會啟動同步的任何檔案或資料夾。如需有關此選項的詳細資訊，請參閱 `--watch-exclude`。

以下是排除與`HelloWorldFunction`函數相關聯`package-lock.json`檔案的範例：

```
$ sam sync --watch --watch-exclude HelloWorldFunction=package-lock.json
```

執行此命令時， AWS SAM CLI會啟動同步程序。這包含下列項目：
+ 執行 `sam build` 來建置您的 函數，並準備您的應用程式以進行部署。
+ 執行 `sam deploy`以部署您的應用程式。
+ 請注意應用程式的變更。

當我們修改`package-lock.json`檔案時， AWS SAM CLI 不會啟動同步。更新另一個檔案時， AWS SAM CLI會啟動同步，其中包含 `package-lock.json` 檔案。

以下是指定子堆疊 Lambda 函數的範例：

```
$ sam sync --watch --watch-exclude ChildStackA/MyFunction=database.sqlite3
```

## 疑難排解
<a name="using-sam-cli-sync-troubleshooting"></a>

若要對 進行故障診斷 AWS SAM CLI，請參閱 [AWS SAM CLI 故障診斷](sam-cli-troubleshooting.md)。

## 範例
<a name="using-sam-cli-sync-examples"></a>

### 使用 sam 同步更新 Hello World 應用程式
<a name="using-sam-cli-sync-examples-example1"></a>

在此範例中，我們從初始化範例 Hello World 應用程式開始。若要進一步了解此應用程式，請參閱 [教學課程：使用 部署 Hello World 應用程式 AWS SAM](serverless-getting-started-hello-world.md)。

執行 會`sam sync`開始建置和部署程序。

```
$ sam sync
				
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]:
Queued infra sync. Waiting for in progress code syncs to complete...
Starting infra sync.
Manifest file is changed (new hash: 3298f13049d19cffaa37ca931dd4d421) or dependency folder (.aws-sam/deps/0663e6fe-a888-4efb-b908-e2344261e9c7) is missing for (HelloWorldFunction), downloading dependencies and copying/building source
Building codeuri: /Users/.../Demo/sync/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
Running PythonPipBuilder:CleanUp
Running PythonPipBuilder:ResolveDependencies
Running PythonPipBuilder:CopySource

Build Succeeded

Successfully packaged artifacts and wrote output template to file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpx_5t4u3f.
Execute the following command to deploy the packaged template
sam deploy --template-file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpx_5t4u3f --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-samclisam-s3-demo-bucket-1a4x26zbcdkqr
    Capabilities                 : ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"]
    Parameter overrides          : {}
    Signing Profiles             : null

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


2023-03-17 11:17:19 - Waiting for stack create/update to complete

CloudFormation events from stack operations (refresh every 0.5 seconds)
---------------------------------------------------------------------------------------------------------------------------------------------
ResourceStatus                      ResourceType                        LogicalResourceId                   ResourceStatusReason
---------------------------------------------------------------------------------------------------------------------------------------------
CREATE_IN_PROGRESS                  AWS::CloudFormation::Stack          sam-app                             Transformation succeeded
CREATE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                        ack
CREATE_IN_PROGRESS                  AWS::IAM::Role                      HelloWorldFunctionRole              -
CREATE_IN_PROGRESS                  AWS::IAM::Role                      HelloWorldFunctionRole              Resource creation Initiated
CREATE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   Resource creation Initiated
                                                                        ack
CREATE_COMPLETE                     AWS::IAM::Role                      HelloWorldFunctionRole              -
CREATE_COMPLETE                     AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                        ack
CREATE_IN_PROGRESS                  AWS::Lambda::Function               HelloWorldFunction                  -
CREATE_IN_PROGRESS                  AWS::Lambda::Function               HelloWorldFunction                  Resource creation Initiated
CREATE_COMPLETE                     AWS::Lambda::Function               HelloWorldFunction                  -
CREATE_IN_PROGRESS                  AWS::ApiGateway::RestApi            ServerlessRestApi                   -
CREATE_IN_PROGRESS                  AWS::ApiGateway::RestApi            ServerlessRestApi                   Resource creation Initiated
CREATE_COMPLETE                     AWS::ApiGateway::RestApi            ServerlessRestApi                   -
CREATE_IN_PROGRESS                  AWS::ApiGateway::Deployment         ServerlessRestApiDeployment47fc2d   -
                                                                        5f9d
CREATE_IN_PROGRESS                  AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   -
                                                                        ssionProd
CREATE_IN_PROGRESS                  AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   Resource creation Initiated
                                                                        ssionProd
CREATE_IN_PROGRESS                  AWS::ApiGateway::Deployment         ServerlessRestApiDeployment47fc2d   Resource creation Initiated
                                                                        5f9d
CREATE_COMPLETE                     AWS::ApiGateway::Deployment         ServerlessRestApiDeployment47fc2d   -
                                                                        5f9d
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             HelloWorldFunctionHelloWorldPermi   -
                                                                        ssionProd
CREATE_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-BUFVMO2PJIYF

Key                 HelloWorldApi
Description         API Gateway endpoint URL for Prod stage for Hello World function
Value               https://pcrx5gdaof.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-2PlN6TPTQoco
----------------------------------------------------------------------------------------------------------------------------------------------
Stack creation succeeded. Sync infra completed.

Infra sync completed.
CodeTrigger not created as CodeUri or DefinitionUri is missing for ServerlessRestApi.
```

部署完成後，我們會修改`HelloWorldFunction`程式碼。 AWS SAM CLI 會偵測此變更，並將我們的應用程式同步至 AWS 雲端。由於 AWS Lambda 支援 AWS 服務 APIs，因此會執行快速同步。

```
Syncing Lambda Function HelloWorldFunction...
Manifest is not changed for (HelloWorldFunction), running incremental build
Building codeuri: /Users/.../Demo/sync/sam-app/hello_world runtime: python3.9 metadata: {} architecture: x86_64 functions: HelloWorldFunction
Running PythonPipBuilder:CopySource
Finished syncing Lambda Function HelloWorldFunction.
```

接著，我們在應用程式的 AWS SAM 範本中修改 API 端點。我們將 `/hello`變更為 `/helloworld`。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    ...
    Properties:
      ...
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /helloworld
            Method: get
```

由於 Amazon API Gateway 資源不支援 AWS 服務 API，因此 AWS SAM CLI會自動執行 CloudFormation 部署。以下是輸出範例：

```
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/sync/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/tmpuabo0jb9.
Execute the following command to deploy the packaged template
sam deploy --template-file /var/folders/45/5ct135bx3fn2551_ptl5g6_80000gr/T/tmpuabo0jb9 --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-samclisam-s3-demo-bucket-1a4x26zbcdkqr
    Capabilities                 : ["CAPABILITY_NAMED_IAM", "CAPABILITY_AUTO_EXPAND"]
    Parameter overrides          : {}
    Signing Profiles             : null

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


2023-03-17 14:41:18 - 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
UPDATE_IN_PROGRESS                  AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                        ack
UPDATE_COMPLETE                     AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                        ack
UPDATE_IN_PROGRESS                  AWS::ApiGateway::RestApi            ServerlessRestApi                   -
UPDATE_COMPLETE                     AWS::ApiGateway::RestApi            ServerlessRestApi                   -
CREATE_IN_PROGRESS                  AWS::ApiGateway::Deployment         ServerlessRestApiDeployment8cf30e   -
                                                                        d3cd
UPDATE_IN_PROGRESS                  AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   Requested update requires the
                                                                        ssionProd                           creation of a new physical
                                                                                                            resource; hence creating one.
UPDATE_IN_PROGRESS                  AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   Resource creation Initiated
                                                                        ssionProd
CREATE_IN_PROGRESS                  AWS::ApiGateway::Deployment         ServerlessRestApiDeployment8cf30e   Resource creation Initiated
                                                                        d3cd
CREATE_COMPLETE                     AWS::ApiGateway::Deployment         ServerlessRestApiDeployment8cf30e   -
                                                                        d3cd
UPDATE_IN_PROGRESS                  AWS::ApiGateway::Stage              ServerlessRestApiProdStage          -
UPDATE_COMPLETE                     AWS::ApiGateway::Stage              ServerlessRestApiProdStage          -
UPDATE_COMPLETE                     AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   -
                                                                        ssionProd
UPDATE_COMPLETE_CLEANUP_IN_PROGRE   AWS::CloudFormation::Stack          sam-app                             -
SS
DELETE_IN_PROGRESS                  AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   -
                                                                        ssionProd
DELETE_IN_PROGRESS                  AWS::ApiGateway::Deployment         ServerlessRestApiDeployment47fc2d   -
                                                                        5f9d
DELETE_COMPLETE                     AWS::ApiGateway::Deployment         ServerlessRestApiDeployment47fc2d   -
                                                                        5f9d
UPDATE_COMPLETE                     AWS::CloudFormation::Stack          AwsSamAutoDependencyLayerNestedSt   -
                                                                        ack
DELETE_COMPLETE                     AWS::Lambda::Permission             HelloWorldFunctionHelloWorldPermi   -
                                                                        ssionProd
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-BUFVMO2PJIYF

Key                 HelloWorldApi
Description         API Gateway endpoint URL for Prod stage for Hello World function
Value               https://pcrx5gdaof.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-2PlN6TPTQoco
----------------------------------------------------------------------------------------------------------------------------------------------


Stack update succeeded. Sync infra completed.

Infra sync completed.
```

## 進一步了解
<a name="using-sam-cli-sync-learn"></a>

如需所有`sam sync`選項的說明，請參閱 [sam sync](sam-cli-command-reference-sam-sync.md)。