

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

# 使用同步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)。