

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

# 使用部署您的应用程序和资源 AWS SAM
<a name="serverless-deploying"></a>

部署应用程序会预置和配置 AWS 云中的 AWS 资源，从而使您的应用程序在云中运行。 AWS SAM [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/)用作其底层部署机制。 AWS SAM 使用您在运行**sam build**命令时创建的构建工件作为部署无服务器应用程序的标准输入。

使用 AWS SAM，您可以手动部署无服务器应用程序，也可以自动部署。要实现部署自动化，您可以使用带有您选择的持续集成和持续部署 (CI/CD) 系统的 AWS SAM 管道。您的部署管线是一系列自动执行的步骤，用于发布无服务器应用程序的新版本。

本节中的主题提供了有关自动部署和手动部署的指导。要手动部署应用程序，请使用 AWS SAMCLI 命令。要自动执行部署，请参阅本节中的主题。他们特别提供了有关使用管道和 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 命令行界面 (AWS SAMCLI) `sam deploy` 命令将您的无服务器应用程序部署到。 AWS 云
+ 有关简介 AWS SAMCLI，请参阅[那是什么 AWS SAMCLI？](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 deploy 部署应用程序](#using-sam-cli-deploy-deploying)
+ [最佳实践](#using-sam-cli-deploy-best)
+ [sam deploy 的选项](#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 deploy 部署应用程序
<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 SAMCLI部署到。 AWS 云在部署过程中，命令提示符中会显示进度。以下是部署的主要阶段：
   + 对于 AWS Lambda 功能打包为.zip 文件存档的应用程序， AWS SAMCLI压缩包并将其上传到亚马逊简单存储服务 (Amazon S3) 存储桶。如有必要， AWS SAM CLI 会创建新的存储桶。
   + 对于将 Lambda 函数打包为容器映像的应用程序， AWS SAM CLI 会将映像上传到 Amazon Elastic Container Registry (Amazon ECR)。如有必要， AWS SAM CLI 会创建新的存储库。
   +  AWS SAMCLI创建 AWS CloudFormation 更改集并将您的应用程序 CloudFormation 作为堆栈部署到其中。
   + 使用您的 Lambda 函数的新`CodeUri`值 AWS SAMCLI修改您部署的 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. 使用 [https://console.aws.amazon.com/cloudformat](https://console.aws.amazon.com/cloudformation/) ion 网址直接打开 CloudFormation 控制台。

   1. 选择**堆栈**。

   1. 通过应用程序名称识别堆栈并选择它。

### 在部署之前验证更改
<a name="using-sam-cli-deploy-deploying-changes"></a>

您可以将配置 AWS SAMCLI为显示您的 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 deploy 的选项
<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 SAMCLI，请参阅[AWS SAM CLI 故障排除](sam-cli-troubleshooting.md)。

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

### 部署包含打包为 .zip 文件存档的 Lambda 函数的 Hello World 应用程序
<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)。

### 部署包含打包为容器映像的 Lambda 函数的 Hello World 应用程序
<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 会使用 Docker 在本地构建 Lambda 函数。

```
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 SAMCLI部署到。 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 SAMCLI`sam deploy`命令的更多信息，请参阅以下内容：
+ **[完整 AWS SAM 研讨会：模块 3-手动部署-](https://s12d.com/sam-ws-en-manual-deploy)** 学习如何使用构建、打包和部署无服务器应用程序。 AWS SAMCLI

# 用于部署应用程序的选项 AWS SAM
<a name="deploying-options"></a>

借 AWS SAM助，您可以手动部署应用程序并自动进行部署。使用 AWS SAMCLI 来手动部署应用程序。要自动执行部署，请使用管线与持续集成和持续部署（CI/CD）系统。本节中的主题提供有关这两种方法的信息。

**Topics**
+ [如何使用 AWS SAMCLI 手动部署](#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 SAMCLI 手动部署
<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 还为多个 CI/CD 系统提供一组默认管道模板，用于封 AWS装部署最佳实践。

有关更多信息，请参阅 [使用 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>

有关部署无服务器应用程序的实际操作示例，请参阅*完整 AWS SAM 研讨会中的*以下内容：
+ [模块 3-手动部署-](https://s12d.com/sam-ws-en-manual-deploy) 学习如何使用构建、打包和部署无服务器应用程序。 AWS SAMCLI
+ [模块 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 Lambda 运行时的 AWS SAMCLI和构建工具。这使得使用构建和打包无服务器应用程序变得更加容易。 AWS SAMCLI这些映像还可以减轻团队为 CI/CD 系统创建和管理自己的映像的需求。有关 AWS SAM 构建容器镜像的更多信息，请参阅[的图像存储库 AWS SAM](serverless-image-repositories.md)。

多个 CI/CD 系统支持 AWS SAM 构建容器镜像。你应该使用哪种 CI/CD 系统取决于几个因素。这些因素包括：应用程序使用单个运行时系统还是多个运行时系统；您是要在容器映像中还是直接在主机（虚拟机 (VM) 或裸机主机）上构建应用程序。

AWS SAM 还为多个 CI/CD 系统提供了一组默认管道模板，这些模板封装 AWS了部署最佳实践。这些默认管道模板使用标准的 JSON/YAML 管道配置格式，内置的最佳实践有助于执行多账户和多区域部署，并验证管道不会对基础设施进行意外更改。

您可以使用两个主要选项 AWS SAM 来部署无服务器应用程序：1) 修改现有工作流配置以使用 AWS SAMCLI命令，或者 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)
+ [如何对管道使用 OIDC 身份验证 AWS SAM](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/)、C [GitLab I/CD 和 Ac](https://docs.gitlab.com/ee/ci/) tions。GitHub](https://github.com/features/actions)

管道模板包括 AWS 部署最佳实践，可帮助进行多账户和多区域部署。 AWS 诸如开发和生产环境之类的环境通常存在于不同的 AWS 账户中。这允许开发团队配置安全的部署管线，而无需对基础设施进行意外更改。

您还可以提供自己的自定义管线模板，以帮助跨开发团队标准化管线。

# 如何在 AWS SAM 部署时上传本地文件
<a name="deploy-upload-local-files"></a>

当您将应用程序部署到时 AWS 云， AWS CloudFormation 需要先将本地文件上传到可访问的 AWS 服务，例如亚马逊简单存储服务 (Amazon S3) Service。这包括您的 AWS SAM 模板引用的本地文件。为了满足此要求，在使用 `sam deploy` 或 `sam package` 命令时， AWS SAMCLI 会执行以下操作：

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 模板中，我们使用属性引用 Lambda 函数代码的本地路径。`CodeUri`

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

对于多种文件类型、 CloudFormation 资源类型和 CloudFormation 宏， AWS SAMCLI可以自动简化此过程。

### 文件类型
<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`转换的示例，请参阅 S *erver* less Land 上[的 API Gateway HTTP API 到 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 语法，并纳入了最佳实践，例如跨多个账户和区域管理工件，以及使用部署应用程序所需的最低权限量。[https://github.com/features/actions](https://github.com/features/actions)

以下是生成入门管道配置所需执行的高级任务：

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 in 生成入门管道 AWS SAM](serverless-generating-example-ci-cd-codepipeline.md)。
+ 如果你使用的是 Jenkins、C GitLab I/CD、Actions 或 Bitbucket Pipelines，请参 GitHub 阅。[用于 AWS SAM 为 Jenkins、C GitLab I/CD、Actions、Bitbucket Pipelines 生成入 GitHub](serverless-generating-example-ci-cd-others.md)

# 正在为 AWS CodePipeline in 生成入门管道 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>
```

如果您使用的是 Bitbucket， GitHub 则在之前运行**sam deploy**命令后，请按照*开发者工具控制台用户指南*中 “[更新待处理的**连接” 主题中的 “完成**连接](https://docs.aws.amazon.com/dtconsole/latest/userguide/connections-update.html)” 下的步骤完成连接，完成连接。此外，请存储**sam deploy**命令输出`CodeStarConnectionArn`中的副本，因为如果您想与之以外的其他分支 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 *研讨会 AWS CodePipeline中的 [CI/CD](https://catalog.workshops.aws/complete-aws-sam/en-US/module-4-cicd)。

# 用于 AWS SAM 为 Jenkins、C GitLab I/CD、Actions、Bitbucket Pipelines 生成入 GitHub
<a name="serverless-generating-example-ci-cd-others"></a>

要为 Jenkins、C GitLab I/CD、Actions 或 Bitbucket Pipelines 生成入门工作流配置，请按以下顺序执行以下任务： GitHub 

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 带有存储库的 CI/CD GitLab 
带有 Bitbucket 存储库的 Bitbucket 管线

要将 Git 存储库与 CI/CD 系统连接，请执行以下任一操作：
+ 如果您使用的是 Jenkins，请参阅 [Jenkins 文档](https://www.jenkins.io/doc/book/pipeline/multibranch/)中的“添加分支源”。
+ 如果您使用的是 C GitLab I/CD 和除之外的 Git 存储库 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构建 Jenkins 管道](https://aws.amazon.com/blogs/compute/building-a-jenkins-pipeline-with-aws-sam/)博客中的说明进行操作。下一步您将需要用到“凭证 ID”。
+ 如果您使用的是 C GitLab I/CD，请创建两个 “受保护变量”，密钥 ID 和密钥各一个。按照[GitLab 文档](https://docs.gitlab.com/ee/ci/variables/)中的说明进行操作 — 下一步需要两个 “变量键”。
+ 如果您使用的是 Ac GitHub tions，请创建两个 “加密机密”，密钥和密钥各一个。按照[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 *研讨会GitHub中的 [CI/CD](https://s12d.com/sam-ws-en-gh)。

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

作为 CI/CD 管理员，您可能需要自定义入门工作流模板和相关的指导性提示，组织中的开发人员可以使用这些模板来创建工作流配置。

在创建入门模板时 AWS SAM CLI 使用 Cookiecutter 模板。有关 cookiecutter 模板的详细信息，请访问 [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 如何将用户提示响应映射到 cookiecutter 模板。要查看此键匹配示例，请参阅本主题后面的 [示例文件](#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 SAMCLI

根据您使用的 CI/CD 系统，现有 CI/CD 管道部署无服务器应用程序的过程略 AWS SAM 有不同。

以下主题提供了配置 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 Pipelin](https://support.atlassian.com/bitbucket-cloud/docs/get-started-with-bitbucket-pipelines/) e 配置为自动构建和部署 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操作设置 Ubuntu 主机，然后运行 AWS SAMCLI命令来构建和部署应用程序： 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)。

# 如何对管道使用 OIDC 身份验证 AWS SAM
<a name="deploying-with-oidc"></a>

AWS Serverless Application Model (AWS SAM) 支持 OpenID Connect (OIDC) 用户身份验证，支持 Bitbucket、 GitHub Actions、 GitLab 持续集成和持续交付（来自这些平台的CI/CD) platforms. With this support, you can use authorized CI/CD用户账户），用于管理您的无服务器应用程序管道。 否则，您需要创建和管理多个 AWS Identity and Access Management (IAM) 用户来控制对 AWS SAM 管道的访问权限。

## 使用管道设置 OIDC AWS SAM
<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 用户指南OIDCProvider*中的 [AWS:: IAM](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>

以下是使用管道设置 OIDC 的 AWS SAM 示例。

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

有关将 OIDC 与 AWS SAM 管道配合使用的更多信息，请参阅。[sam pipeline bootstrap](sam-cli-command-reference-sam-pipeline-bootstrap.md)

# 使用同步sam sync到的简介 AWS 云
<a name="using-sam-cli-sync"></a>

 AWS Serverless Application Model 命令行界面 (AWS SAMCLI) `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 sync 命令的选项](#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>

通过 `--watch` 选项运行 `sam sync` 以开始将应用程序同步到 AWS 云。其执行以下操作：

1. **构建应用程序** – 此过程与使用 `sam build` 命令类似。

1. **部署应用程序** – AWS SAM CLI 使用您的默认设置将应用程序部署到 AWS CloudFormation 。使用以下默认值：

   1. AWS 可在您的`.aws`用户文件夹中找到凭据和常规配置设置。

   1. 应用程序部署设置可在应用程序 `samconfig.toml` 文件中找到。

   如果找不到默认值，则 AWS SAM CLI 会通知您并退出同步过程。

1. **注意本地更改** – AWS SAMCLI 保持运行状态，并监视应用程序的本地更改。这就是 `--watch` 选项提供的内容。

   默认情况下，此选项可能处于启用状态。有关默认值，请参阅应用程序的 `samconfig.toml` 文件。以下是 文件示例：

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

1. 将@@ **本地更改同步到 AWS 云** — 当您进行本地更改时，会 AWS 云 通过最快的可用方法 AWS SAMCLI检测这些更改并将其同步到。根据变更的类型，可能会出现以下情况：

   1. 如果您更新的资源支持 AWS 服务 APIs，则 AWS SAMCLI将使用它来部署您的更改。这会导致快速同步以更新 AWS 云中的资源。

   1. 如果您更新的资源不支持 AWS 服务 APIs，则 AWS SAMCLI将执行 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 云中。这可以加快在云端查看本地更改以进行测试和验证所需的时间。

例如，提供仅同步代码更改（例如 AWS Lambda 函数代码）的`--code`选项。在开发过程中，如果您特别关注 Lambda 代码，这会将您的更改快速发送到云端进行测试和验证。以下是示例：

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

要仅同步特定 Lambda 函数或层的代码更改，请使用选项 `--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 sync 命令的选项
<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 SAMCLI将执行一次性 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 SAMCLI会将您的本地 AWS SAM 模板与已部署 CloudFormation 的模板进行比较，如果未检测到更改，则会跳过初始 CloudFormation 部署。在将本地更改同步到时，跳过 CloudFormation 部署可以节省时间。 AWS 云

  如果未检测到任何更改，则在以下情况下仍 AWS SAMCLI会执行 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 SAMCLI，请参阅[AWS SAM CLI 故障排除](sam-cli-troubleshooting.md)。

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

### 使用 sam sync 更新 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 SAMCLI检测到此更改，并将我们的应用程序同步到。 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 SAMCLI会自动执行 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)。