

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

# 使用开发您的无服务器应用程序 AWS SAM
<a name="chapter-create-application"></a>

本节包含有关验证 AWS SAM 模板和使用依赖项构建应用程序的主题。它还包含有关在某些用例中使用的主题，例如使用 Lambda 层、使用嵌套应用程序、控制 API Gat APIs eway 的访问权限、使用 Ste AWS p Functions 编排资源以及对应用程序进行代码签名。 AWS SAM 下面列出了开发应用程序需要完成的三个主要里程碑。

**Topics**
+ [

# 在中创建您的应用程序 AWS SAM
](using-sam-cli-init.md)
+ [

# 使用以下方式定义您的基础架构 AWS SAM
](serverless-authoring.md)
+ [

# 使用构建您的应用程序 AWS SAM
](serverless-building.md)

# 在中创建您的应用程序 AWS SAM
<a name="using-sam-cli-init"></a>

完成[入门](serverless-getting-started.md)和阅读[如何使用 AWS Serverless Application Model (AWS SAM)](chapter-using-sam.md)后，您就可以准备好在开发人员环境中创建 AWS SAM 项目了。您的 AWS SAM 项目将作为编写无服务器应用程序的起点。有关 AWS SAMCLI`sam init`命令选项的列表，请参见[sam init](sam-cli-command-reference-sam-init.md)。

 AWS Serverless Application Model 命令行接口 (AWS SAMCLI) `sam init` 命令提供了用于初始化新的无服务器应用程序的选项，该应用程序包括：
+ 用于定义基础架构代码的 AWS SAM 模板。
+ 用于组织应用程序的文件夹结构。
+ 为您的 AWS Lambda 函数进行配置。

要创建 AWS SAM 项目，请参阅本节中的主题。

**注意**  
`sam init`包括支持运行时（Python TypeScript、Java）中持久函数的项目模板。这些模板为构建有状态的无服务器应用程序提供了入门代码和配置。

**Topics**
+ [

## 初始化新的无服务器应用程序
](#using-sam-cli-init-new)
+ [

## sam init 的选项
](#using-sam-cli-init-options)
+ [

## 问题排查
](#using-sam-cli-init-troubleshooting)
+ [

## 示例
](#using-sam-cli-init-examples)
+ [

## 了解详情
](#using-sam-cli-init-learn)
+ [

## 后续步骤
](#w2aac18c11c39)

## 初始化新的无服务器应用程序
<a name="using-sam-cli-init-new"></a>

**使用 AWS SAM CLI 初始化新的无服务器应用程序**

1. 指向起始目录的 `cd`。

1. 在命令行中执行以下命令：

   ```
   $ sam init
   ```

1.  AWS SAM CLI 会指导您完成交互式流程，以创建新的无服务器应用程序。
**注意**  
如[教程：使用以下命令部署 Hello World 应用程序 AWS SAM](serverless-getting-started-hello-world.md)中所述，此命令会初始化您的无服务器应用程序，从而创建您的项目目录。此目录将包含多个文件和文件夹。最重要的文件是 `template.yaml`。这是你的 AWS SAM 模板。您的 python 版本必须与 **sam init** 命令创建的 `template.yaml` 文件中列出的 python 版本匹配。

### 选择起始模板
<a name="using-sam-cli-init-new-template"></a>

*模板*由以下部分组成：

1. 基础架构代码的 AWS SAM 模板。

1. 用于组织项目文件的项目起始目录。例如，这可能包括：

   1. Lambda 函数代码及其依赖项的结构。

   1. 包含用于本地测试的测试事件的 `events` 文件夹。

   1. 支持单元测试的 `tests` 文件夹。

   1. 用于配置项目设置的 `samconfig.toml` 文件。

   1. `ReadMe` 文件和其他基本的项目起始文件。

   以下是项目起始目录的示例：

   ```
   sam-app
   ├── README.md
   ├── __init__.py
   ├── events
   │   └── event.json
   ├── hello_world
   │   ├── __init__.py
   │   ├── app.py
   │   └── requirements.txt
   ├── samconfig.toml
   ├── template.yaml
   └── tests
       ├── __init__.py
       ├── integration
       │   ├── __init__.py
       │   └── test_api_gateway.py
       ├── requirements.txt
       └── unit
           ├── __init__.py
           └── test_handler.py
   ```

您可以从可用的 *AWS 快速入门模板*列表中进行选择，也可以自行提供*自定义模板位置*。

**选择 AWS 快速入门模板**

1. 当系统提示时，选择 **AWS 快速入门模板**。

1. 首先选择一个 AWS 快速入门模板。以下是示例：

   ```
   Which template source would you like to use?
       1 - AWS Quick Start Templates
       2 - Custom Template Location
   Choice: 1
   
   Choose an AWS Quick Start application template
       1 - Hello World Example
       2 - Multi-step workflow
       3 - Serverless API
       4 - Scheduled task
       5 - Standalone function
       6 - Data processing
       7 - Hello World Example With Powertools
       8 - Infrastructure event management
       9 - Serverless Connector Hello World Example
       10 - Multi-step workflow with Connectors
       11 - Lambda EFS example
       12 - DynamoDB Example
       13 - Machine Learning
   Template: 4
   ```

**选择自定义模板位置**

1. 当系统提示时，选择**自定义模板位置**。

   ```
   Which template source would you like to use?
       1 - AWS Quick Start Templates
       2 - Custom Template Location
   Choice: 2
   ```

1.  AWS SAM CLI 会提示您提供模板位置。

   ```
   Template location (git, mercurial, http(s), zip, path):
   ```

   为模板 .zip 文件存档提供以下任意位置：
   + **GitHub 存储库** - .zip 文件在 GitHub 存储库中的路径。文件必须位于存储库的根目录中。
   + **Mercurial 存储库** - .zip 文件在 Mercurial 存储库中的路径。文件必须位于存储库的根目录中。
   + **.zip 路径** - .zip 文件的 HTTPS 或本地路径。

1.  AWS SAM CLI 会使用您的自定义模板初始化无服务器应用程序。

### 选择运行时系统
<a name="using-sam-cli-init-new-runtime"></a>

当您选择 *AWS 快速入门模板*时， AWS SAM CLI 会提示您为 Lambda 函数选择运行时系统。 AWS SAM CLI 列出的选项是本身受 Lambda 支持的运行时系统。
+ [运行时](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html#gettingstarted-concepts-runtime)提供在执行环境中运行的语言特定环境。
+ [部署到后 AWS 云，Lambda 服务将在执行环境中调用您的函数。](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtime-environment.html)

您可以将任何其他编程语言与自定义运行时配合使用。若要这样做，您需要手动创建应用程序起始结构。然后，您可以配置自定义模板位置，使用 `sam init` 来快速初始化应用程序。

根据您的选择， AWS SAM CLI 会为 Lambda 函数代码和依赖项创建起始目录。

如果 Lambda 对于运行时支持多个依赖项管理器，则系统会提示您选择首选的依赖项管理器。

### 选择包类型
<a name="using-sam-cli-init-new-package"></a>

当您选择 *AWS 快速入门模板*和*运行时*时， AWS SAM CLI 会提示您选择*包类型*。包类型决定了如何部署 Lambda 函数以与 Lambda 服务配合使用。受支持的两种包类型是：

1. **容器印象** – 包括基本操作系统、运行时系统、Lambda 扩展、应用程序代码及其依赖项。

1. **.zip 文件归档** – 包括您的应用程序代码及其依赖项。

要了解有关部署包类型的更多信息，请参阅*《AWS Lambda 开发人员指南》*中的 [Lambda 部署包](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html)。

以下示例显示了将 Lambda 函数打包为容器映像的应用程序的目录结构。 AWS SAMCLI下载图像并在函数的目录`Dockerfile`中创建一个来指定图像。

```
sam-app
├── README.md
├── __init__.py
├── events
│   └── event.json
├── hello_world
│   ├── Dockerfile
│   ├── __init__.py
│   ├── app.py
│   └── requirements.txt
├── samconfig.toml
├── template.yaml
└── tests
    ├── __init__.py
    └── unit
        ├── __init__.py
        └── test_handler.py
```

以下示例显示了将函数打包为 .zip 文件存档的应用程序的目录结构。

```
sam-app
├── README.md
├── __init__.py
├── events
│   └── event.json
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── requirements.txt
├── samconfig.toml
├── template.yaml
└── tests
    ├── __init__.py
    ├── integration
    │   ├── __init__.py
    │   └── test_api_gateway.py
    ├── requirements.txt
    └── unit
        ├── __init__.py
        └── test_handler.py
```

### 配置 AWS X-Ray 跟踪
<a name="using-sam-cli-init-new-tracing"></a>

您可以选择激活跟 AWS X-Ray 踪。要了解更多信息，请参阅[什么是 AWS X-Ray？](https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html) 在《*AWS X-Ray 开发人员指南》*中。

如果您激活，则 AWS SAMCLI会配置您的 AWS SAM 模板。以下是示例：

```
Globals:
  Function:
    ...
    Tracing: Active
  Api:
    TracingEnabled: True
```

### 使用 Amazon CloudWatch 应用程序见解配置监控
<a name="using-sam-cli-init-new-insights"></a>

您可以选择使用 Amazon App CloudWatch lication Insights 激活监控。要了解更多信息，请参阅《[亚马逊* CloudWatch 用户指南》中的 “亚马逊 CloudWatch *应用程序见解](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html)”。

如果您激活，则 AWS SAMCLI会配置您的 AWS SAM 模板。以下是示例：

```
Resources:
  ApplicationResourceGroup:
    Type: AWS::ResourceGroups::Group
    Properties:
      Name:
        Fn::Join:
        - ''
        - - ApplicationInsights-SAM-
          - Ref: AWS::StackName
      ResourceQuery:
        Type: CLOUDFORMATION_STACK_1_0
  ApplicationInsightsMonitoring:
    Type: AWS::ApplicationInsights::Application
    Properties:
      ResourceGroupName:
        Fn::Join:
        - ''
        - - ApplicationInsights-SAM-
          - Ref: AWS::StackName
      AutoConfigurationEnabled: 'true'
    DependsOn: ApplicationResourceGroup
```

### 命名您的应用程序
<a name="using-sam-cli-init-new-name"></a>

提供应用程序的名称。 AWS SAM CLI 会使用此名称为应用程序创建顶级文件夹。

## sam init 的选项
<a name="using-sam-cli-init-options"></a>

以下是可与 `sam init` 命令配合使用的一些主要选项。有关全部选项的列表，请参阅 [sam init](sam-cli-command-reference-sam-init.md)。

### 使用自定义模板位置初始化应用程序
<a name="using-sam-cli-init-options-location"></a>

使用 `--location` 选项并提供受支持的自定义模板位置。以下是示例：

```
$ sam init --location https://github.com/aws-samples/sessions-with-aws-sam/raw/master/starter-templates/web-app.zip
```

### 在不使用交互式流程的情况下初始化应用程序
<a name="using-sam-cli-init-options-no-interactive"></a>

使用 `--no-interactive` 选项并在命令行中提供您的配置选择，以跳过交互式流程。以下是示例：

```
$ sam init --no-interactive --runtime go1.x --name go-demo --dependency-manager mod --app-template hello-world
```

## 问题排查
<a name="using-sam-cli-init-troubleshooting"></a>

要排除故障 AWS SAMCLI，请参阅[AWS SAM CLI 故障排除](sam-cli-troubleshooting.md)。

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

### 使用 Hello World AWS 入门模板初始化新的无服务器应用程序
<a name="using-sam-cli-init-examples-helloworld"></a>

有关此示例的更多信息，请参阅*教程：部署 Hello World 应用程序*中的[第 1 步：初始化示例 Hello World 应用程序](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-init)。

### 使用自定义模板位置初始化新的无服务器应用程序
<a name="using-sam-cli-init-examples-custom"></a>

以下几个示例说明了如何为自定义模板提供 GitHub 位置：

```
$ sam init --location gh:aws-samples/cookiecutter-aws-sam-python
$ sam init --location git+sh://git@github.com/aws-samples/cookiecutter-aws-sam-python.git
$ sam init --location hg+ssh://hg@bitbucket.org/repo/template-name
```

以下是本地文件路径的示例：

```
$ sam init --location /path/to/template.zip
```

以下是 HTTPS 可访问路径的示例：

```
$ sam init --location https://github.com/aws-samples/sessions-with-aws-sam/raw/master/starter-templates/web-app.zip
```

## 了解详情
<a name="using-sam-cli-init-learn"></a>

要了解有关使用 `sam init` 命令的更多信息，请参阅以下内容：
+ **[学习 AWS SAM：sam init](https://www.youtube.com/watch?v=9m3R-leD5Xo)** — Serverless Land “学习 AWS SAM” 系列开启。YouTube
+ **[构建可与 AWS SAM CLI 配合使用的无服务器应用程序（使用 SAM S2E7 的会话）](https://www.youtube.com/watch?v=k9IRdgze9fQ)** - YouTube 上的“使用 AWS SAM 的会话”系列。

## 后续步骤
<a name="w2aac18c11c39"></a>

既然您已经创建了 AWS SAM 项目，就可以开始创作应用程序了。有关执行此操作所需完成的任务的详细说明，请参阅[使用以下方式定义您的基础架构 AWS SAM](serverless-authoring.md)。

# 使用以下方式定义您的基础架构 AWS SAM
<a name="serverless-authoring"></a>

既然您已经创建了项目，就可以用定义应用程序基础架构了 AWS SAM。通过配置 AWS SAM 模板来定义应用程序的资源和属性（即 AWS SAM 项目中的`template.yaml`文件）来实现此目的。

本节中的主题提供了有关在 AWS SAM 模板（您的`template.yaml`文件）中定义基础架构的内容。它还包含有关为特定用例定义资源的主题，例如使用 Lambda 层、使用嵌套应用程序、控制 API Gat APIs eway 的访问权限、使用 Ste AWS p Functions 编排资源、对应用程序进行代码签名以及验证模板。 AWS SAM 

**Topics**
+ [

# 在 AWS SAM 模板中定义应用程序资源
](authoring-define-resources.md)
+ [

# 在 AWS SAM 模板中设置和管理资源访问权限
](sam-permissions.md)
+ [

# 使用您的 AWS SAM 模板控制 API 访问权限
](serverless-controlling-access-to-apis.md)
+ [

# 使用带有 Lambda 层的 Lambda 层来提高效率 AWS SAM
](serverless-sam-cli-layers.md)
+ [

# 使用嵌套应用程序重用代码和资源 AWS SAM
](serverless-sam-template-nested-applications.md)
+ [

# 使用 “ EventBridge 调度器” 管理基于时间的事件 AWS SAM
](using-eventbridge-scheduler.md)
+ [

# 使用编排资源 AWS SAM AWS Step Functions
](serverless-step-functions-in-sam.md)
+ [

# 为您的 AWS SAM 应用程序设置代码签名
](authoring-codesigning.md)
+ [

# 验证 AWS SAM 模板文件
](serverless-sam-cli-using-validate.md)

# 在 AWS SAM 模板中定义应用程序资源
<a name="authoring-define-resources"></a>

您可以在 AWS SAM 模板的`Resources`部分中定义无服务器应用程序使用的 AWS 资源。在定义资源时，您可以确定该资源是什么、它如何与其他资源交互以及如何访问该资源（即资源的权限）。

 AWS SAM 模板的`Resources`部分可以包含 CloudFormation 资源和 AWS SAM 资源的组合。此外，您可以将 AWS SAM的简写语法用于以下资源：


| AWS SAM 简写语法 | 它如何处理相关 AWS 资源 | 
| --- | --- | 
| [AWS::Serverless::Api](sam-resource-api.md) | 创建一组可通过 HTTPS 端点调用的 API Gateway 资源和方法。 | 
| [AWS::Serverless::Application](sam-resource-application.md) | 将来自 [AWS Serverless Application Repository](https://serverlessrepo.aws.amazon.com/applications) 或来自 Amazon S3 存储桶的无服务器应用程序嵌入为嵌套应用程序。 | 
| [AWS::Serverless::Connector](sam-resource-connector.md) | 配置两种资源之间的权限。有关连接器的简介，请参阅[使用 AWS SAM 连接器管理资源权限](managing-permissions-connectors.md)。 | 
| [AWS::Serverless::Function](sam-resource-function.md) | 创建触发该 AWS Lambda 函数的函数、 AWS Identity and Access Management (IAM) 执行角色和事件源映射。 | 
| [AWS::Serverless::GraphQLApi](sam-resource-graphqlapi.md) | 为您的无服务器应用程序创建和配置 AWS AppSync GraphQL API。 | 
| [AWS::Serverless::HttpApi](sam-resource-httpapi.md) | 创建 Amazon API Gateway HTTP API，这使您能够以比 REST 更低的延迟和更低的成本 RESTful APIs 进行创作 APIs。 | 
| [AWS::Serverless::LayerVersion](sam-resource-layerversion.md) | 创建包含 Lambda 函数 LayerVersion 所需的库或运行时代码的 Lambda。 | 
| [AWS::Serverless::SimpleTable](sam-resource-simpletable.md) | 创建具有单个属性主键的 DynamoDB 表。 | 
| [AWS::Serverless::StateMachine](sam-resource-statemachine.md) | 创建 AWS Step Functions 状态机，您可以使用它来编排 AWS Lambda 函数和其他 AWS 资源，以形成复杂而强大的工作流程。 | 

上述资源也列在 [AWS SAM 资源和财产](sam-specification-resources-and-properties.md)中。

有关所有 AWS 资源和属性类型 CloudFormation 及 AWS SAM 支持的参考信息，请参阅*AWS CloudFormation 用户指南*中的[AWS 资源和属性类型参考](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html)。

# 在 AWS SAM 模板中设置和管理资源访问权限
<a name="sam-permissions"></a>

为了使您的 AWS 资源相互交互，必须在您的资源之间配置适当的访问权限和权限。为此，需要配置 AWS Identity and Access Management (IAM) 用户、角色和策略，以安全的方式完成互动。

本节中的主题都与设置对模板中定义的资源的访问相关。本节从一般最佳实践开始。接下来的两个主题回顾了在无服务器应用程序中引用的资源之间设置访问权限和权限的两个选项： AWS SAM 连接器和 AWS SAM 策略模板。最后一个主题详细介绍了如何使用与管理用户相同的机制 CloudFormation 来管理用户访问权限。

要了解更多信息，请参阅*《AWS CloudFormation 用户指南》*中的[使用 AWS Identity and Access Management控制访问](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html)。

 AWS Serverless Application Model (AWS SAM) 提供了两个选项，可简化对无服务器应用程序的访问和权限的管理。

1. AWS SAM 连接器

1. AWS SAM 策略模板

## AWS SAM 连接器
<a name="sam-permissions-intro-connectors"></a>

连接器是在两个资源之间配置权限的一种方式。为此，您可以通过在 AWS SAM 模板中描述它们应如何相互交互来实现。可以使用 `Connectors` 资源属性或 `AWS::Serverless::Connector` 资源类型进行定义。连接器支持在资源组合之间配置`Read`和`Write`访问数据和事件。 AWS 要了解有关 AWS SAM 连接器的更多信息，请参阅[使用 AWS SAM 连接器管理资源权限](managing-permissions-connectors.md)。

## AWS SAM 策略模板
<a name="sam-permissions-intro-policy-templates"></a>

AWS SAM 策略模板是预定义的权限集，您可以将其添加到 AWS SAM 模板中，以管理您的 AWS Lambda 函数、 AWS Step Functions 状态机及其与之交互的资源之间的访问权限和权限。要了解有关 AWS SAM 策略模板的更多信息，请参阅[AWS SAM策略模板](serverless-policy-templates.md)。

## AWS CloudFormation 机制
<a name="sam-permissions-intro-cloudformation"></a>

CloudFormation 机制包括配置 IAM 用户、角色和策略，以管理您的 AWS 资源之间的权限。要了解更多信息，请参阅[使用 CloudFormation 机制管理 AWS SAM 权限](sam-permissions-cloudformation.md)。

## 最佳实践
<a name="sam-permissions-intro-best-practices"></a>

在整个无服务器应用程序中，您可以使用多种方法来配置资源之间的权限。因此，您可以为每个场景选择最佳选项，并在整个应用程序中结合使用多个选项。选择最适合您的选项时，需要考虑以下几点：
+ AWS SAM 连接器和策略模板都减少了促进 AWS 资源之间安全交互所需的 IAM 专业知识。如果受支持，请使用连接器和策略模板。
+ AWS SAM 连接器提供了一种简单直观的简短语法，用于在 AWS SAM 模板中定义权限，并且只需要最少的 IAM 专业知识。当同时支持 AWS SAM 连接器和策略模板时，请使用 AWS SAM 连接器。
+ AWS SAM 连接器可以在支持的 AWS SAM 源资源和目标资源之间配置`Read`和`Write`访问数据和事件。有关受支持的资源的列表，请参阅 [AWS SAM 连接器参考](reference-sam-connector.md)。如果支持，请使用 AWS SAM 连接器。
+ 虽然 AWS SAM 策略模板仅限于您的 Lambda 函数、Step Functions 状态机及其与之交互的 AWS 资源之间的权限，但策略模板确实支持所有 CRUD 操作。如果支持并且有适用于您的场景的 AWS SAM 策略模板，请使用 AWS SAM 策略模板。有关可用策略模板的列表，请参阅 [AWS SAM策略模板](serverless-policy-templates.md)。
+ 对于所有其他场景，或者需要精细度时，请使用 CloudFormation 机制。

# 使用 AWS SAM 连接器管理资源权限
<a name="managing-permissions-connectors"></a>

连接器是一种 AWS Serverless Application Model (AWS SAM) 抽象资源类型，标识为`AWS::Serverless::Connector`，它在您的无服务器应用程序资源之间提供简单且范围明确的权限。

## AWS SAM 连接器的好处
<a name="connector-benefits"></a>

通过在资源之间自动编写适当的访问策略，连接器使您能够编写无服务器应用程序并专注于应用程序架构，而无需在 AWS 授权功能、策略语言和特定于服务的安全设置方面的专业知识。因此，对于可能不熟悉无服务器开发的开发人员或希望提高开发速度的经验丰富的开发人员来说，连接器十分有用。

## 使用 AWS SAM 连接器
<a name="what-are-connectors"></a>

通过将 `Connectors` 资源属性嵌入到**源**资源中来使用它。然后，定义您的**目标**资源并描述数据或事件应如何在这些资源之间流动。 AWS SAM 然后制定必要的访问策略，以促进所需的交互。

以下内容概述了此资源属性的编写方式：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  <source-resource-logical-id>:
    Type: <resource-type>
    ...
    Connectors:
      <connector-name>:
        Properties:
          Destination:
            <properties-that-identify-destination-resource>
          Permissions:
            <permission-types-to-provision>
  ...
```

## 连接器的工作原理
<a name="connectors-work"></a>

**注意**  
本节介绍连接器如何在幕后提供必要的资源。使用连接器时，这种情况会自动发生。

首先，嵌入的 `Connectors` 资源属性转换为 `AWS::Serverless::Connector` 资源类型。其逻辑 ID 会自动创建为*<source-resource-logical-id><embedded-connector-logical-id>*。

例如，这是嵌入式连接器：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Lambda::Function
    Connectors:
      MyConn:
        Properties:
          Destination:
            Id: MyTable
          Permissions:
            - Read
            - Write
  MyTable:
    Type: AWS::DynamoDB::Table
```

这将生成以下 `AWS::Serverless::Connector` 资源：

```
Transform: AWS::Serverless-2016-10-31
Resources:
  ...
  MyFunctionMyConn:
    Type: AWS::Serverless::Connector
    Properties:
      Source:
        Id: MyFunction
      Destination:
        Id: MyTable
      Permissions:
        - Read
        - Write
```

**注意**  
您也可以使用此语法在 AWS SAM 模板中定义连接器。如果源资源定义于与连接器不同的模板上，则建议使用此方法。

接下来，将自动编写该连接必要的访问策略。有关连接器生成的资源的更多信息，请参阅 [CloudFormation 指定时生成的资源 AWS::Serverless::Connector](sam-specification-generated-resources-connector.md)。

## 连接器示例
<a name="what-are-connectors-example"></a>

以下示例说明如何使用连接器将数据从 AWS Lambda 函数写入 Amazon DynamoDB 表。

![\[Lambda 函数使用 AWS SAM 连接器将数据写入 DynamoDB 表。\]](http://docs.aws.amazon.com/zh_cn/serverless-application-model/latest/developerguide/images/managing-connectors-example.png)


```
Transform: AWS::Serverless-2016-10-31
Resources:
  MyTable:
    Type: AWS::Serverless::SimpleTable
  MyFunction:
    Type: AWS::Serverless::Function
    Connectors:
      MyConn:
        Properties:
          Destination:
            Id: MyTable
          Permissions:
            - Write
    Properties:
      Runtime: nodejs16.x
      Handler: index.handler
      InlineCode: |
        const AWS = require("aws-sdk");
        const docClient = new AWS.DynamoDB.DocumentClient();
        exports.handler = async (event, context) => {
          await docClient.put({
            TableName: process.env.TABLE_NAME,
            Item: {
              id: context.awsRequestId,
              event: JSON.stringify(event) 
            }
          }).promise();
        }
      Environment:
        Variables:
          TABLE_NAME: !Ref MyTable
```

`Connectors` 资源属性嵌入在 Lambda 函数源资源中。使用 `Id` 属性将 DynamoDB 表定义为目标资源。连接器将在这两个资源之间提供 `Write` 权限。

当您将 AWS SAM 模板部署到时 CloudFormation， AWS SAM 将自动编写此连接正常运行所需的必要访问策略。

## 源资源和目标资源之间支持的连接
<a name="supported-connector-resources"></a>

连接器支持源和目标资源连接的精选组合之间的 `Read` 和 `Write` 数据和事件权限类型。例如，连接器支持 `AWS::ApiGateway::RestApi` 源资源和 `AWS::Lambda::Function` 目标资源之间的 `Write` 连接。

可以使用支持的属性的组合来定义源资源和目标资源。属性要求将取决于您正在建立的连接以及资源定义的位置。

**注意**  
连接器可以在支持的无服务器和非无服务器资源类型之间配置权限。

有关支持的资源连接及其属性要求的列表，请参阅 [连接器支持的源资源和目的地资源类型](reference-sam-connector.md#supported-connector-resource-types)。

# 在中定义读取和写入权限 AWS SAM
<a name="connector-usage-define"></a>

在`Read`和中 AWS SAM，可以在单个连接器中配置`Write`权限：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Lambda::Function
    Connectors:
      MyTableConn:
        Properties:
          Destination:
            Id: MyTable
          Permissions:
            - Read
            - Write
  MyTable:
    Type: AWS::DynamoDB::Table
```

有关使用连接器的更多信息，请参阅 [AWS SAM 连接器参考](reference-sam-connector.md)。

# 使用中其他支持的属性来定义资源 AWS SAM
<a name="connector-usage-other-properties"></a>

对于源资源和目标资源，如果在同一个模板中定义，则使用 `Id` 属性。或者，可以添加 `Qualifier` 以缩小您定义的资源范围。当资源不在同一个模板中时，请使用受支持属性的组合。
+ 有关源资源和目标资源支持的属性组合列表，请参阅 [连接器支持的源资源和目的地资源类型](reference-sam-connector.md#supported-connector-resource-types)。
+ 有关可用于连接器的属性的说明，请参见 [AWS::Serverless::Connector](sam-resource-connector.md)。

在定义具有 `Id` 之外属性的源资源时，请使用 `SourceReference` 属性。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  <source-resource-logical-id>:
    Type: <resource-type>
    ...
    Connectors:
      <connector-name>:
        Properties:
          SourceReference:
            Qualifier: <optional-qualifier>
            <other-supported-properties>
          Destination:
            <properties-that-identify-destination-resource>
          Permissions:
            <permission-types-to-provision>
```

以下示例使用 `Qualifier` 缩小 Amazon API Gateway 资源的范围：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Connectors:
      ApiToLambdaConn:
        Properties:
          SourceReference:
            Qualifier: Prod/GET/foobar
          Destination:
            Id: MyFunction
          Permissions:
            - Write           
  ...
```

以下示例使用支持的 `Arn` 和 `Type` 组合定义来自另一个模板的目标资源：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Connectors:
      TableConn:
        Properties:
          Destination:
            Type: AWS::DynamoDB::Table
            Arn: !GetAtt MyTable.Arn
  ...
```

有关使用连接器的更多信息，请参阅 [AWS SAM 连接器参考](reference-sam-connector.md)。

# 从单一来源创建多个连接器 AWS SAM
<a name="connector-usage-single-source"></a>

在一个源资源中，您可以定义多个连接器，且每个都有不同的目标资源。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Connectors:
      BucketConn:
        Properties:
          Destination:
            Id: amzn-s3-demo-bucket
          Permissions:
            - Read
            - Write
      SQSConn:
        Properties:
          Destination:
            Id: MyQueue
          Permissions:
            - Read
            - Write
      TableConn:
        Properties:
          Destination:
            Id: MyTable
          Permissions:
            - Read
            - Write
      TableConnWithTableArn:
        Properties:
          Destination:
            Type: AWS::DynamoDB::Table
            Arn: !GetAtt MyTable.Arn
          Permissions:
            - Read
            - Write
...
```

有关使用连接器的更多信息，请参阅 [AWS SAM 连接器参考](reference-sam-connector.md)。

# 在中创建多目的地连接器 AWS SAM
<a name="connector-usage-multi-destination"></a>

在一个源资源中，您可以定义具有多个目标资源的单个连接器。以下是 Lambda 函数源资源的示例，其连接到 Amazon Simple Storage Service（Amazon S3）存储桶和 DynamoDB 表：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Connectors:
      WriteAccessConn:
        Properties:
          Destination:
            - Id: OutputBucket
            - Id: CredentialTable
          Permissions:
            - Write
  ...
  OutputBucket:
    Type: AWS::S3::Bucket
  CredentialTable:
    Type: AWS::DynamoDB::Table
```

有关使用连接器的更多信息，请参阅 [AWS SAM 连接器参考](reference-sam-connector.md)。

# 使用连接器定义资源属性 AWS SAM
<a name="connector-usage-resource-attributes"></a>

可以为资源定义资源属性，以指定其他行为和关系。要了解有关资源属性的更多信息，请参阅*《AWS CloudFormation 用户指南》*中的[资源属性参考](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-product-attribute-reference.html)。

您可以将资源属性添加到嵌入式连接器，方法是在与连接器属性相同的级别上对其进行定义。在部署时转换 AWS SAM 模板时，属性将传递给生成的资源。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Connectors:
      MyConn:
        DeletionPolicy: Retain
        DependsOn: AnotherFunction
        Properties:
          ...
```

有关使用连接器的更多信息，请参阅 [AWS SAM 连接器参考](reference-sam-connector.md)。

## 了解详情
<a name="connector-learn-more"></a>

有关使用 AWS SAM 连接器的更多信息，请参阅以下主题：
+ [AWS::Serverless::Connector](sam-resource-connector.md)
+ [在中定义读取和写入权限 AWS SAM](connector-usage-define.md)
+ [使用中其他支持的属性来定义资源 AWS SAM](connector-usage-other-properties.md)
+ [从单一来源创建多个连接器 AWS SAM](connector-usage-single-source.md)
+ [在中创建多目的地连接器 AWS SAM](connector-usage-multi-destination.md)
+ [在中定义读取和写入权限 AWS SAM](connector-usage-define.md)
+ [使用连接器定义资源属性 AWS SAM](connector-usage-resource-attributes.md)

## 提供反馈
<a name="connector-feedback"></a>

要提供有关连接器的反馈，[请在*serverless-application-model AWS GitHub存储库*中提交新问题](https://github.com/aws/serverless-application-model/issues/new?assignees=&labels=area%2Fconnectors,stage%2Fneeds-triage&template=other.md&title=%28Feature%20Request%29)。

# AWS SAM策略模板
<a name="serverless-policy-templates"></a>

 AWS Serverless Application Model (AWS SAM) 允许您从策略模板列表中进行选择，将 Lambda 函数和 AWS Step Functions 状态机的权限范围限定为应用程序使用的资源。

AWS SAM 中使用策略模板 AWS Serverless Application Repository 的应用程序不需要任何特殊的客户确认即可从中部署应用程序。 AWS Serverless Application Repository

如果要请求添加新的策略模板，请执行以下操作：

1. 针对项目分支中的 policy\$1templates.json 源文件提交拉取请求。`develop` AWS SAM GitHub 你可以在网站上的 p [olicy\$1templates.](https://github.com/aws/serverless-application-model/blob/develop/samtranslator/policy_templates_data/policy_templates.json) json 中找到源文件。 GitHub 

1. 在 AWS SAM GitHub 项目中提交一个问题，其中包含您的拉取请求的原因和请求链接。使用此链接提交新问题：[AWS Serverless Application Model：问题](https://github.com/aws/serverless-application-model/issues/new)。

## 语法
<a name="serverless-policy-template-syntax"></a>

对于您在模板文件中指定的每个策略 AWS SAM 模板，必须始终指定一个包含策略模板占位符值的对象。如果策略模板不需要任何占位符值，则必须指定一个空对象。

### YAML
<a name="serverless-policy-template-syntax.yaml"></a>

```
MyFunction:
  Type: AWS::Serverless::Function
  Properties:
    Policies:
      - PolicyTemplateName1:        # Policy template with placeholder value
          Key1: Value1
      - PolicyTemplateName2: {}     # Policy template with no placeholder value
```

**注意**  
若您已设置常规 IAM 策略或通过 Lambda 管理策略，则无需使用空对象即可设置策略模板。

## 示例
<a name="serverless-policy-template-examples"></a>

### 示例 1：具有占位符值的策略模板
<a name="policy-template-example-1"></a>

以下示例显示 [SQSPollerPolicy](serverless-policy-template-list.md#sqs-poller-policy) 策略模板期待 `QueueName` 作为资源。 AWS SAM 模板检索 “`MyQueue`” Amazon SQS 队列的名称，您可以在同一个应用程序中创建该队列，也可以将其作为应用程序的参数进行请求。

```
 1. MyFunction:
 2.   Type: 'AWS::Serverless::Function'
 3.   Properties:
 4.     CodeUri: ${codeuri}
 5.     Handler: hello.handler
 6.     Runtime: python2.7
 7.     Policies:
 8.       - SQSPollerPolicy:
 9.           QueueName:
10.             !GetAtt MyQueue.QueueName
```

### 示例 2：不具有占位符值的策略模板
<a name="policy-template-example-2"></a>

以下示例包含 [CloudWatchPutMetricPolicy](serverless-policy-template-list.md#cloudwatch-put-metric-policy) 策略模板，该模板没有占位符值。

**注意**  
即使没有占位符值，也必须指定一个空对象，否则会导致错误。

```
1. MyFunction:
2.   Type: 'AWS::Serverless::Function'
3.   Properties:
4.     CodeUri: ${codeuri}
5.     Handler: hello.handler
6.     Runtime: python2.7
7.     Policies:
8.       - CloudWatchPutMetricPolicy: {}
```

### 示例 3：包含占位符值和常规 IAM 策略的策略模板
<a name="policy-template-example-3"></a>

以下示例包含 Amazon A SQSFull cess 策略和[DynamoDBCrudPolicy](serverless-policy-template-list.md#dynamo-db-crud-policy)策略模板。Amazon A SQSFull ccess AWS SAM 策略是一项 IAM 策略而不是策略，因此您不必指定空对象，因为该策略将直接传递给 CloudFormation。

```
 1. MyFunction:
 2.   Type: 'AWS::Serverless::Function'
 3.   Properties:
 4.     CodeUri: ${codeuri}
 5.     Handler: hello.handler
 6.     Runtime: python2.7
 7.     Policies:
 8.       - AmazonSQSFullAccess // IAM policy could be set without passing an empty object
 9.       - DynamoDBCrudPolicy: // SAM specific policy, has a defined structure
10.            TableName: 
11.              !Ref SampleTable
```

## 策略模板表
<a name="serverless-policy-template-table"></a>

下表列出了可用的策略模板。


****  

| 策略模板 | 说明 | 
| --- | --- | 
| [AcmGetCertificatePolicy](serverless-policy-template-list.md#acm-get-certificate-policy) | 授予读取证书的权限 AWS Certificate Manager。 | 
| [AMIDescribePolicy](serverless-policy-template-list.md#ami-describe-policy) | 授予描述 Amazon 机器映像的权限 (AMIs)。 | 
| [AthenaQueryPolicy](serverless-policy-template-list.md#athena-query-policy) | 授予执行 Athena 查询的权限。 | 
| [AWSSecretsManagerGetSecretValuePolicy](serverless-policy-template-list.md#secrets-manager-get-secret-value-policy) | 授予获取指定 AWS Secrets Manager 密钥的密钥值的权限。 | 
| [AWSSecretsManagerRotationPolicy](serverless-policy-template-list.md#secrets-manager-rotation-policy) | 授予在 AWS Secrets Manager中轮换密钥的权限。 | 
| [CloudFormationDescribeStacksPolicy](serverless-policy-template-list.md#cloud-formation-describe-stacks-policy) | 授予描述 CloudFormation 堆栈的权限。 | 
| [CloudWatchDashboardPolicy](serverless-policy-template-list.md#cloudwatch-dashboard-policy) | 授予在 CloudWatch 仪表板上放置要操作的指标的权限。 | 
| [CloudWatchDescribeAlarmHistoryPolicy](serverless-policy-template-list.md#cloudwatch-describe-alarm-history-policy) | 授予描述 CloudWatch 警报历史记录的权限。 | 
| [CloudWatchPutMetricPolicy](serverless-policy-template-list.md#cloudwatch-put-metric-policy) | 授予向发送指标的权限 CloudWatch。 | 
| [CodeCommitCrudPolicy](serverless-policy-template-list.md#codecommit-crud-policy) | 为特定 CodeCommit存储库中的create/read/update/delete对象授予权限。 | 
| [CodeCommitReadPolicy](serverless-policy-template-list.md#codecommit-read-policy) | 授予读取特定 CodeCommit 存储库中对象的权限。 | 
| [CodePipelineLambdaExecutionPolicy](serverless-policy-template-list.md#code-pipeline-lambda-execution-policy) | 允许调用的 Lambda 函数报告任务状态。 CodePipeline  | 
| [CodePipelineReadOnlyPolicy](serverless-policy-template-list.md#code-pipeline-readonly-policy) | 授予读取权限以获取有关 CodePipeline 管道的详细信息。 | 
| [ComprehendBasicAccessPolicy](serverless-policy-template-list.md#comprehend-basic-access-policy) | 授予检测实体、关键短语、语言和情绪的权限。 | 
| [CostExplorerReadOnlyPolicy](serverless-policy-template-list.md#cost-explorer-readonly-policy) | 向只读的 Cost Explorer 授予账单历史记录 APIs 的只读权限。 | 
| [DynamoDBBackupFullAccessPolicy](serverless-policy-template-list.md#ddb-back-full-policy) | 授予对表进行 DynamoDB 按需备份的读和写权限。 | 
| [DynamoDBCrudPolicy](serverless-policy-template-list.md#dynamo-db-crud-policy) | 授予对 Amazon DynamoDB 表的创建、读取、更新和删除权限。 | 
| [DynamoDBReadPolicy](serverless-policy-template-list.md#dynamo-db-read-policy) | 授予对 DynamoDB 表的只读权限。 | 
| [DynamoDBReconfigurePolicy](serverless-policy-template-list.md#dynamo-db-reconfigure-policy) | 授予重新配置 DynamoDB 表的权限。 | 
| [DynamoDBRestoreFromBackupPolicy](serverless-policy-template-list.md#ddb-restore-from-backup-policy) | 授予从备份还原 DynamoDB 表的权限。 | 
| [DynamoDBStreamReadPolicy](serverless-policy-template-list.md#dynamo-db-stream-read-policy) | 授予描述和读取 DynamoDB 流和记录的权限。 | 
| [DynamoDBWritePolicy](serverless-policy-template-list.md#dynamo-db-write-policy) | 授予对 DynamoDB 表的只写权限。 | 
| [EC2CopyImagePolicy](serverless-policy-template-list.md#ec2-copy-image-policy) | 授予复制 Amazon EC2 映像的权限。 | 
| [EC2DescribePolicy](serverless-policy-template-list.md#ec2-describe-policy) | 授予描述 Amazon Elastic Compute Cloud (Amazon EC2) 实例的权限。 | 
| [EcsRunTaskPolicy](serverless-policy-template-list.md#ecs-run-task-policy) | 授予根据任务定义启动新任务的权限。 | 
| [EFSWriteAccessPolicy](serverless-policy-template-list.md#efs-write-access-policy) | 授予挂载具有写入访问权限的 Amazon EFS 文件系统的权限。 | 
| [EKSDescribePolicy](serverless-policy-template-list.md#eks-describe-policy) | 授予描述或列出 Amazon EKS 集群的权限。 | 
| [ElasticMapReduceAddJobFlowStepsPolicy](serverless-policy-template-list.md#elastic-map-reduce-add-job-flows-policy) | 授予将新步骤添加到运行的集群中的权限。 | 
| [ElasticMapReduceCancelStepsPolicy](serverless-policy-template-list.md#elastic-map-reduce-cancel-steps-policy) | 授予取消正在运行中的集群中的一个或多个待处理步骤的权限。 | 
| [ElasticMapReduceModifyInstanceFleetPolicy](serverless-policy-template-list.md#elastic-map-reduce-modify-instance-fleet-policy) | 授予列出集群内实例集的详细信息和修改这些实例集的容量的权限。 | 
| [ElasticMapReduceModifyInstanceGroupsPolicy](serverless-policy-template-list.md#elastic-map-reduce-modify-instance-groups-policy) | 授予列出集群内实例组的详细信息和修改这些实例组的设置的权限。 | 
| [ElasticMapReduceSetTerminationProtectionPolicy](serverless-policy-template-list.md#elastic-map-reduce-set-termination-protection-policy) | 授予为集群设置终止保护的权限。 | 
| [ElasticMapReduceTerminateJobFlowsPolicy](serverless-policy-template-list.md#elastic-map-reduce-terminate-job-flows-policy) | 授予关闭集群的权限。 | 
| [ElasticsearchHttpPostPolicy](serverless-policy-template-list.md#elastic-search-http-post-policy) | 向 Amazon OpenSearch 服务授予 POST 权限。 | 
| [EventBridgePutEventsPolicy](serverless-policy-template-list.md#eventbridge-put-events-policy) | 授予向发送事件的权限 EventBridge。 | 
| [FilterLogEventsPolicy](serverless-policy-template-list.md#filter-log-events-policy) | 授予筛选指定 CloudWatch 日志组中的日志事件的权限。 | 
| [FirehoseCrudPolicy](serverless-policy-template-list.md#firehose-crud-policy) | 授予创建、写入、更新和删除 Firehose 传输流的权限。 | 
| [FirehoseWritePolicy](serverless-policy-template-list.md#firehose-write-policy) | 授予写入 Firehose 传输流的权限。 | 
| [KinesisCrudPolicy](serverless-policy-template-list.md#kinesis-crud-policy) | 授予创建、发布和删除 Amazon Kinesis 流的权限。 | 
| [KinesisStreamReadPolicy](serverless-policy-template-list.md#kinesis-stream-read-policy) | 授予列出和读取 Amazon Kinesis 流的权限。 | 
| [KMSDecryptPolicy](serverless-policy-template-list.md#kms-decrypt-policy) | 授予使用 AWS Key Management Service (AWS KMS) 密钥解密的权限。 | 
| [KMSEncryptPolicy](serverless-policy-template-list.md#kms-encrypt-policy) | 允许使用 AWS Key Management Service (AWS KMS) 密钥进行加密。 | 
| [LambdaInvokePolicy](serverless-policy-template-list.md#lambda-invoke-policy) | 授予调用 AWS Lambda 函数、别名或版本的权限。 | 
| [MobileAnalyticsWriteOnlyAccessPolicy](serverless-policy-template-list.md#mobile-analytics-write-only-access-policy) | 授予对所有应用程序资源放置事件数据的只写权限。 | 
| [OrganizationsListAccountsPolicy](serverless-policy-template-list.md#organizations-list-accounts-policy) | 授予列出子女账户名称的只读权限，以及 IDs. | 
| [PinpointEndpointAccessPolicy](serverless-policy-template-list.md#pinpoint-endpoint-access-policy) | 授予为 Amazon Pinpoint 应用程序获取并更新端点的权限。 | 
| [PollyFullAccessPolicy](serverless-policy-template-list.md#polly-full-access-policy) | 授予对 Amazon Polly 词典资源的完全访问权限。 | 
| [RekognitionDetectOnlyPolicy](serverless-policy-template-list.md#rekognition-detect-only-policy) | 授予检测人脸、标签和文本的权限。 | 
| [RekognitionFacesManagementPolicy](serverless-policy-template-list.md#rekognition-face-management-policy) | 授予在 Amazon Rekognition 集合中添加、删除和搜索人脸的权限。 | 
| [RekognitionFacesPolicy](serverless-policy-template-list.md#rekognition-faces-policy) | 授予比较并检测面部和标签的权限。 | 
| [RekognitionLabelsPolicy](serverless-policy-template-list.md#rekognition-labels-policy) | 授予检测对象和审核标签的权限。 | 
| [RekognitionNoDataAccessPolicy](serverless-policy-template-list.md#rekognition-no-data-access-policy) | 授予比较并检测面部和标签的权限。 | 
| [RekognitionReadPolicy](serverless-policy-template-list.md#rekognition-read-policy) | 授予列出和搜索人脸的权限。 | 
| [RekognitionWriteOnlyAccessPolicy](serverless-policy-template-list.md#rekognition-write-only-access-policy) | 授予创建集合和为人脸编制索引的权限。 | 
| [Route53ChangeResourceRecordSetsPolicy](serverless-policy-template-list.md#route53-change-resource-record-sets-policy) | 授予更改 Route 53 中的资源记录集的权限。 | 
| [S3CrudPolicy](serverless-policy-template-list.md#s3-crud-policy) | 授予创建、读取、更新和删除权限，以便对 Amazon S3 存储桶中的对象执行操作。 | 
| [S3FullAccessPolicy](serverless-policy-template-list.md#s3-full-access-policy) | 授予完全访问权限，以便对 Amazon S3 存储桶中的对象执行操作。 | 
| [S3ReadPolicy](serverless-policy-template-list.md#s3-read-policy) | 授予读取 Amazon Simple Storage Service (Amazon S3) 存储桶中的对象的只读权限。 | 
| [S3WritePolicy](serverless-policy-template-list.md#s3-write-policy) | 授予将对象写入到 Amazon S3 存储桶的写入权限。 | 
| [SageMakerCreateEndpointConfigPolicy](serverless-policy-template-list.md#sagemaker-create-endpoint-config-policy) | 授予在 SageMaker AI 中创建终端节点配置的权限。 | 
| [SageMakerCreateEndpointPolicy](serverless-policy-template-list.md#sagemaker-create-endpoint-policy) | 授予在 SageMaker AI 中创建终端节点的权限。 | 
| [ServerlessRepoReadWriteAccessPolicy](serverless-policy-template-list.md#serverlessrepo-read-write-access-policy) | 授予在 AWS Serverless Application Repository 服务中创建和列出应用程序的权限。 | 
| [SESBulkTemplatedCrudPolicy](serverless-policy-template-list.md#ses-bulk-templated-crud-policy) | 授予发送电子邮件、模板化电子邮件和模板化批量电子邮件以及验证身份的权限。 | 
| [SESBulkTemplatedCrudPolicy\$1v2](serverless-policy-template-list.md#ses-bulk-templated-crud-policy-v2) | 授予发送 Amazon SES 电子邮件、模板化电子邮件和模板化批量电子邮件以及验证身份的权限。 | 
| [SESCrudPolicy](serverless-policy-template-list.md#ses-crud-policy) | 授予发送电子邮件和验证身份的权限。 | 
| [SESEmailTemplateCrudPolicy](serverless-policy-template-list.md#ses-email-template-crud-policy) | 授予创建、获取、列出、更新和删除 Amazon SES 电子邮件模板的权限。 | 
| [SESSendBouncePolicy](serverless-policy-template-list.md#ses-send-bounce-policy) |  SendBounce 授予亚马逊简单电子邮件服务 (Amazon SES) Service 身份的权限。 | 
| [SNSCrudPolicy](serverless-policy-template-list.md#sns-crud-policy) | 授予创建、发布和订阅 Amazon SNS 主题的权限。 | 
| [SNSPublishMessagePolicy](serverless-policy-template-list.md#sqs-publish-message-policy) | 授予将消息发布到 Amazon Simple Notiﬁcation Service (Amazon SNS)主题的权限。 | 
| [SQSPollerPolicy](serverless-policy-template-list.md#sqs-poller-policy) | 授予轮询 Amazon Simple Queue Service (Amazon SQS) 队列的权限。 | 
| [SQSSendMessagePolicy](serverless-policy-template-list.md#sqs-send-message-policy) | 授予向 Amazon SQS 队列发送消息的权限。 | 
| [SSMParameterReadPolicy](serverless-policy-template-list.md#ssm-parameter-read-policy) | 授予访问来自 Amazon EC2 Systems Manager (SSM) Parameter Store 的参数的权限，以便在此账户中加载密钥。在参数名称不包含斜杠前缀时使用。 | 
| [SSMParameterWithSlashPrefixReadPolicy](serverless-policy-template-list.md#ssm-parameter-slash-read-policy) | 授予访问来自 Amazon EC2 Systems Manager (SSM) Parameter Store 的参数的权限，以便在此账户中加载密钥。在参数名称包含斜杠前缀时使用。 | 
| [StepFunctionsExecutionPolicy](serverless-policy-template-list.md#stepfunctions-execution-policy) | 授予开始执行 Step Functions 状态机的权限。 | 
| [TextractDetectAnalyzePolicy](serverless-policy-template-list.md#textract-detect-analyze-policy) | 授予使用 Amazon Textract 检测和分析文档的权限。 | 
| [TextractGetResultPolicy](serverless-policy-template-list.md#textract-get-result-policy) | 授予从 Amazon Textract 中获取检测到和分析过的文档的权限。 | 
| [TextractPolicy](serverless-policy-template-list.md#textract-policy) | 授予对 Amazon Textract 的完全访问权限。 | 
| [VPCAccessPolicy](serverless-policy-template-list.md#vpc-access-policy) | 授予访问权限以创建、删除、描述和分离弹性网络接口。 | 

## 问题排查
<a name="serverless-policy-template-troubleshooting"></a>

### SAM CLI 错误：“必须为策略模板'< policy-template-name >'指定有效的参数值”
<a name="serverless-policy-template-troubleshooting-"></a>

执行 `sam build` 时，您会看到以下错误：

```
"Must specify valid parameter values for policy template '<policy-template-name>'"
```

这意味着您在声明没有任何占位符值的策略模板时没有传递空对象。

要解决此问题，请如以下示例所示声明策略：[CloudWatchPutMetricPolicy](serverless-policy-template-list.md#cloudwatch-put-metric-policy)。

```
1. MyFunction:
2.   Policies:
3.     - CloudWatchPutMetricPolicy: {}
```

# AWS SAM 策略模板列表
<a name="serverless-policy-template-list"></a>

以下是可用的策略模板以及应用于每个模板的权限。 AWS Serverless Application Model (AWS SAM) 会自动使用相应信息填充占位符项目（例如 AWS 区域和账户 ID）。

**Topics**
+ [

## AcmGetCertificatePolicy
](#acm-get-certificate-policy)
+ [

## AMIDescribePolicy
](#ami-describe-policy)
+ [

## AthenaQueryPolicy
](#athena-query-policy)
+ [

## AWSSecretsManagerGetSecretValuePolicy
](#secrets-manager-get-secret-value-policy)
+ [

## AWSSecretsManagerRotationPolicy
](#secrets-manager-rotation-policy)
+ [

## CloudFormationDescribeStacksPolicy
](#cloud-formation-describe-stacks-policy)
+ [

## CloudWatchDashboardPolicy
](#cloudwatch-dashboard-policy)
+ [

## CloudWatchDescribeAlarmHistoryPolicy
](#cloudwatch-describe-alarm-history-policy)
+ [

## CloudWatchPutMetricPolicy
](#cloudwatch-put-metric-policy)
+ [

## CodePipelineLambdaExecutionPolicy
](#code-pipeline-lambda-execution-policy)
+ [

## CodePipelineReadOnlyPolicy
](#code-pipeline-readonly-policy)
+ [

## CodeCommitCrudPolicy
](#codecommit-crud-policy)
+ [

## CodeCommitReadPolicy
](#codecommit-read-policy)
+ [

## ComprehendBasicAccessPolicy
](#comprehend-basic-access-policy)
+ [

## CostExplorerReadOnlyPolicy
](#cost-explorer-readonly-policy)
+ [

## DynamoDBBackupFullAccessPolicy
](#ddb-back-full-policy)
+ [

## DynamoDBCrudPolicy
](#dynamo-db-crud-policy)
+ [

## DynamoDBReadPolicy
](#dynamo-db-read-policy)
+ [

## DynamoDBReconfigurePolicy
](#dynamo-db-reconfigure-policy)
+ [

## DynamoDBRestoreFromBackupPolicy
](#ddb-restore-from-backup-policy)
+ [

## DynamoDBStreamReadPolicy
](#dynamo-db-stream-read-policy)
+ [

## DynamoDBWritePolicy
](#dynamo-db-write-policy)
+ [

## EC2CopyImagePolicy
](#ec2-copy-image-policy)
+ [

## EC2DescribePolicy
](#ec2-describe-policy)
+ [

## EcsRunTaskPolicy
](#ecs-run-task-policy)
+ [

## EFSWriteAccessPolicy
](#efs-write-access-policy)
+ [

## EKSDescribePolicy
](#eks-describe-policy)
+ [

## ElasticMapReduceAddJobFlowStepsPolicy
](#elastic-map-reduce-add-job-flows-policy)
+ [

## ElasticMapReduceCancelStepsPolicy
](#elastic-map-reduce-cancel-steps-policy)
+ [

## ElasticMapReduceModifyInstanceFleetPolicy
](#elastic-map-reduce-modify-instance-fleet-policy)
+ [

## ElasticMapReduceModifyInstanceGroupsPolicy
](#elastic-map-reduce-modify-instance-groups-policy)
+ [

## ElasticMapReduceSetTerminationProtectionPolicy
](#elastic-map-reduce-set-termination-protection-policy)
+ [

## ElasticMapReduceTerminateJobFlowsPolicy
](#elastic-map-reduce-terminate-job-flows-policy)
+ [

## ElasticsearchHttpPostPolicy
](#elastic-search-http-post-policy)
+ [

## EventBridgePutEventsPolicy
](#eventbridge-put-events-policy)
+ [

## FilterLogEventsPolicy
](#filter-log-events-policy)
+ [

## FirehoseCrudPolicy
](#firehose-crud-policy)
+ [

## FirehoseWritePolicy
](#firehose-write-policy)
+ [

## KinesisCrudPolicy
](#kinesis-crud-policy)
+ [

## KinesisStreamReadPolicy
](#kinesis-stream-read-policy)
+ [

## KMSDecryptPolicy
](#kms-decrypt-policy)
+ [

## KMSEncryptPolicy
](#kms-encrypt-policy)
+ [

## LambdaInvokePolicy
](#lambda-invoke-policy)
+ [

## MobileAnalyticsWriteOnlyAccessPolicy
](#mobile-analytics-write-only-access-policy)
+ [

## OrganizationsListAccountsPolicy
](#organizations-list-accounts-policy)
+ [

## PinpointEndpointAccessPolicy
](#pinpoint-endpoint-access-policy)
+ [

## PollyFullAccessPolicy
](#polly-full-access-policy)
+ [

## RekognitionDetectOnlyPolicy
](#rekognition-detect-only-policy)
+ [

## RekognitionFacesManagementPolicy
](#rekognition-face-management-policy)
+ [

## RekognitionFacesPolicy
](#rekognition-faces-policy)
+ [

## RekognitionLabelsPolicy
](#rekognition-labels-policy)
+ [

## RekognitionNoDataAccessPolicy
](#rekognition-no-data-access-policy)
+ [

## RekognitionReadPolicy
](#rekognition-read-policy)
+ [

## RekognitionWriteOnlyAccessPolicy
](#rekognition-write-only-access-policy)
+ [

## Route53ChangeResourceRecordSetsPolicy
](#route53-change-resource-record-sets-policy)
+ [

## S3CrudPolicy
](#s3-crud-policy)
+ [

## S3FullAccessPolicy
](#s3-full-access-policy)
+ [

## S3ReadPolicy
](#s3-read-policy)
+ [

## S3WritePolicy
](#s3-write-policy)
+ [

## SageMakerCreateEndpointConfigPolicy
](#sagemaker-create-endpoint-config-policy)
+ [

## SageMakerCreateEndpointPolicy
](#sagemaker-create-endpoint-policy)
+ [

## ServerlessRepoReadWriteAccessPolicy
](#serverlessrepo-read-write-access-policy)
+ [

## SESBulkTemplatedCrudPolicy
](#ses-bulk-templated-crud-policy)
+ [

## SESBulkTemplatedCrudPolicy\$1v2
](#ses-bulk-templated-crud-policy-v2)
+ [

## SESCrudPolicy
](#ses-crud-policy)
+ [

## SESEmailTemplateCrudPolicy
](#ses-email-template-crud-policy)
+ [

## SESSendBouncePolicy
](#ses-send-bounce-policy)
+ [

## SNSCrudPolicy
](#sns-crud-policy)
+ [

## SNSPublishMessagePolicy
](#sqs-publish-message-policy)
+ [

## SQSPollerPolicy
](#sqs-poller-policy)
+ [

## SQSSendMessagePolicy
](#sqs-send-message-policy)
+ [

## SSMParameterReadPolicy
](#ssm-parameter-read-policy)
+ [

## SSMParameterWithSlashPrefixReadPolicy
](#ssm-parameter-slash-read-policy)
+ [

## StepFunctionsExecutionPolicy
](#stepfunctions-execution-policy)
+ [

## TextractDetectAnalyzePolicy
](#textract-detect-analyze-policy)
+ [

## TextractGetResultPolicy
](#textract-get-result-policy)
+ [

## TextractPolicy
](#textract-policy)
+ [

## VPCAccessPolicy
](#vpc-access-policy)

## AcmGetCertificatePolicy
<a name="acm-get-certificate-policy"></a>

授予读取证书的权限 AWS Certificate Manager。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "acm:GetCertificate"
    ],
    "Resource": {
      "Fn::Sub": [
        "${certificateArn}",
        {
          "certificateArn": {
            "Ref": "CertificateArn"
          }
        }
      ]
    }
  }
]
```

## AMIDescribePolicy
<a name="ami-describe-policy"></a>

授予描述 Amazon 机器映像的权限 (AMIs)。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ec2:DescribeImages"
    ],
    "Resource": "*"
  }
]
```

## AthenaQueryPolicy
<a name="athena-query-policy"></a>

授予执行 Athena 查询的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "athena:ListWorkGroups",
      "athena:GetExecutionEngine",
      "athena:GetExecutionEngines",
      "athena:GetNamespace",
      "athena:GetCatalogs",
      "athena:GetNamespaces",
      "athena:GetTables",
      "athena:GetTable"
    ],
    "Resource": "*"
  },
  {
    "Effect": "Allow",
    "Action": [
      "athena:StartQueryExecution",
      "athena:GetQueryResults",
      "athena:DeleteNamedQuery",
      "athena:GetNamedQuery",
      "athena:ListQueryExecutions",
      "athena:StopQueryExecution",
      "athena:GetQueryResultsStream",
      "athena:ListNamedQueries",
      "athena:CreateNamedQuery",
      "athena:GetQueryExecution",
      "athena:BatchGetNamedQuery",
      "athena:BatchGetQueryExecution",
      "athena:GetWorkGroup"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:athena:${AWS::Region}:${AWS::AccountId}:workgroup/${workgroupName}",
        {
          "workgroupName": {
            "Ref": "WorkGroupName"
          }
        }
      ]
    }
  }
]
```

## AWSSecretsManagerGetSecretValuePolicy
<a name="secrets-manager-get-secret-value-policy"></a>

授予获取指定 AWS Secrets Manager 密钥的密钥值的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "secretsmanager:GetSecretValue"
    ],
    "Resource": {
      "Fn::Sub": [
        "${secretArn}",
        {
          "secretArn": {
            "Ref": "SecretArn"
          }
        }
      ]
    }
  }
]
```

## AWSSecretsManagerRotationPolicy
<a name="secrets-manager-rotation-policy"></a>

授予在 AWS Secrets Manager中轮换密钥的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "secretsmanager:DescribeSecret",
      "secretsmanager:GetSecretValue",
      "secretsmanager:PutSecretValue",
      "secretsmanager:UpdateSecretVersionStage"
    ],
    "Resource": {
      "Fn::Sub": "arn:${AWS::Partition}:secretsmanager:${AWS::Region}:${AWS::AccountId}:secret:*"
    },
    "Condition": {
      "StringEquals": {
        "secretsmanager:resource/AllowRotationLambdaArn": {
          "Fn::Sub": [
            "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${functionName}",
            {
              "functionName": {
                "Ref": "FunctionName"
              }
            }
          ]
        }
      }
    }
  },
  {
    "Effect": "Allow",
    "Action": [
      "secretsmanager:GetRandomPassword"
    ],
    "Resource": "*"
  }
]
```

## CloudFormationDescribeStacksPolicy
<a name="cloud-formation-describe-stacks-policy"></a>

授予描述 CloudFormation 堆栈的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "cloudformation:DescribeStacks"
    ],
    "Resource": {
      "Fn::Sub": "arn:${AWS::Partition}:cloudformation:${AWS::Region}:${AWS::AccountId}:stack/*"
    }
  }
]
```

## CloudWatchDashboardPolicy
<a name="cloudwatch-dashboard-policy"></a>

授予在 CloudWatch 仪表板上放置要操作的指标的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "cloudwatch:GetDashboard",
      "cloudwatch:ListDashboards",
      "cloudwatch:PutDashboard",
      "cloudwatch:ListMetrics"
    ],
    "Resource": "*"
  }
]
```

## CloudWatchDescribeAlarmHistoryPolicy
<a name="cloudwatch-describe-alarm-history-policy"></a>

授予描述亚马逊 CloudWatch 警报历史记录的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "cloudwatch:DescribeAlarmHistory"
    ],
    "Resource": "*"
  }
]
```

## CloudWatchPutMetricPolicy
<a name="cloudwatch-put-metric-policy"></a>

授予向发送指标的权限 CloudWatch。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "cloudwatch:PutMetricData"
    ],
    "Resource": "*"
  }
]
```

## CodePipelineLambdaExecutionPolicy
<a name="code-pipeline-lambda-execution-policy"></a>

允许调用的 Lambda 函数报告任务状态。 AWS CodePipeline 

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "codepipeline:PutJobSuccessResult",
      "codepipeline:PutJobFailureResult"
    ],
    "Resource": "*"
  }
]
```

## CodePipelineReadOnlyPolicy
<a name="code-pipeline-readonly-policy"></a>

授予读取权限以获取有关 CodePipeline 管道的详细信息。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "codepipeline:ListPipelineExecutions"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:codepipeline:${AWS::Region}:${AWS::AccountId}:${pipelinename}",
        {
          "pipelinename": {
            "Ref": "PipelineName"
          }
        }
      ]
    }
  }
]
```

## CodeCommitCrudPolicy
<a name="codecommit-crud-policy"></a>

授予在特定 CodeCommit存储库中创建、读取、更新和删除对象的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "codecommit:GitPull",
      "codecommit:GitPush",
      "codecommit:CreateBranch",
      "codecommit:DeleteBranch",
      "codecommit:GetBranch",
      "codecommit:ListBranches",
      "codecommit:MergeBranchesByFastForward",
      "codecommit:MergeBranchesBySquash",
      "codecommit:MergeBranchesByThreeWay",
      "codecommit:UpdateDefaultBranch",
      "codecommit:BatchDescribeMergeConflicts",
      "codecommit:CreateUnreferencedMergeCommit",
      "codecommit:DescribeMergeConflicts",
      "codecommit:GetMergeCommit",
      "codecommit:GetMergeOptions",
      "codecommit:BatchGetPullRequests",
      "codecommit:CreatePullRequest",
      "codecommit:DescribePullRequestEvents",
      "codecommit:GetCommentsForPullRequest",
      "codecommit:GetCommitsFromMergeBase",
      "codecommit:GetMergeConflicts",
      "codecommit:GetPullRequest",
      "codecommit:ListPullRequests",
      "codecommit:MergePullRequestByFastForward",
      "codecommit:MergePullRequestBySquash",
      "codecommit:MergePullRequestByThreeWay",
      "codecommit:PostCommentForPullRequest",
      "codecommit:UpdatePullRequestDescription",
      "codecommit:UpdatePullRequestStatus",
      "codecommit:UpdatePullRequestTitle",
      "codecommit:DeleteFile",
      "codecommit:GetBlob",
      "codecommit:GetFile",
      "codecommit:GetFolder",
      "codecommit:PutFile",
      "codecommit:DeleteCommentContent",
      "codecommit:GetComment",
      "codecommit:GetCommentsForComparedCommit",
      "codecommit:PostCommentForComparedCommit",
      "codecommit:PostCommentReply",
      "codecommit:UpdateComment",
      "codecommit:BatchGetCommits",
      "codecommit:CreateCommit",
      "codecommit:GetCommit",
      "codecommit:GetCommitHistory",
      "codecommit:GetDifferences",
      "codecommit:GetObjectIdentifier",
      "codecommit:GetReferences",
      "codecommit:GetTree",
      "codecommit:GetRepository",
      "codecommit:UpdateRepositoryDescription",
      "codecommit:ListTagsForResource",
      "codecommit:TagResource",
      "codecommit:UntagResource",
      "codecommit:GetRepositoryTriggers",
      "codecommit:PutRepositoryTriggers",
      "codecommit:TestRepositoryTriggers",
      "codecommit:GetBranch",
      "codecommit:GetCommit",
      "codecommit:UploadArchive",
      "codecommit:GetUploadArchiveStatus",
      "codecommit:CancelUploadArchive"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:codecommit:${AWS::Region}:${AWS::AccountId}:${repositoryName}",
        {
          "repositoryName": {
            "Ref": "RepositoryName"
          }
        }
      ]
    }
  }
]
```

## CodeCommitReadPolicy
<a name="codecommit-read-policy"></a>

授予读取特定 CodeCommit 存储库中对象的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "codecommit:GitPull",
      "codecommit:GetBranch",
      "codecommit:ListBranches",
      "codecommit:BatchDescribeMergeConflicts",
      "codecommit:DescribeMergeConflicts",
      "codecommit:GetMergeCommit",
      "codecommit:GetMergeOptions",
      "codecommit:BatchGetPullRequests",
      "codecommit:DescribePullRequestEvents",
      "codecommit:GetCommentsForPullRequest",
      "codecommit:GetCommitsFromMergeBase",
      "codecommit:GetMergeConflicts",
      "codecommit:GetPullRequest",
      "codecommit:ListPullRequests",
      "codecommit:GetBlob",
      "codecommit:GetFile",
      "codecommit:GetFolder",
      "codecommit:GetComment",
      "codecommit:GetCommentsForComparedCommit",
      "codecommit:BatchGetCommits",
      "codecommit:GetCommit",
      "codecommit:GetCommitHistory",
      "codecommit:GetDifferences",
      "codecommit:GetObjectIdentifier",
      "codecommit:GetReferences",
      "codecommit:GetTree",
      "codecommit:GetRepository",
      "codecommit:ListTagsForResource",
      "codecommit:GetRepositoryTriggers",
      "codecommit:TestRepositoryTriggers",
      "codecommit:GetBranch",
      "codecommit:GetCommit",
      "codecommit:GetUploadArchiveStatus"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:codecommit:${AWS::Region}:${AWS::AccountId}:${repositoryName}",
        {
          "repositoryName": {
            "Ref": "RepositoryName"
          }
        }
      ]
    }
  }
]
```

## ComprehendBasicAccessPolicy
<a name="comprehend-basic-access-policy"></a>

授予检测实体、关键短语、语言和情绪的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "comprehend:BatchDetectKeyPhrases",
      "comprehend:DetectDominantLanguage",
      "comprehend:DetectEntities",
      "comprehend:BatchDetectEntities",
      "comprehend:DetectKeyPhrases",
      "comprehend:DetectSentiment",
      "comprehend:BatchDetectDominantLanguage",
      "comprehend:BatchDetectSentiment"
    ],
    "Resource": "*"
  }
]
```

## CostExplorerReadOnlyPolicy
<a name="cost-explorer-readonly-policy"></a>

向只读 AWS Cost Explorer （Cost Explorer）授予账单历史记录 APIs 的只读权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ce:GetCostAndUsage",
      "ce:GetDimensionValues",
      "ce:GetReservationCoverage",
      "ce:GetReservationPurchaseRecommendation",
      "ce:GetReservationUtilization",
      "ce:GetTags"
    ],
    "Resource": "*"
  }
]
```

## DynamoDBBackupFullAccessPolicy
<a name="ddb-back-full-policy"></a>

授予对表进行 DynamoDB 按需备份的读和写权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:CreateBackup",
      "dynamodb:DescribeContinuousBackups"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}",
        {
          "tableName": {
            "Ref": "TableName"
          }
        }
      ]
    }
  },
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:DeleteBackup",
      "dynamodb:DescribeBackup",
      "dynamodb:ListBackups"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}/backup/*",
        {
          "tableName": {
            "Ref": "TableName"
          }
        }
      ]
    }
  }
]
```

## DynamoDBCrudPolicy
<a name="dynamo-db-crud-policy"></a>

授予对 Amazon DynamoDB 表的创建、读取、更新和删除权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:GetItem",
      "dynamodb:DeleteItem",
      "dynamodb:PutItem",
      "dynamodb:Scan",
      "dynamodb:Query",
      "dynamodb:UpdateItem",
      "dynamodb:BatchWriteItem",
      "dynamodb:BatchGetItem",
      "dynamodb:DescribeTable",
      "dynamodb:ConditionCheckItem"
    ],
    "Resource": [
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}",
          {
            "tableName": {
              "Ref": "TableName"
            }
          }
        ]
      },
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}/index/*",
          {
            "tableName": {
              "Ref": "TableName"
            }
          }
        ]
      }
    ]
  }
]
```

## DynamoDBReadPolicy
<a name="dynamo-db-read-policy"></a>

授予对 DynamoDB 表的只读权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:GetItem",
      "dynamodb:Scan",
      "dynamodb:Query",
      "dynamodb:BatchGetItem",
      "dynamodb:DescribeTable"
    ],
    "Resource": [
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}",
          {
            "tableName": {
              "Ref": "TableName"
            }
          }
        ]
      },
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}/index/*",
          {
            "tableName": {
              "Ref": "TableName"
            }
          }
        ]
      }
    ]
  }
]
```

## DynamoDBReconfigurePolicy
<a name="dynamo-db-reconfigure-policy"></a>

授予重新配置 DynamoDB 表的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:UpdateTable"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}",
        {
          "tableName": {
            "Ref": "TableName"
          }
        }
      ]
    }
  }
]
```

## DynamoDBRestoreFromBackupPolicy
<a name="ddb-restore-from-backup-policy"></a>

授予从备份还原 DynamoDB 表的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:RestoreTableFromBackup"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}/backup/*",
        {
          "tableName": {
            "Ref": "TableName"
          }
        }
      ]
    }
  },
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:PutItem",
      "dynamodb:UpdateItem",
      "dynamodb:DeleteItem",
      "dynamodb:GetItem",
      "dynamodb:Query",
      "dynamodb:Scan",
      "dynamodb:BatchWriteItem"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}",
        {
          "tableName": {
            "Ref": "TableName"
          }
        }
      ]
    }
  }
]
```

## DynamoDBStreamReadPolicy
<a name="dynamo-db-stream-read-policy"></a>

授予描述和读取 DynamoDB 流和记录的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:DescribeStream",
      "dynamodb:GetRecords",
      "dynamodb:GetShardIterator"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}/stream/${streamName}",
        {
          "tableName": {
            "Ref": "TableName"
          },
          "streamName": {
            "Ref": "StreamName"
          }
        }
      ]
    }
  },
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:ListStreams"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}/stream/*",
        {
          "tableName": {
            "Ref": "TableName"
          }
        }
      ]
    }
  }          
]
```

## DynamoDBWritePolicy
<a name="dynamo-db-write-policy"></a>

授予对 DynamoDB 表的只写权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:PutItem",
      "dynamodb:UpdateItem",
      "dynamodb:BatchWriteItem"
    ],
    "Resource": [
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}",
          {
            "tableName": {
              "Ref": "TableName"
            }
          }
        ]
      },
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:dynamodb:${AWS::Region}:${AWS::AccountId}:table/${tableName}/index/*",
          {
            "tableName": {
              "Ref": "TableName"
            }
          }
        ]
      }
    ]
  }
]
```

## EC2CopyImagePolicy
<a name="ec2-copy-image-policy"></a>

允许复制 Amazon EC2 图片。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ec2:CopyImage"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:ec2:${AWS::Region}:${AWS::AccountId}:image/${imageId}",
        {
          "imageId": {
            "Ref": "ImageId"
          }
        }
      ]
    }
  }
]
```

## EC2DescribePolicy
<a name="ec2-describe-policy"></a>

允许描述亚马逊弹性计算云 (Amazon EC2) 实例。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ec2:DescribeRegions",
      "ec2:DescribeInstances"
    ],
    "Resource": "*"
  }
]
```

## EcsRunTaskPolicy
<a name="ecs-run-task-policy"></a>

授予根据任务定义启动新任务的权限。

```
"Statement": [
  {
    "Action": [
      "ecs:RunTask"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:ecs:${AWS::Region}:${AWS::AccountId}:task-definition/${taskDefinition}",
        {
          "taskDefinition": {
            "Ref": "TaskDefinition"
          }
        }
      ]
    },
    "Effect": "Allow"
  }
]
```

## EFSWriteAccessPolicy
<a name="efs-write-access-policy"></a>

授予挂载具有写入访问权限的 Amazon EFS 文件系统的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "elasticfilesystem:ClientMount",
      "elasticfilesystem:ClientWrite"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:file-system/${FileSystem}",
        {
          "FileSystem": {
            "Ref": "FileSystem"
          }
        }
      ]
    },
    "Condition": {
      "StringEquals": {
        "elasticfilesystem:AccessPointArn": {
          "Fn::Sub": [
            "arn:${AWS::Partition}:elasticfilesystem:${AWS::Region}:${AWS::AccountId}:access-point/${AccessPoint}",
            {
              "AccessPoint": {
                "Ref": "AccessPoint"
              }
            }
          ]
        }
      }
    }
  }
]
```

## EKSDescribePolicy
<a name="eks-describe-policy"></a>

授予描述或列出 Amazon Elastic Kubernetes Service (Amazon EKS) 集群的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "eks:DescribeCluster",
      "eks:ListClusters"
    ],
    "Resource": "*"
  }
]
```

## ElasticMapReduceAddJobFlowStepsPolicy
<a name="elastic-map-reduce-add-job-flows-policy"></a>

授予将新步骤添加到运行的集群中的权限。

```
"Statement": [
  {
    "Action": "elasticmapreduce:AddJobFlowSteps",
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:${AWS::AccountId}:cluster/${clusterId}",
        {
          "clusterId": {
            "Ref": "ClusterId"
          }
        }
      ]
    },
    "Effect": "Allow"
  }
]
```

## ElasticMapReduceCancelStepsPolicy
<a name="elastic-map-reduce-cancel-steps-policy"></a>

授予取消正在运行中的集群中的一个或多个待处理步骤的权限。

```
"Statement": [
  {
    "Action": "elasticmapreduce:CancelSteps",
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:${AWS::AccountId}:cluster/${clusterId}",
        {
          "clusterId": {
            "Ref": "ClusterId"
          }
        }
      ]
    },
    "Effect": "Allow"
  }
]
```

## ElasticMapReduceModifyInstanceFleetPolicy
<a name="elastic-map-reduce-modify-instance-fleet-policy"></a>

授予列出集群内实例集的详细信息和修改这些实例集的容量的权限。

```
"Statement": [
  {
    "Action": [
      "elasticmapreduce:ModifyInstanceFleet",
      "elasticmapreduce:ListInstanceFleets"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:${AWS::AccountId}:cluster/${clusterId}",
        {
          "clusterId": {
            "Ref": "ClusterId"
          }
        }
      ]
    },
    "Effect": "Allow"
  }
]
```

## ElasticMapReduceModifyInstanceGroupsPolicy
<a name="elastic-map-reduce-modify-instance-groups-policy"></a>

授予列出集群内实例组的详细信息和修改这些实例组的设置的权限。

```
"Statement": [
  {
    "Action": [
      "elasticmapreduce:ModifyInstanceGroups",
      "elasticmapreduce:ListInstanceGroups"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:${AWS::AccountId}:cluster/${clusterId}",
        {
          "clusterId": {
            "Ref": "ClusterId"
          }
        }
      ]
    },
    "Effect": "Allow"
  }
]
```

## ElasticMapReduceSetTerminationProtectionPolicy
<a name="elastic-map-reduce-set-termination-protection-policy"></a>

授予为集群设置终止保护的权限。

```
"Statement": [
  {
    "Action": "elasticmapreduce:SetTerminationProtection",
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:${AWS::AccountId}:cluster/${clusterId}",
        {
          "clusterId": {
            "Ref": "ClusterId"
          }
        }
      ]
    },
    "Effect": "Allow"
  }
]
```

## ElasticMapReduceTerminateJobFlowsPolicy
<a name="elastic-map-reduce-terminate-job-flows-policy"></a>

授予关闭集群的权限。

```
"Statement": [
  {
    "Action": "elasticmapreduce:TerminateJobFlows",
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:elasticmapreduce:${AWS::Region}:${AWS::AccountId}:cluster/${clusterId}",
        {
          "clusterId": {
            "Ref": "ClusterId"
          }
        }
      ]
    },
    "Effect": "Allow"
  }
]
```

## ElasticsearchHttpPostPolicy
<a name="elastic-search-http-post-policy"></a>

向 Amazon OpenSearch 服务授予 POST 和 PUT 权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "es:ESHttpPost",
      "es:ESHttpPut"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:es:${AWS::Region}:${AWS::AccountId}:domain/${domainName}/*",
        {
          "domainName": {
            "Ref": "DomainName"
          }
        }
      ]
    }
  }
]
```

## EventBridgePutEventsPolicy
<a name="eventbridge-put-events-policy"></a>

授予向 Amazon 发送事件的权限 EventBridge。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": "events:PutEvents",
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:events:${AWS::Region}:${AWS::AccountId}:event-bus/${eventBusName}",
        {
          "eventBusName": {
            "Ref": "EventBusName"
          }
        }
      ]
    }
  }
]
```

## FilterLogEventsPolicy
<a name="filter-log-events-policy"></a>

授予筛选指定 CloudWatch 日志组中的日志事件的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "logs:FilterLogEvents"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:${logGroupName}:log-stream:*",
        {
          "logGroupName": {
            "Ref": "LogGroupName"
          }
        }
      ]
    }
  }
]
```

## FirehoseCrudPolicy
<a name="firehose-crud-policy"></a>

授予创建、写入、更新和删除 Firehose 传输流的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "firehose:CreateDeliveryStream",
      "firehose:DeleteDeliveryStream",
      "firehose:DescribeDeliveryStream",
      "firehose:PutRecord",
      "firehose:PutRecordBatch",
      "firehose:UpdateDestination"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:firehose:${AWS::Region}:${AWS::AccountId}:deliverystream/${deliveryStreamName}",
        {
          "deliveryStreamName": {
            "Ref": "DeliveryStreamName"
          }
        }
      ]
    }
  }
]
```

## FirehoseWritePolicy
<a name="firehose-write-policy"></a>

授予写入 Firehose 传输流的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "firehose:PutRecord",
      "firehose:PutRecordBatch"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:firehose:${AWS::Region}:${AWS::AccountId}:deliverystream/${deliveryStreamName}",
        {
          "deliveryStreamName": {
            "Ref": "DeliveryStreamName"
          }
        }
      ]
    }
  }
]
```

## KinesisCrudPolicy
<a name="kinesis-crud-policy"></a>

授予创建、发布和删除 Amazon Kinesis 流的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "kinesis:AddTagsToStream",
      "kinesis:CreateStream",
      "kinesis:DecreaseStreamRetentionPeriod",
      "kinesis:DeleteStream",
      "kinesis:DescribeStream",
      "kinesis:DescribeStreamSummary",
      "kinesis:GetShardIterator",
      "kinesis:IncreaseStreamRetentionPeriod",
      "kinesis:ListTagsForStream",
      "kinesis:MergeShards",
      "kinesis:PutRecord",
      "kinesis:PutRecords",
      "kinesis:SplitShard",
      "kinesis:RemoveTagsFromStream"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:kinesis:${AWS::Region}:${AWS::AccountId}:stream/${streamName}",
        {
          "streamName": {
            "Ref": "StreamName"
          }
        }
      ]
    }
  }
]
```

## KinesisStreamReadPolicy
<a name="kinesis-stream-read-policy"></a>

授予列出和读取 Amazon Kinesis 流的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "kinesis:ListStreams",
      "kinesis:DescribeLimits"
    ],
    "Resource": {
      "Fn::Sub": "arn:${AWS::Partition}:kinesis:${AWS::Region}:${AWS::AccountId}:stream/*"
    }
  },
  {
    "Effect": "Allow",
    "Action": [
      "kinesis:DescribeStream",
      "kinesis:DescribeStreamSummary",
      "kinesis:GetRecords",
      "kinesis:GetShardIterator"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:kinesis:${AWS::Region}:${AWS::AccountId}:stream/${streamName}",
        {
          "streamName": {
            "Ref": "StreamName"
          }
        }
      ]
    }
  }
]
```

## KMSDecryptPolicy
<a name="kms-decrypt-policy"></a>

授予使用 AWS Key Management Service (AWS KMS) 密钥解密的权限。请注意，`keyId`必须是 AWS KMS 密钥 ID，而不是密钥别名。

```
"Statement": [
  {
    "Action": "kms:Decrypt",
    "Effect": "Allow",
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:kms:${AWS::Region}:${AWS::AccountId}:key/${keyId}",
        {
          "keyId": {
            "Ref": "KeyId"
          }
        }
      ]
    }
  }
]
```

## KMSEncryptPolicy
<a name="kms-encrypt-policy"></a>

允许使用密 AWS KMS 钥进行加密。请注意，keyID 必须是 AWS KMS 密钥 ID，而不是密钥别名。

```
"Statement": [
  {
    "Action": "kms:Encrypt",
    "Effect": "Allow",
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:kms:${AWS::Region}:${AWS::AccountId}:key/${keyId}",
        {
          "keyId": {
            "Ref": "KeyId"
          }
        }
      ]
    }
  }
]
```

## LambdaInvokePolicy
<a name="lambda-invoke-policy"></a>

授予调用 AWS Lambda 函数、别名或版本的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "lambda:InvokeFunction"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:lambda:${AWS::Region}:${AWS::AccountId}:function:${functionName}*",
        {
          "functionName": {
            "Ref": "FunctionName"
          }
        }
      ]
    }
  }
]
```

## MobileAnalyticsWriteOnlyAccessPolicy
<a name="mobile-analytics-write-only-access-policy"></a>

授予对所有应用程序资源放置事件数据的只写权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "mobileanalytics:PutEvents"
    ],
    "Resource": "*"
  }
]
```

## OrganizationsListAccountsPolicy
<a name="organizations-list-accounts-policy"></a>

授予列出子女账户名称的只读权限，以及 IDs.

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "organizations:ListAccounts"
    ],
    "Resource": "*"
  }
]
```

## PinpointEndpointAccessPolicy
<a name="pinpoint-endpoint-access-policy"></a>

授予为 Amazon Pinpoint 应用程序获取并更新端点的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "mobiletargeting:GetEndpoint",
      "mobiletargeting:UpdateEndpoint",
      "mobiletargeting:UpdateEndpointsBatch"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:mobiletargeting:${AWS::Region}:${AWS::AccountId}:apps/${pinpointApplicationId}/endpoints/*",
        {
          "pinpointApplicationId": {
            "Ref": "PinpointApplicationId"
          }
        }
      ]
    }
  }
]
```

## PollyFullAccessPolicy
<a name="polly-full-access-policy"></a>

授予对 Amazon Polly 词典资源的完全访问权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "polly:GetLexicon",
      "polly:DeleteLexicon"
    ],
    "Resource": [
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:polly:${AWS::Region}:${AWS::AccountId}:lexicon/${lexiconName}",
          {
            "lexiconName": {
              "Ref": "LexiconName"
            }
          }
        ]
      }
    ]
  },
  {
    "Effect": "Allow",
    "Action": [
      "polly:DescribeVoices",
      "polly:ListLexicons",
      "polly:PutLexicon",
      "polly:SynthesizeSpeech"
    ],
    "Resource": [
      {
        "Fn::Sub": "arn:${AWS::Partition}:polly:${AWS::Region}:${AWS::AccountId}:lexicon/*"
      }
    ]
  }
]
```

## RekognitionDetectOnlyPolicy
<a name="rekognition-detect-only-policy"></a>

授予检测人脸、标签和文本的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "rekognition:DetectFaces",
      "rekognition:DetectLabels",
      "rekognition:DetectModerationLabels",
      "rekognition:DetectText"
    ],
    "Resource": "*"
  }
]
```

## RekognitionFacesManagementPolicy
<a name="rekognition-face-management-policy"></a>

授予在 Amazon Rekognition 集合中添加、删除和搜索人脸的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "rekognition:IndexFaces",
      "rekognition:DeleteFaces",
      "rekognition:SearchFaces",
      "rekognition:SearchFacesByImage",
      "rekognition:ListFaces"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:rekognition:${AWS::Region}:${AWS::AccountId}:collection/${collectionId}",
        {
          "collectionId": {
            "Ref": "CollectionId"
          }
        }
      ]
    }
  }
]
```

## RekognitionFacesPolicy
<a name="rekognition-faces-policy"></a>

授予比较并检测面部和标签的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "rekognition:CompareFaces",
      "rekognition:DetectFaces"
    ],
    "Resource": "*"
  }
]
```

## RekognitionLabelsPolicy
<a name="rekognition-labels-policy"></a>

授予检测对象和审核标签的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "rekognition:DetectLabels",
      "rekognition:DetectModerationLabels"
    ],
    "Resource": "*"
  }
]
```

## RekognitionNoDataAccessPolicy
<a name="rekognition-no-data-access-policy"></a>

授予比较并检测面部和标签的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "rekognition:CompareFaces",
      "rekognition:DetectFaces",
      "rekognition:DetectLabels",
      "rekognition:DetectModerationLabels"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:rekognition:${AWS::Region}:${AWS::AccountId}:collection/${collectionId}",
        {
          "collectionId": {
            "Ref": "CollectionId"
          }
        }
      ]
    }
  }
]
```

## RekognitionReadPolicy
<a name="rekognition-read-policy"></a>

授予列出和搜索人脸的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "rekognition:ListCollections",
      "rekognition:ListFaces",
      "rekognition:SearchFaces",
      "rekognition:SearchFacesByImage"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:rekognition:${AWS::Region}:${AWS::AccountId}:collection/${collectionId}",
        {
          "collectionId": {
            "Ref": "CollectionId"
          }
        }
      ]
    }
  }
]
```

## RekognitionWriteOnlyAccessPolicy
<a name="rekognition-write-only-access-policy"></a>

授予创建集合和为人脸编制索引的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "rekognition:CreateCollection",
      "rekognition:IndexFaces"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:rekognition:${AWS::Region}:${AWS::AccountId}:collection/${collectionId}",
        {
          "collectionId": {
            "Ref": "CollectionId"
          }
        }
      ]
    }
  }
]
```

## Route53ChangeResourceRecordSetsPolicy
<a name="route53-change-resource-record-sets-policy"></a>

授予更改 Route 53 中的资源记录集的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "route53:ChangeResourceRecordSets"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:route53:::hostedzone/${HostedZoneId}",
        {
          "HostedZoneId": {
            "Ref": "HostedZoneId"
          }
        }
      ]
    }
  }
]
```

## S3CrudPolicy
<a name="s3-crud-policy"></a>

授予创建、读取、更新和删除权限，以便对 Amazon S3 存储桶中的对象执行操作。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "s3:GetObject",
      "s3:ListBucket",
      "s3:GetBucketLocation",
      "s3:GetObjectVersion",
      "s3:PutObject",
      "s3:PutObjectAcl",
      "s3:GetLifecycleConfiguration",
      "s3:PutLifecycleConfiguration",
      "s3:DeleteObject"
    ],
    "Resource": [
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:s3:::${bucketName}",
          {
            "bucketName": {
              "Ref": "BucketName"
            }
          }
        ]
      },
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:s3:::${bucketName}/*",
          {
            "bucketName": {
              "Ref": "BucketName"
            }
          }
        ]
      }
    ]
  }
]
```

## S3FullAccessPolicy
<a name="s3-full-access-policy"></a>

授予完全访问权限，以便对 Amazon S3 存储桶中的对象执行操作。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "s3:GetObject",
      "s3:GetObjectAcl",
      "s3:GetObjectVersion",
      "s3:PutObject",
      "s3:PutObjectAcl",
      "s3:DeleteObject",
      "s3:DeleteObjectTagging",
      "s3:DeleteObjectVersionTagging",
      "s3:GetObjectTagging",
      "s3:GetObjectVersionTagging",
      "s3:PutObjectTagging",
      "s3:PutObjectVersionTagging"
    ],
    "Resource": [
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:s3:::${bucketName}/*",
          {
            "bucketName": {
              "Ref": "BucketName"
            }
          }
        ]
      }
    ]
  },
  {
    "Effect": "Allow",
    "Action": [
      "s3:ListBucket",
      "s3:GetBucketLocation",
      "s3:GetLifecycleConfiguration",
      "s3:PutLifecycleConfiguration"
    ],
    "Resource": [
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:s3:::${bucketName}",
          {
            "bucketName": {
              "Ref": "BucketName"
            }
          }
        ]
      }
    ]
  }
]
```

## S3ReadPolicy
<a name="s3-read-policy"></a>

授予读取 Amazon Simple Storage Service (Amazon S3) 存储桶中的对象的只读权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "s3:GetObject",
      "s3:ListBucket",
      "s3:GetBucketLocation",
      "s3:GetObjectVersion",
      "s3:GetLifecycleConfiguration"
    ],
    "Resource": [
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:s3:::${bucketName}",
          {
            "bucketName": {
              "Ref": "BucketName"
            }
          }
        ]
      },
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:s3:::${bucketName}/*",
          {
            "bucketName": {
              "Ref": "BucketName"
            }
          }
        ]
      }
    ]
  }
]
```

## S3WritePolicy
<a name="s3-write-policy"></a>

授予将对象写入到 Amazon S3 存储桶的写入权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "s3:PutObject",
      "s3:PutObjectAcl",
      "s3:PutLifecycleConfiguration"
    ],
    "Resource": [
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:s3:::${bucketName}",
          {
            "bucketName": {
              "Ref": "BucketName"
            }
          }
        ]
      },
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:s3:::${bucketName}/*",
          {
            "bucketName": {
              "Ref": "BucketName"
            }
          }
        ]
      }
    ]
  }
]
```

## SageMakerCreateEndpointConfigPolicy
<a name="sagemaker-create-endpoint-config-policy"></a>

授予在 SageMaker AI 中创建终端节点配置的权限。

```
"Statement": [
  {
    "Action": [
      "sagemaker:CreateEndpointConfig"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:sagemaker:${AWS::Region}:${AWS::AccountId}:endpoint-config/${endpointConfigName}",
        {
          "endpointConfigName": {
            "Ref": "EndpointConfigName"
          }
        }
      ]
    },
    "Effect": "Allow"
  }
]
```

## SageMakerCreateEndpointPolicy
<a name="sagemaker-create-endpoint-policy"></a>

授予在 SageMaker AI 中创建终端节点的权限。

```
"Statement": [
  {
    "Action": [
      "sagemaker:CreateEndpoint"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:sagemaker:${AWS::Region}:${AWS::AccountId}:endpoint/${endpointName}",
        {
          "endpointName": {
            "Ref": "EndpointName"
          }
        }
      ]
    },
    "Effect": "Allow"
  }
]
```

## ServerlessRepoReadWriteAccessPolicy
<a name="serverlessrepo-read-write-access-policy"></a>

授予在 AWS Serverless Application Repository (AWS SAM) 服务中创建和列出应用程序的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "serverlessrepo:CreateApplication",
      "serverlessrepo:CreateApplicationVersion",
      "serverlessrepo:GetApplication",
      "serverlessrepo:ListApplications",
      "serverlessrepo:ListApplicationVersions"
    ],
    "Resource": [
      {
        "Fn::Sub": "arn:${AWS::Partition}:serverlessrepo:${AWS::Region}:${AWS::AccountId}:applications/*"
      }
    ]
  }
]
```

## SESBulkTemplatedCrudPolicy
<a name="ses-bulk-templated-crud-policy"></a>

授予发送 Amazon SES 电子邮件、模板化电子邮件和模板化批量电子邮件以及验证身份的权限。

**注意**  
 `ses:SendTemplatedEmail` 操作需要模板 ARN。请改用 `SESBulkTemplatedCrudPolicy_v2`。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ses:GetIdentityVerificationAttributes",
      "ses:SendEmail",
      "ses:SendRawEmail",
      "ses:SendTemplatedEmail",
      "ses:SendBulkTemplatedEmail",
      "ses:VerifyEmailIdentity"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/${identityName}",
        {
          "identityName": {
            "Ref": "IdentityName"
          }
        }
      ]
    }
  }
]
```

## SESBulkTemplatedCrudPolicy\$1v2
<a name="ses-bulk-templated-crud-policy-v2"></a>

授予发送 Amazon SES 电子邮件、模板化电子邮件和模板化批量电子邮件以及验证身份的权限。

```
"Statement": [
  {
    "Action": [
      "ses:SendEmail",
      "ses:SendRawEmail",
      "ses:SendTemplatedEmail",
      "ses:SendBulkTemplatedEmail"
    ],
    "Effect": "Allow",
    "Resource": [
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/${identityName}",
          {
            "identityName": {
              "Ref": "IdentityName"
            }
          }
        ]
      },
      {
        "Fn::Sub": [
          "arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:template/${templateName}",
          {
            "templateName": {
              "Ref": "TemplateName"
            }
          }
        ]
      }
    ]
  },
  {
    "Action": [
      "ses:GetIdentityVerificationAttributes",
      "ses:VerifyEmailIdentity"
    ],
    "Effect": "Allow",
    "Resource": "*"
  }
]
```

## SESCrudPolicy
<a name="ses-crud-policy"></a>

授予发送电子邮件和验证身份的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ses:GetIdentityVerificationAttributes",
      "ses:SendEmail",
      "ses:SendRawEmail",
      "ses:VerifyEmailIdentity"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/${identityName}",
        {
          "identityName": {
            "Ref": "IdentityName"
          }
        }
      ]
    }
  }
]
```

## SESEmailTemplateCrudPolicy
<a name="ses-email-template-crud-policy"></a>

授予创建、获取、列出、更新和删除 Amazon SES 电子邮件模板的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ses:CreateTemplate",
      "ses:GetTemplate",
      "ses:ListTemplates",
      "ses:UpdateTemplate",
      "ses:DeleteTemplate",
      "ses:TestRenderTemplate"
    ],
    "Resource": "*"
  }
]
```

## SESSendBouncePolicy
<a name="ses-send-bounce-policy"></a>

 SendBounce 授予亚马逊简单电子邮件服务 (Amazon SES) Service 身份的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ses:SendBounce"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:ses:${AWS::Region}:${AWS::AccountId}:identity/${identityName}",
        {
          "identityName": {
            "Ref": "IdentityName"
          }
        }
      ]
    }
  }
]
```

## SNSCrudPolicy
<a name="sns-crud-policy"></a>

授予创建、发布和订阅 Amazon SNS 主题的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "sns:ListSubscriptionsByTopic",
      "sns:CreateTopic",
      "sns:SetTopicAttributes",
      "sns:Subscribe",
      "sns:Publish"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:sns:${AWS::Region}:${AWS::AccountId}:${topicName}*",
        {
          "topicName": {
            "Ref": "TopicName"
          }
        }
      ]
    }
  }
]
```

## SNSPublishMessagePolicy
<a name="sqs-publish-message-policy"></a>

授予将消息发布到 Amazon Simple Notiﬁcation Service (Amazon SNS)主题的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "sns:Publish"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:sns:${AWS::Region}:${AWS::AccountId}:${topicName}",
        {
          "topicName": {
            "Ref": "TopicName"
          }
        }
      ]
    }
  }
]
```

## SQSPollerPolicy
<a name="sqs-poller-policy"></a>

授予轮询 Amazon Simple Queue Service (Amazon SQS) 队列的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "sqs:ChangeMessageVisibility",
      "sqs:ChangeMessageVisibilityBatch",
      "sqs:DeleteMessage",
      "sqs:DeleteMessageBatch",
      "sqs:GetQueueAttributes",
      "sqs:ReceiveMessage"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:sqs:${AWS::Region}:${AWS::AccountId}:${queueName}",
        {
          "queueName": {
            "Ref": "QueueName"
          }
        }
      ]
    }
  }
]
```

## SQSSendMessagePolicy
<a name="sqs-send-message-policy"></a>

授予向 Amazon SQS 队列发送消息的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "sqs:SendMessage*"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:sqs:${AWS::Region}:${AWS::AccountId}:${queueName}",
        {
          "queueName": {
            "Ref": "QueueName"
          }
        }
      ]
    }
  }
]
```

## SSMParameterReadPolicy
<a name="ssm-parameter-read-policy"></a>

授予访问来自 Amazon S EC2 ystems Manager (SSM) 参数存储库的参数的权限，以便在此账户中加载密钥。在参数名称不包含斜杠前缀时使用。

**注意**  
如果没有使用默认密钥，则还需要 `KMSDecryptPolicy` 策略。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ssm:DescribeParameters"
    ],
    "Resource": "*"
  },
  {
    "Effect": "Allow",
    "Action": [
      "ssm:GetParameters",
      "ssm:GetParameter",
      "ssm:GetParametersByPath"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter/${parameterName}",
        {
          "parameterName": {
            "Ref": "ParameterName"
          }
        }
      ]
    }
  }
]
```

## SSMParameterWithSlashPrefixReadPolicy
<a name="ssm-parameter-slash-read-policy"></a>

授予访问来自 Amazon S EC2 ystems Manager (SSM) 参数存储库的参数的权限，以便在此账户中加载密钥。在参数名称包含斜杠前缀时使用。

**注意**  
如果没有使用默认密钥，则还需要 `KMSDecryptPolicy` 策略。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ssm:DescribeParameters"
    ],
    "Resource": "*"
  },
  {
    "Effect": "Allow",
    "Action": [
      "ssm:GetParameters",
      "ssm:GetParameter",
      "ssm:GetParametersByPath"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:ssm:${AWS::Region}:${AWS::AccountId}:parameter${parameterName}",
        {
          "parameterName": {
            "Ref": "ParameterName"
          }
        }
      ]
    }
  }
]
```

## StepFunctionsExecutionPolicy
<a name="stepfunctions-execution-policy"></a>

授予开始执行 Step Functions 状态机的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "states:StartExecution"
    ],
    "Resource": {
      "Fn::Sub": [
        "arn:${AWS::Partition}:states:${AWS::Region}:${AWS::AccountId}:stateMachine:${stateMachineName}",
        {
          "stateMachineName": {
            "Ref": "StateMachineName"
          }
        }
      ]
    }
  }
]
```

## TextractDetectAnalyzePolicy
<a name="textract-detect-analyze-policy"></a>

授予使用 Amazon Textract 检测和分析文档的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "textract:DetectDocumentText",
      "textract:StartDocumentTextDetection",
      "textract:StartDocumentAnalysis",
      "textract:AnalyzeDocument"
    ],
    "Resource": "*"
  }
]
```

## TextractGetResultPolicy
<a name="textract-get-result-policy"></a>

授予从 Amazon Textract 中获取检测到和分析过的文档的权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "textract:GetDocumentTextDetection",
      "textract:GetDocumentAnalysis"
    ],
    "Resource": "*"
  }
]
```

## TextractPolicy
<a name="textract-policy"></a>

授予对 Amazon Textract 的完全访问权限。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "textract:*"
    ],
    "Resource": "*"
  }
]
```

## VPCAccessPolicy
<a name="vpc-access-policy"></a>

授予访问权限以创建、删除、描述和分离弹性网络接口。

```
"Statement": [
  {
    "Effect": "Allow",
    "Action": [
      "ec2:CreateNetworkInterface",
      "ec2:DeleteNetworkInterface",
      "ec2:DescribeNetworkInterfaces",
      "ec2:DetachNetworkInterface"
    ],
    "Resource": "*"
  }
]
```

# 使用 CloudFormation 机制管理 AWS SAM 权限
<a name="sam-permissions-cloudformation"></a>

要控制对 AWS 资源的访问权限， AWS Serverless Application Model (AWS SAM) 可以使用与相同的机制 CloudFormation。有关更多信息，请参阅《*AWS CloudFormation 用户指南*》中的[使用 AWS Identity and Access Management进行访问控制](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html)。

有三个选项可用于向用户授予管理无服务器应用程序的权限。每个选项可为用户提供不同级别的访问控制。
+ 授予管理员权限。
+ 附加必要的 AWS 托管策略。
+ 授予特定 AWS Identity and Access Management (IAM) 权限。

根据您选择的选项，用户只能管理包含他们有权访问的 AWS 资源的无服务器应用程序。

以下部分详细介绍了每个选项。

## 授予管理员权限
<a name="sam-permissions-cloudformation-admin"></a>

如果您向用户授予管理员权限，则他们可以管理包含任意 AWS 资源组合的无服务器应用程序。这是最简单的选项，但也会向用户授予最广泛的权限，使得他们能够执行具有巨大影响的操作。

有关向用户授予管理员权限的详细信息，请参阅 *IAM 用户指南*中的[创建您的第一个 IAM 管理员用户和组](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html)。

## 附加必要的 AWS 托管策略
<a name="sam-permissions-cloudformation-managed-policies"></a>

您可以使用 [AWS 托管策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies)向用户授予部分权限，而不是授予完全管理员权限。如果使用此选项，请确保 AWS 托管策略集涵盖用户管理的无服务器应用程序所需的所有操作和资源。

例如，以下 AWS 托管策略足以[部署示例 Hello World 应用程序](serverless-getting-started-hello-world.md)：
+ AWSCloudFormationFullAccess
+ IAMFull访问权限
+ AWSLambda\$1FullAccess
+ 亚马逊APIGateway管理员
+ 亚马逊 3 FullAccess
+ Amazon EC2 ContainerRegistryFullAccess

 有关附加策略到 IAM 用户的信息，请参阅*《IAM 用户指南》*中的[更改 IAM 用户的权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_change-permissions.html)。

## 授予特定的 IAM 权限
<a name="sam-permissions-cloudformation-policy-statement"></a>

要实现最精细级别的访问控制，您可以使用[策略声明](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_statement.html)向用户授予特定的 IAM 权限。如果使用此选项，请确保策略声明包含用户管理的无服务器应用程序所需的所有操作和资源。

使用此选项的最佳做法是，拒绝用户创建角色（包括 Lambda 执行角色）的权限，这样他们就无法向自己授予升级权限。因此，作为管理员，您必须先创建 [Lambda 执行角色](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html)（该角色将在用户要管理的无服务器应用程序中指定）。有关创建 Lambda 执行角色的信息，请参阅[在 IAM 控制台中创建执行角色](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html#permissions-executionrole-console)。

对于[示例 Hello World 应用程序](serverless-getting-started-hello-world.md)，足以运行该应用程序。**AWSLambdaBasicExecutionRole**创建 Lambda 执行角色后，修改示例 Hello World 应用程序的 AWS SAM 模板文件，将以下属性添加到资源中`AWS::Serverless::Function`：

```
  Role: lambda-execution-role-arn
```

修改后的 Hello World 应用程序准备就绪后，以下策略声明会向用户授予部署、更新和删除应用程序所需的足够权限：

**注意**  
本节中的示例策略声明向您授予部署、更新和删除[示例 Hello World 应用程序](serverless-getting-started-hello-world.md)所需的足够权限。如果您向应用程序添加其他资源类型，则需要更新政策声明以包含以下内容：  
应用程序调用服务操作所需的权限。
服务主体（如果对于服务操作是必需的）。
例如，如果您添加 Step Functions 工作流程，则可能需要添加[此处](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsstepfunctions.html#awsstepfunctions-actions-as-permissions)所列操作的权限以及 `states.amazonaws.com` 服务主体。

有关 IAM policy 的更多信息，请参阅 *IAM 用户指南*中的[管理 IAM policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage.html)。

# 使用您的 AWS SAM 模板控制 API 访问权限
<a name="serverless-controlling-access-to-apis"></a>

控制 API Gateway 的访问权限 APIs 有助于确保您的无服务器应用程序是安全的，并且只能通过您启用的授权进行访问。您可以在 AWS SAM 模板中启用授权，以控制谁可以访问您的 API Gateway APIs。

AWS SAM 支持多种控制您的 API Gateway 访问权限的机制 APIs。`AWS::Serverless::HttpApi` 和 `AWS::Serverless::Api` 资源类型所支持的机制集有所不同。

下表总结了每种资源类型支持的机制。


| 控制访问的机制 | AWS::Serverless::HttpApi | AWS::Serverless::Api | 
| --- | --- | --- | 
| Lambda 授权方 | ✓ | ✓ | 
| IAM 权限 |  | ✓ | 
| Amazon Cognito 用户群体 | ✓ \$1 | ✓ | 
| API 密钥 |  | ✓ | 
| 资源策略 |  | ✓ | 
| OAuth 2.0/JWT 授权方 | ✓ |  | 

\$1 您可以使用 Amazon Cognito 作为 `AWS::Serverless::HttpApi` 资源类型的 JSON Web Token (JWT) 颁发者。
+ **Lambda 授权方** – Lambda 授权方（以前称为*自定义授权方*）是您为控制对 API 的访问而提供的 Lambda 函数。调用 API 时，将使用客户端应用程序提供的请求上下文或授权令牌调用此 Lambda 函数。Lambda 函数会响应调用者是否有权执行所请求的操作。

  `AWS::Serverless::HttpApi` 和 `AWS::Serverless::Api` 资源类型均支持 Lambda 授权方。

  *有关使用的 Lambda 授权方的更多信息`AWS::Serverless::HttpApi`，请参阅 APIs API Gateway [开发者指南中的使用 HTTP 的 AWS Lambda 授权方](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-lambda-authorizer.html)。*有关 Lambda 授权方与 `AWS::Serverless::Api` 的更多信息，请参阅*《API Gateway 开发人员指南》*中的[使用 API Gateway Lambda 授权方](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html)。

  有关任一资源类型的 Lambda 授权方的示例，请参阅 [Lambda 授权方示例 AWS SAM](serverless-controlling-access-to-apis-lambda-authorizer.md)。

  
+ **IAM 权限** – 您可以使用 [AWS Identity and Access Management (IAM) 权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_controlling.html)控制谁可以调用您的 API。调用 API 的用户必须使用 IAM 凭证进行身份验证。只有存在与代表 API 调用方的 IAM 用户、包含该用户的 IAM 群组或该用户担任的 IAM 角色关联的 IAM policy 时，对 API 的调用才会成功。

  仅 `AWS::Serverless::Api` 资源类型支持 IAM 权限。

  有关更多信息，请参阅*《API Gateway 开发人员指南》*中的[使用 IAM 权限控制对 API 的访问](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html)。有关示例，请参阅[的 IAM 权限示例 AWS SAM](serverless-controlling-access-to-apis-permissions.md)。
+ **Amazon Cognito 用户群体** – Amazon Cognito 用户群体是 Amazon Cognito 中的用户目录。API 的客户端必须先将用户登录到用户群体，然后为该用户获取身份或访问令牌。然后，客户端使用其中返回的令牌调用 API。只有在所需的令牌有效时，API 调用才会成功。

  `AWS::Serverless::Api` 资源类型支持 Amazon Cognito 用户群体。`AWS::Serverless::HttpApi` 资源类型支持使用 Amazon Cognito 作为 JWT 颁发者。

  有关更多信息，请参阅*《API Gateway 开发人员指南》*中的[使用 Amazon Cognito 用户群体作为授权方控制对 REST API 的访问](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html)。有关示例，请参阅[Amazon Cognito 用户池示例 AWS SAM](serverless-controlling-access-to-apis-cognito-user-pool.md)。
+ **API 密钥** – API 密钥是字母数字字符串值，可将它分发给应用程序开发人员（要向其授予对您的 API 的访问权的客户）。

  仅 `AWS::Serverless::Api` 资源类型支持 API 密钥。

  有关 API 密钥的更多信息，请参阅*《API Gateway 开发人员指南》*中的[创建和使用带 API 密钥的使用计划](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html)。有关 API 密钥的示例，请参阅 [的 API 密钥示例 AWS SAM](serverless-controlling-access-to-apis-keys.md)。
+ **资源策略** – 资源策略是您可以附加到 API Gateway API 的 JSON 策略文档。使用资源策略控制指定的主体（通常是 IAM 用户或角色）能否调用 API。

  只有`AWS::Serverless::Api`资源类型支持资源策略作为控制 API Gateway 访问权限的机制 APIs。

  有关资源策略的更多信息，请参阅*《API Gateway 开发人员指南》*中的[使用 API Gateway 资源策略控制 API 的访问权限](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-resource-policies.html)。有关资源策略的示例，请参阅 [的资源策略示例 AWS SAM](serverless-controlling-access-to-apis-resource-policies.md)。
+ **OAuth 2.0/JWT 授权者** [— 你可以作 JWTs 为 OpenID C [onnect (OIDC)](https://openid.net/specs/openid-connect-core-1_0.html) 和 OAuth 2.0 框架的一部分来控制对你的访问权限。](https://oauth.net/2/) APIsAPI Gateway JWTs 会验证客户端通过 API 请求提交的内容，并根据令牌验证和令牌中的范围（可选）允许或拒绝请求。

  只有`AWS::Serverless::HttpApi`资源类型支持 OAuth 2.0/JWT 授权者。

  有关更多信息，请参阅《*API Gateway 开发*者指南》中的 “[ APIs 使用 JWT 授权者控制 HTTP 访问权限](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html)”。有关示例，请参阅[OAuth 2.0/JWT 授权方示例 AWS SAM](serverless-controlling-access-to-apis-oauth2-authorizer.md)。

## 选择控制访问的机制
<a name="serverless-controlling-access-to-apis-choices"></a>

您选择用于控制 API Gateway 访问权限的机制 APIs 取决于几个因素。例如，如果您有一个未设置授权或访问控制的全新项目，那么 Amazon Cognito 用户群体可能是您的最佳选择。这是因为在设置用户群体时，还会自动设置身份验证和访问控制。

但是，如果应用程序已经设置了身份验证，那么使用 Lambda 授权方可能是您的最佳选择。这是因为您可以调用现有的身份验证服务并根据响应返回策略文档。此外，如果您的应用程序需要用户群体不支持的自定义身份验证或访问控制逻辑，那么 Lambda 授权方可能是您的最佳选择。

选择使用哪种机制后，请参阅中的[示例](#serverless-controlling-access-to-apis-examples)相应部分，了解如何使用该机制 AWS SAM 来配置您的应用程序。

## 自定义错误响应
<a name="serverless-controlling-access-to-apis-responses"></a>

您可以使用 AWS SAM 自定义某些 API Gateway 错误响应的内容。仅 `AWS::Serverless::Api` 资源类型支持自定义 API Gateway 响应。

有关 API Gateway 响应的更多信息，请参阅*《API Gateway 开发人员指南》*中的 [API Gateway 中的网关响应](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-gatewayResponse-definition.html)。有关自定义响应的示例，请参阅 [的自定义响应示例 AWS SAM](serverless-controlling-access-to-apis-customize-response.md)。

## 示例
<a name="serverless-controlling-access-to-apis-examples"></a>
+ [Lambda 授权方示例 AWS SAM](serverless-controlling-access-to-apis-lambda-authorizer.md)
+ [的 IAM 权限示例 AWS SAM](serverless-controlling-access-to-apis-permissions.md)
+ [Amazon Cognito 用户池示例 AWS SAM](serverless-controlling-access-to-apis-cognito-user-pool.md)
+ [的 API 密钥示例 AWS SAM](serverless-controlling-access-to-apis-keys.md)
+ [的资源策略示例 AWS SAM](serverless-controlling-access-to-apis-resource-policies.md)
+ [OAuth 2.0/JWT 授权方示例 AWS SAM](serverless-controlling-access-to-apis-oauth2-authorizer.md)
+ [的自定义响应示例 AWS SAM](serverless-controlling-access-to-apis-customize-response.md)

# Lambda 授权方示例 AWS SAM
<a name="serverless-controlling-access-to-apis-lambda-authorizer"></a>

`AWS::Serverless::Api` 资源类型支持两种类型的 Lambda 授权方：`TOKEN` 授权方和 `REQUEST` 授权方。`AWS::Serverless::HttpApi` 资源类型仅支持 `REQUEST` 授权方。下面是每个类型的示例。

## Lambda `TOKEN` 授权方示例 (AWS::Serverless::Api)
<a name="serverless-controlling-access-to-apis-lambda-token-authorizer"></a>

您可以 APIs 通过在模板中定义 Lambda `TOKEN` 授权机构来控制对您的访问权限。 AWS SAM 为此，您需要使用 [ApiAuth](sam-property-api-apiauth.md) 数据类型。

以下是 Lambda `TOKEN` 授权方的示例 AWS SAM 模板部分：

**注意**  
在以下示例中，SAM `FunctionRole` 是隐式生成的。

```
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        DefaultAuthorizer: MyLambdaTokenAuthorizer
        Authorizers:
          MyLambdaTokenAuthorizer:
            FunctionArn: !GetAtt MyAuthFunction.Arn

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: index.handler
      Runtime: nodejs12.x
      Events:
        GetRoot:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: get

  MyAuthFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: authorizer.handler
      Runtime: nodejs12.x
```

有关 Lambda 授权方的更多信息，请参阅*《API Gateway 开发人员指南》*中的[使用 API Gateway Lambda 授权方](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html)。

## Lambda `REQUEST` 授权方示例 (AWS::Serverless::Api)
<a name="serverless-controlling-access-to-apis-lambda-request-authorizer"></a>

您可以 APIs 通过在模板中定义 Lambda `REQUEST` 授权机构来控制对您的访问权限。 AWS SAM 为此，您需要使用 [ApiAuth](sam-property-api-apiauth.md) 数据类型。

以下是 Lambda `REQUEST` 授权方的示例 AWS SAM 模板部分：

```
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        DefaultAuthorizer: MyLambdaRequestAuthorizer
        Authorizers:
          MyLambdaRequestAuthorizer:
            FunctionPayloadType: REQUEST
            FunctionArn: !GetAtt MyAuthFunction.Arn
            Identity:
              QueryStrings:
                - auth

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: index.handler
      Runtime: nodejs12.x
      Events:
        GetRoot:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: get

  MyAuthFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: authorizer.handler
      Runtime: nodejs12.x
```

有关 Lambda 授权方的更多信息，请参阅*《API Gateway 开发人员指南》*中的[使用 API Gateway Lambda 授权方](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html)。

## Lambda 授权方示例 (AWS::Serverless::HttpApi)
<a name="serverless-controlling-access-to-apis-lambda-authorizer-httpapi"></a>

您可以 APIs 通过在模板中定义 Lambda 授权机构来控制对 HTTP 的访问。 AWS SAM 为此，您需要使用 [HttpApiAuth](sam-property-httpapi-httpapiauth.md) 数据类型。

以下是 Lambda 授权方的示例 AWS SAM 模板部分：

```
Resources:
  MyApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      StageName: Prod
      Auth:
        DefaultAuthorizer: MyLambdaRequestAuthorizer
        Authorizers:
          MyLambdaRequestAuthorizer:
            FunctionArn: !GetAtt MyAuthFunction.Arn
            FunctionInvokeRole: !GetAtt MyAuthFunctionRole.Arn
            Identity:
              Headers:
                - Authorization
            AuthorizerPayloadFormatVersion: 2.0
            EnableSimpleResponses: true

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: index.handler
      Runtime: nodejs12.x
      Events:
        GetRoot:
          Type: HttpApi
          Properties:
            ApiId: !Ref MyApi
            Path: /
            Method: get
            PayloadFormatVersion: "2.0"

  MyAuthFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: authorizer.handler
      Runtime: nodejs12.x
```

# 的 IAM 权限示例 AWS SAM
<a name="serverless-controlling-access-to-apis-permissions"></a>

您可以 APIs 通过在 AWS SAM 模板中定义 IAM 权限来控制对您的访问权限。为此，您需要使用 [ApiAuth](sam-property-api-apiauth.md) 数据类型。

以下是用于 IAM 权限的示例 AWS SAM 模板：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Description: 'API with IAM authorization'
      Auth:
        DefaultAuthorizer: AWS_IAM #sets AWS_IAM auth for all methods in this API
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: python3.10
      Events:
        GetRoot:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: get
      InlineCode: |
        def handler(event, context):
          return {'body': 'Hello World!', 'statusCode': 200}
```

有关 IAM 权限的更多信息，请参阅*《API Gateway 开发人员指南》*中的[控制调用 API 的访问权限](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-control-access-using-iam-policies-to-invoke-api.html)。

# Amazon Cognito 用户池示例 AWS SAM
<a name="serverless-controlling-access-to-apis-cognito-user-pool"></a>

您可以 APIs 通过在模板中定义 Amazon Cognito 用户池来控制对您的 AWS SAM 访问权限。为此，您需要使用 [ApiAuth](sam-property-api-apiauth.md) 数据类型。

以下是用户池的示例 AWS SAM 模板部分：

```
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Cors: "'*'"
      Auth:
        DefaultAuthorizer: MyCognitoAuthorizer
        Authorizers:
          MyCognitoAuthorizer:
            UserPoolArn: !GetAtt MyCognitoUserPool.Arn

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Handler: lambda.handler
      Runtime: nodejs12.x
      Events:
        Root:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: GET

  MyCognitoUserPool:
    Type: AWS::Cognito::UserPool
    Properties:
      UserPoolName: !Ref CognitoUserPoolName
      Policies:
        PasswordPolicy:
          MinimumLength: 8
      UsernameAttributes:
        - email
      Schema:
        - AttributeDataType: String
          Name: email
          Required: false
  
  MyCognitoUserPoolClient:
    Type: AWS::Cognito::UserPoolClient
    Properties:
      UserPoolId: !Ref MyCognitoUserPool
      ClientName: !Ref CognitoUserPoolClientName
      GenerateSecret: false
```

有关 Amazon Cognito 用户群体的更多信息，请参阅*《API Gateway 开发人员指南》*中的[使用 Amazon Cognito 用户群体作为授权方控制对 REST API 的访问](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html)。

# 的 API 密钥示例 AWS SAM
<a name="serverless-controlling-access-to-apis-keys"></a>

您可以 APIs 通过在 AWS SAM 模板中要求 API 密钥来控制对您的访问权限。为此，您需要使用 [ApiAuth](sam-property-api-apiauth.md) 数据类型。

以下是 API 密钥的示例 AWS SAM 模板部分：

```
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      Auth:
        ApiKeyRequired: true # sets for all methods

  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: .
      Handler: index.handler
      Runtime: nodejs12.x
      Events:
        ApiKey:
          Type: Api
          Properties:
            RestApiId: !Ref MyApi
            Path: /
            Method: get
            Auth:
              ApiKeyRequired: true
```

有关 API 密钥的更多信息，请参阅*《API Gateway 开发人员指南》*中的[创建和使用带 API 密钥的使用计划](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-api-usage-plans.html)。

# 的资源策略示例 AWS SAM
<a name="serverless-controlling-access-to-apis-resource-policies"></a>

您可以 APIs 通过在 AWS SAM 模板中附加资源策略来控制对您的访问权限。为此，您需要使用 [ApiAuth](sam-property-api-apiauth.md) 数据类型。

以下是私有 API 的示例 AWS SAM 模板。私有 API 必须具有资源策略才能部署。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  MyPrivateApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      EndpointConfiguration: PRIVATE  # Creates a private API. Resource policies are required for all private APIs.
      Auth:
        ResourcePolicy:
          CustomStatements: 
            - Effect: 'Allow'
              Action: 'execute-api:Invoke'
              Resource: ['execute-api:/*/*/*']
              Principal: '*'
            - Effect: 'Deny'
              Action: 'execute-api:Invoke'
              Resource: ['execute-api:/*/*/*']
              Principal: '*'
  MyFunction:
    Type: 'AWS::Serverless::Function'
    Properties:
      InlineCode: |
        def handler(event, context):
          return {'body': 'Hello World!', 'statusCode': 200}
      Handler: index.handler
      Runtime: python3.10
      Events:
        AddItem:
          Type: Api
          Properties:
            RestApiId: 
              Ref: MyPrivateApi
            Path: /
            Method: get
```

有关资源策略的更多信息，请参阅*《API Gateway 开发人员指南》*中的[使用 API Gateway 资源策略控制 API 的访问权限](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-resource-policies.html)。有关私有化的更多信息 APIs，请参阅 [API Gateway 开发者指南中的在 Amazon API Gateway 中创建私](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-private-apis.html)*有 API*。

# OAuth 2.0/JWT 授权方示例 AWS SAM
<a name="serverless-controlling-access-to-apis-oauth2-authorizer"></a>

 JWTs [作为 [OpenID Connect (OIDC) 和](https://openid.net/specs/openid-connect-core-1_0.html) 2.0 框架的一部分，你可以控制对你的 APIs 使用的访问权限。OAuth ](https://oauth.net/2/)为此，您需要使用 [HttpApiAuth](sam-property-httpapi-httpapiauth.md) 数据类型。

以下是 OAuth 2.0/JWT 授权方的示例 AWS SAM 模板部分：

```
Resources:
  MyApi:
    Type: AWS::Serverless::HttpApi
    Properties:
      Auth:
        Authorizers:
          MyOauth2Authorizer:
            AuthorizationScopes:
              - scope
            IdentitySource: $request.header.Authorization
            JwtConfiguration:
              audience:
                - audience1
                - audience2
              issuer: "https://www.example.com/v1/connect/oidc"
        DefaultAuthorizer: MyOauth2Authorizer
      StageName: Prod
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./src
      Events:
        GetRoot:
          Properties:
            ApiId: MyApi
            Method: get
            Path: /
            PayloadFormatVersion: "2.0"
          Type: HttpApi
      Handler: index.handler
      Runtime: nodejs12.x
```

*有关 OAuth 2.0/JWT 授权方的更多信息，请参阅《API Gateway 开发者指南》[中的 “ APIs 使用 JWT 授权者控制 HTTP 访问权限](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-jwt-authorizer.html)”。*

# 的自定义响应示例 AWS SAM
<a name="serverless-controlling-access-to-apis-customize-response"></a>

您可以通过在 AWS SAM 模板中定义响应标头来自定义某些 API Gateway 错误响应。为此，您需要使用[网关响应对象](https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#gateway-response-object)数据类型。

以下是为`DEFAULT_5XX`错误创建自定义响应的示例 AWS SAM 模板。

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
  MyApi:
    Type: AWS::Serverless::Api
    Properties:
      StageName: Prod
      GatewayResponses:
        DEFAULT_5XX:
          ResponseParameters:
            Headers:
              Access-Control-Expose-Headers: "'WWW-Authenticate'"
              Access-Control-Allow-Origin: "'*'"
              ErrorHeader: "'MyCustomErrorHeader'"
          ResponseTemplates:
            application/json: "{\"message\": \"Error on the $context.resourcePath resource\" }"
              
  GetFunction:
    Type: AWS::Serverless::Function
    Properties:
      Runtime: python3.10
      Handler: index.handler
      InlineCode: |
        def handler(event, context):
          raise Exception('Check out the new response!')
      Events:
        GetResource:
          Type: Api
          Properties:
            Path: /error
            Method: get
            RestApiId: !Ref MyApi
```

有关 API Gateway 响应的更多信息，请参阅*《API Gateway 开发人员指南》*中的 [API Gateway 中的网关响应](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-gatewayResponse-definition.html)。

# 使用带有 Lambda 层的 Lambda 层来提高效率 AWS SAM
<a name="serverless-sam-cli-layers"></a>

使用 AWS SAM，您可以在无服务器应用程序中包含图层。 AWS Lambda 层允许您将代码从 Lambda 函数提取到 Lambda 层中，然后可以在多个 Lambda 函数中使用该层。这样做可以让您缩小部署包的大小，将核心函数逻辑与依赖项分开，并在多个函数之间共享依赖项。有关层的更多信息，请参阅《AWS Lambda 开发人员指南》**中的 [Lambda 层](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)。

本主题提供有关以下内容的信息：
+ 在应用程序中包含层
+ 如何在本地缓存层

有关构建自定义层的更多信息，请参阅 [在中构建 Lambda 图层 AWS SAM](building-layers.md)。

## 在应用程序中包含层
<a name="including-layers"></a>

要在应用程序中包含层，请使用 [AWS::Serverless::Function](sam-resource-function.md) 资源类型的 `Layers` 属性。

以下是带有包含层的 Lambda 函数的示例 AWS SAM 模板：

```
ServerlessFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: .
    Handler: my_handler
    Runtime: Python3.7
    Layers:
        - <LayerVersion ARN>
```

## 如何在本地缓存层
<a name="local-testing-with-layers"></a>

当您使用其中一个 `sam local` 命令调用函数时，函数的层包会被下载并缓存在本地主机上。

下表显示不同操作系统的默认缓存目录位置。


****  

| OS | 位置 | 
| --- | --- | 
| Windows 7 | C:\$1Users\$1<user>\$1AppData\$1Roaming\$1AWS SAM | 
| Windows 8 | C:\$1Users\$1<user>\$1AppData\$1Roaming\$1AWS SAM | 
| Windows 10 | C:\$1Users\$1<user>\$1AppData\$1Roaming\$1AWS SAM | 
| macOS | \$1/.aws-sam/layers-pkg | 
| Unix | \$1/.aws-sam/layers-pkg | 

缓存软件包后， AWS SAM CLI 会将层叠加到用于调用函数的 Docker 映像上。 AWS SAMCLI生成其构建的图像以及缓存中保存 LayerVersions 的图像的名称。您可以在以下部分找到有关架构的更多详细信息。

要检查叠加层，请执行以下命令在要检查的映像中启动 bash 会话：

```
docker run -it --entrypoint=/bin/bash samcli/lambda:<Tag following the schema outlined in Docker Image Tag Schema> -i
```

**层缓存目录名称架构**

给 LayerVersionArn 定模板中定义的，会从 ARN 中 AWS SAMCLI提取 LayerName 和版本。它会创建一个目录，用于存放名为 `LayerName-Version-<first 10 characters of sha256 of ARN>` 的层内容。

示例：

```
ARN = arn:aws:lambda:us-west-2:111111111111:layer:myLayer:1
Directory name = myLayer-1-926eeb5ff1
```

**Docker 映像标签架构**

要计算唯一图层哈希，请将所有唯一的图层名称与分隔符 “-” 合并，取 SHA256 哈希，然后取前 10 个字符。

示例：

```
ServerlessFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: .
    Handler: my_handler
    Runtime: Python3.7
    Layers:
        - arn:aws:lambda:us-west-2:111111111111:layer:myLayer:1
        - arn:aws:lambda:us-west-2:111111111111:layer:mySecondLayer:1
```

唯一名称的计算方法与层缓存目录名称架构相同：

```
arn:aws:lambda:us-west-2:111111111111:layer:myLayer:1 = myLayer-1-926eeb5ff1
arn:aws:lambda:us-west-2:111111111111:layer:mySecondLayer:1 = mySecondLayer-1-6bc1022bdf
```

要计算唯一层哈希，请将所有唯一的层名称合并，分隔符为 '-'，取 sha256 哈希，然后取前 25 个字符：

```
myLayer-1-926eeb5ff1-mySecondLayer-1-6bc1022bdf = 2dd7ac5ffb30d515926aef
```

然后将此值与函数的运行时和架构合并，分隔符为 '-'：

```
python3.7-x86_64-2dd7ac5ffb30d515926aefffd
```

# 使用嵌套应用程序重用代码和资源 AWS SAM
<a name="serverless-sam-template-nested-applications"></a>

无服务器应用程序可以包含一个或多个**嵌套应用程序**。嵌套应用程序是大型应用程序的一部分，可以作为独立构件或大型应用程序的组件进行打包和部署。嵌套应用程序允许您将常用代码转换为其自己的应用程序，然后可以在大型无服务器应用程序或多个无服务器应用程序中重复使用。

随着无服务器架构的发展，通常会出现常见的模式，其中在多个应用程序模板中定义相同组件。嵌套应用程序允许您在单独的 AWS SAM 模板中重复使用常用代码、功能、资源和配置，从而只能维护来自单一来源的代码。这可以减少重复的代码和配置。此外，这种模块化方法简化了开发过程，增强了代码组织，并促进了无服务器应用程序之间的一致性。使用嵌套应用程序，您可以更加专注于应用程序特有的业务逻辑。

要在无服务器应用程序中定义嵌套应用程序，请使用 [AWS::Serverless::Application](sam-resource-application.md) 资源类型。

您可以从以下两个来源定义嵌套应用程序：
+ **AWS Serverless Application Repository 应用程序** – 您可以使用您的账户在 AWS Serverless Application Repository中可用的应用程序来定义嵌套应用程序。它们可以是您账户中的*私有*应用程序、与您的账户*私下共享*的应用程序或在 AWS Serverless Application Repository中*公开共享*的应用程序。有关不同部署权限级别的更多信息，请参阅*《AWS Serverless Application Repository 开发人员指南》*中的[应用程序部署权限](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/serverless-app-consuming-applications.html#application-deployment-permissions)和[发布应用程序](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/serverless-app-publishing-applications.html)。
+ **本地应用程序** – 您可以使用存储在本地文件系统上的应用程序来定义嵌套应用程序。

有关如何在无服务器应用程序中使用 AWS SAM 定义这两种类型的嵌套应用程序的详细信息，请参阅以下各节。

**注意**  
无服务器应用程序中可以嵌套的最大应用程序数量为 200。  
嵌套应用程序可以拥有的最大参数数量为 60。

## 从中定义嵌套应用程序 AWS Serverless Application Repository
<a name="serverless-sam-template-nested-applications-how-to-serverlessrepo"></a>

您可以使用 AWS Serverless Application Repository中可用的应用程序来定义嵌套应用程序。您还可以使用 AWS Serverless Application Repository存储和分发包含嵌套应用程序的应用程序。要查看中嵌套应用程序的详细信息 AWS Serverless Application Repository，您可以使用 AWS 软件开发工具包 AWS CLI、或 Lambda 控制台。

要在无服务器应用程序的 AWS SAM 模板中定义托管 AWS Serverless Application Repository 在中的应用程序，请使用每个 AWS Serverless Application Repository 应用程序详细信息页面上的 “**复制为 SAM 资源**” 按钮。为此，请按照以下步骤操作：

1. 请确保您已登录 AWS 管理控制台。

1. 使用《*AWS Serverless Application Repository 开发人员指南*》 AWS Serverless Application Repository 的 “[浏览、搜索和部署应用程序” 部分中的步骤，找到要嵌套的应用程序](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/serverless-app-consuming-applications.html#browse-and-search-applications                         )。

1. 选择**复制为 SAM 资源**按钮。您正在查看的应用程序的 SAM 模板部分现在位于剪贴板中。

1. 将 SAM 模板部分粘贴到要嵌套在此应用程序中的应用程序的 SAM 模板文件的 `Resources:` 部分。

以下是托管在 AWS Serverless Application Repository中的嵌套应用程序的 SAM 模板部分示例：

```
Transform: AWS::Serverless-2016-10-31

Resources:
  applicationaliasname:
    Type: AWS::Serverless::Application
    Properties:
      Location:
        ApplicationId: arn:aws:serverlessrepo:us-east-1:123456789012:applications/application-alias-name
        SemanticVersion: 1.0.0
      Parameters:
        # Optional parameter that can have default value overridden
        # ParameterName1: 15 # Uncomment to override default value
        # Required parameter that needs value to be provided
        ParameterName2: YOUR_VALUE
```

如果没有必需的参数设置，则可以省略模板的 `Parameters:` 部分。

**重要**  
包含托管在中的嵌套应用程序的应用程序会 AWS Serverless Application Repository 继承嵌套应用程序的共享限制。  
例如，假设一个应用程序是公开共享的，但它包含一个仅与创建父应用程序的 AWS 账户私下共享的嵌套应用程序。在这种情况下，如果您的 AWS 账户无权部署嵌套应用程序，则无法部署父应用程序。有关应用程序部署权限的更多信息，请参阅*《AWS Serverless Application Repository 开发人员指南》*中的[应用程序部署权限](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/serverless-app-consuming-applications.html#application-deployment-permissions)和[发布应用程序](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/serverless-app-publishing-applications.html)。

## 从本地文件系统定义嵌套应用程序
<a name="serverless-sam-template-nested-applications-how-to-local-app"></a>

您可以使用存储在本地文件系统上的应用程序来定义嵌套应用程序。为此，您可以指定存储在本地文件系统中的 AWS SAM 模板文件的路径。

以下是嵌套本地应用程序的 SAM 模板部分示例：

```
Transform: AWS::Serverless-2016-10-31

Resources:
  applicationaliasname:
    Type: AWS::Serverless::Application
    Properties:
      Location: ../my-other-app/template.yaml
      Parameters:
        # Optional parameter that can have default value overridden
        # ParameterName1: 15 # Uncomment to override default value
        # Required parameter that needs value to be provided
        ParameterName2: YOUR_VALUE
```

如果没有参数设置，则可以省略模板的 `Parameters:` 部分。

## 部署嵌套应用程序
<a name="serverless-sam-templates-nested-applications-deploying"></a>

您可以使用 AWS SAM CLI 命令 `sam deploy` 部署嵌套应用程序。有关更多详细信息，请参阅[使用部署您的应用程序和资源 AWS SAM](serverless-deploying.md)。

**注意**  
部署包含嵌套应用程序的应用程序时，必须确认其包含嵌套应用程序。您可以通过传递`CAPABILITY_AUTO_EXPAND`给 [CreateCloudFormationChangeSet API](https://docs.aws.amazon.com/goto/WebAPI/serverlessrepo-2017-09-08/CreateCloudFormationChangeSet) 或使用[https://docs.aws.amazon.com/cli/latest/reference/serverlessrepo/create-cloud-formation-change-set.html](https://docs.aws.amazon.com/cli/latest/reference/serverlessrepo/create-cloud-formation-change-set.html) AWS CLI 命令来执行此操作。  
有关确认嵌套应用程序的更多信息，请参阅*《AWS Serverless Application Repository 开发人员指南》*中的[在部署应用程序时确认 IAM 角色、资源策略和嵌套应用程序](https://docs.aws.amazon.com/serverlessrepo/latest/devguide/acknowledging-application-capabilities.html)。

# 使用 “ EventBridge 调度器” 管理基于时间的事件 AWS SAM
<a name="using-eventbridge-scheduler"></a>

本主题中的内容详细介绍了什么是 Amazon S EventBridge cheduler、 AWS SAM 提供哪些支持、如何创建计划程序事件，以及在创建计划程序事件时可以参考的示例。

## 什么是 Amazon EventBridge 日程安排？
<a name="using-eventbridge-scheduler-intro"></a>

使用 EventBridge 日程安排器在 AWS SAM 模板中安排活动。Amazon S EventBridge cheduler 是一项计划服务，允许您在所有 AWS 服务中创建、启动和管理数千万个事件和任务。此服务对于与时间相关的事件特别有用。您可以使用它来计划事件和基于时间的重复调用。它还支持一次性事件以及带有开始和结束时间的 rate 和 chron 表达式。

要了解有关 Amazon EventBridge 日程安排器的更多信息，请参阅[什么是亚马逊 EventBridge 日程安排](https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html)？ 在《*EventBridge 日程安排器用户指南》*中。

**Topics**
+ [

## 什么是 Amazon EventBridge 日程安排？
](#using-eventbridge-scheduler-intro)
+ [

## EventBridge 中的调度器支持 AWS SAM
](#using-eventbridge-scheduler-sam-support)
+ [

## 在中创建 EventBridge 调度器事件 AWS SAM
](#using-eventbridge-scheduler-sam-create)
+ [

## 示例
](#using-eventbridge-scheduler-examples)
+ [

## 了解详情
](#using-eventbridge-scheduler-learn)

## EventBridge 中的调度器支持 AWS SAM
<a name="using-eventbridge-scheduler-sam-support"></a>

 AWS Serverless Application Model (AWS SAM) 模板规范提供了一种简单的简短语法，您可以使用该语法通过 S EventBridge cheduler 为 AWS Lambda 和安排事件。 AWS Step Functions

## 在中创建 EventBridge 调度器事件 AWS SAM
<a name="using-eventbridge-scheduler-sam-create"></a>

在 AWS SAM 模板中将该`ScheduleV2`属性设置为事件类型，以定义您的 EventBridge 日程安排器事件。此属性支持 `AWS::Serverless::Function` 和 `AWS::Serverless::StateMachine` 资源类型。

```
MyFunction:
  Type: AWS::Serverless::Function
  Properties:
    Events:
      CWSchedule:
        Type: ScheduleV2
        Properties:
          ScheduleExpression: 'rate(1 minute)'
          Name: TestScheduleV2Function
          Description: Test schedule event
                    
MyStateMachine:
  Type: AWS::Serverless::StateMachine
  Properties:
    Events:
      CWSchedule:
        Type: ScheduleV2
        Properties:
          ScheduleExpression: 'rate(1 minute)'
          Name: TestScheduleV2StateMachine
          Description: Test schedule event
```

EventBridge 调度器事件调度还支持未处理事件*的死信队列 (DLQ)*。*有关死信队列的更多信息，请参阅《日程安排器用户指南》中的[为日 EventBridge 程安排器配置死信队列](https://docs.aws.amazon.com/scheduler/latest/UserGuide/configuring-schedule-dlq.html)。EventBridge *

指定 DLQ ARN 后 AWS SAM ，配置调度程序计划向 DLQ 发送消息的权限。如果未指定 DLQ ARN AWS SAM ，则将创建 DLQ 资源。

## 示例
<a name="using-eventbridge-scheduler-examples"></a>

### 使用定义 EventBridge 调度器事件的基本示例 AWS SAM
<a name="using-eventbridge-scheduler-examples-example1"></a>

```
Transform: AWS::Serverless-2016-10-31
Resources:
  MyLambdaFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: python3.8
      InlineCode: |
        def handler(event, context):
            print(event)
            return {'body': 'Hello World!', 'statusCode': 200}
      MemorySize: 128
      Events:
        Schedule:
          Type: ScheduleV2
          Properties:
            ScheduleExpression: rate(1 minute)
            Input: '{"hello": "simple"}'
 
  MySFNFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: index.handler
      Runtime: python3.8
      InlineCode: |
        def handler(event, context):
            print(event)
            return {'body': 'Hello World!', 'statusCode': 200}
      MemorySize: 128
 
  StateMachine:
    Type: AWS::Serverless::StateMachine
    Properties:
      Type: STANDARD
      Definition:
        StartAt: MyLambdaState
        States:
          MyLambdaState:
            Type: Task
            Resource: !GetAtt MySFNFunction.Arn
            End: true
      Policies:
        - LambdaInvokePolicy:
            FunctionName: !Ref MySFNFunction
      Events:
        Schedule:
          Type: ScheduleV2
          Properties:
            ScheduleExpression: rate(1 minute)
            Input: '{"hello": "simple"}'
```

## 了解详情
<a name="using-eventbridge-scheduler-learn"></a>

要了解有关定义`ScheduleV2` EventBridge 调度器属性的更多信息，请参阅：
+ 用于 `AWS::Serverless::Function` 的 [ScheduleV2](sam-property-function-schedulev2.md)。
+ 用于 `AWS::Serverless::StateMachine` 的 [ScheduleV2](sam-property-statemachine-statemachineschedulev2.md)。

# 使用编排资源 AWS SAM AWS Step Functions
<a name="serverless-step-functions-in-sam"></a>

您可以使用[AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/)来编排 AWS Lambda 函数和其他 AWS 资源，以形成复杂而强大的工作流程。Step Functions 告诉您的应用程序何时以及在什么条件下使用您的 AWS 资源（如 AWS Lambda 函数）。这简化了形成复杂而稳健的工作流的过程。使用 [AWS::Serverless::StateMachine](sam-resource-statemachine.md)，您可以定义工作流中的各个步骤，关联每个步骤中的资源，然后将这些步骤排列在一起。您还可以在需要的地方添加转换和条件。这简化了制定复杂而稳健的工作流的过程。

**注意**  
要管理包含 Step Functions 状态机的 AWS SAM 模板，必须使用 0.52.0 或更高版本的。 AWS SAMCLI要检查您拥有的版本，请执行命令 `sam --version`。

Step Functions 是基于[任务](https://docs.aws.amazon.com/step-functions/latest/dg/amazon-states-language-task-state.html)和[状态机](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-states.html)的概念。您使用基于 JSON 的 [Amazon States Language](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html) 定义状态机。[Step Functions 控制台](https://console.aws.amazon.com/states/home?region=us-east-1#/)显示状态机结构的图形视图，因此您能够直观检查状态机逻辑和监控执行。

借助 AWS Serverless Application Model (AWS SAM) 中的 Step Functions 支持，你可以执行以下操作：
+ 定义状态机，可以直接在 AWS SAM 模板中定义，也可以在单独的文件中定义 
+ 通过 AWS SAM 策略模板、内联策略或托管策略创建状态机执行角色 
+ 使用 API Gateway 或 Amazon EventBridge 事件、在 AWS SAM 模板内按计划或 APIs 直接调用触发状态机执行
+ 使用可用的 [AWS SAM 策略模板](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-templates.html)创建常见的 Step Functions 开发模式。

## 示例
<a name="serverless-step-functions-in-sam-example"></a>

以下 AWS SAM 模板文件中的示例片段在定义文件中定义了 Step Functions 状态机。请注意，该 `my_state_machine.asl.json` 文件必须以 [Amazon States Language](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-amazon-states-language.html) 编写。

```
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: Sample SAM template with Step Functions State Machine

Resources:
  MyStateMachine:
    Type: AWS::Serverless::StateMachine
    Properties:
      DefinitionUri: statemachine/my_state_machine.asl.json
      ...
```

要下载包含 Step Functions 状态机的示例 AWS SAM 应用程序，请参阅《*AWS Step Functions 开发者指南》 AWS SAM*中的 “[使用创建 Step Functions 状态机](https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-state-machine-using-sam.html)”。

## 更多信息
<a name="serverless-step-functions-in-sam-more-information"></a>

要了解有关 Step Functions 及其与之配合使用的更多信息 AWS SAM，请参阅以下内容：
+ [AWS Step Functions 的工作原理](https://docs.aws.amazon.com/step-functions/latest/dg/how-step-functions-works.html)
+ [AWS Step Functions 和 AWS Serverless Application Model](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-sam-sfn.html)
+ [教程：使用创建 Step Functions 状态机 AWS SAM](https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-state-machine-using-sam.html)
+ [AWS SAM 规格： AWS::Serverless::StateMachine](sam-resource-statemachine.md)

# 为您的 AWS SAM 应用程序设置代码签名
<a name="authoring-codesigning"></a>

为确保仅部署可信代码，您可以使用 AWS SAM 对无服务器应用程序启用代码签名。对代码进行签名有助于确保代码在签名后未被更改，并且只有来自可信发布者的签名代码包才能在您的 Lambda 函数中运行。这有助于组织摆脱在部署管线中构建网关守卫组件的负担。

有关代码签名的更多信息，请参阅《AWS Lambda 开发人员指南》**中的[配置 Lambda 函数的代码签名](https://docs.aws.amazon.com/lambda/latest/dg/configuration-codesigning.html)。

在为无服务器应用程序配置代码签名之前，必须使用 S AWS igner 创建签名配置文件。您可以将此签名配置文件用于以下任务：

1. **创建代码签名配置** – 声明 [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-codesigningconfig.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-codesigningconfig.html) 资源以指定可信发布者的签名配置文件并设置验证检查的策略操作。您可以在与无服务器函数相同的 AWS SAM 模板中声明此对象，也可以在不同的模板中声明此对象，也可以在 AWS SAM 模板中声明此对象 CloudFormation 。然后，您可以使用 [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-codesigningconfig.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-codesigningconfig.html) 资源的 Amazon 资源名称（ARN）指定该函数的 [https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-codesigningconfigarn](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-resource-function.html#sam-function-codesigningconfigarn) 属性，从而为无服务器函数启用代码签名。

1. **签署代码** – 使用带 `--signing-profiles` 选项的 [https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-package.html](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-package.html) 或 [https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-deploy.html](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-deploy.html) 命令。

**注意**  
要使用 `sam package` 或 `sam deploy` 命令成功签署您的代码，必须为这些命令中使用的 Amazon S3 存储桶启用版本控制。如果您使用的是为您 AWS SAM 创建的 Amazon S3 存储桶，则会自动启用版本控制。有关 Amazon S3 存储桶版本控制的更多信息以及在您提供的 Amazon S3 存储桶上启用版本控制的说明，请参阅《Amazon Simple Storage Service 用户指南》**中的[在 Amazon S3 存储桶中使用版本控制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html)。

部署无服务器应用程序时，Lambda 会对您启用代码签名的所有函数执行验证检查。Lambda 还会对这些函数所依赖的任何层执行验证检查。有关 Lambda 验证检查的更多信息，请参阅《AWS Lambda 开发人员指南》**中的[签名验证](https://docs.aws.amazon.com/lambda/latest/dg/configuration-codesigning.html#config-codesigning-valid)。

## 示例
<a name="authoring-codesigning-example"></a>

### 创建签名配置文件
<a name="authoring-codesigning-example-signing-profile"></a>

要创建签名配置文件，请运行以下命令：

```
aws signer put-signing-profile --platform-id "AWSLambda-SHA384-ECDSA" --profile-name MySigningProfile
```

如果上一个命令成功，您将看到签名配置文件的 ARN 已返回。例如：

```
{
    "arn": "arn:aws:signer:us-east-1:111122223333:/signing-profiles/MySigningProfile",
    "profileVersion": "SAMPLEverx",
    "profileVersionArn": "arn:aws:signer:us-east-1:111122223333:/signing-profiles/MySigningProfile/SAMPLEverx"
}
```

`profileVersionArn` 字段包含创建代码签名配置时要使用的 ARN。

### 创建代码签名配置并为函数启用代码签名
<a name="authoring-codesigning-example-configure-trusted-deployments"></a>

以下示例 AWS SAM 模板声明[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-codesigningconfig.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-lambda-codesigningconfig.html)资源并启用 Lambda 函数的代码签名。在此示例中，有一个可信配置文件，如果签名检查失败，则部署将被拒绝。

```
Resources:
  HelloWorld:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.7
      CodeSigningConfigArn: !Ref MySignedFunctionCodeSigningConfig

  MySignedFunctionCodeSigningConfig:
    Type: AWS::Lambda::CodeSigningConfig
    Properties:
      Description: "Code Signing for MySignedLambdaFunction"
      AllowedPublishers:
        SigningProfileVersionArns:
          - MySigningProfile-profileVersionArn
      CodeSigningPolicies:
        UntrustedArtifactOnDeployment: "Enforce"
```

### 签署代码
<a name="authoring-codesigning-example-signing-code"></a>

您可以在打包或部署应用程序时签署代码。使用 `sam package` 或 `sam deploy` 命令指定 `--signing-profiles` 选项，如以下示例命令所示。

在打包应用程序时对函数代码进行签名：

```
sam package --signing-profiles HelloWorld=MySigningProfile --s3-bucket amzn-s3-demo-bucket --output-template-file packaged.yaml
```

在打包应用程序时，对函数代码和函数所依赖的层进行签名：

```
sam package --signing-profiles HelloWorld=MySigningProfile MyLayer=MySigningProfile --s3-bucket amzn-s3-demo-bucket --output-template-file packaged.yaml
```

对函数代码和层进行签名，然后执行部署：

```
sam deploy --signing-profiles HelloWorld=MySigningProfile MyLayer=MySigningProfile --s3-bucket amzn-s3-demo-bucket --template-file packaged.yaml --stack-name --region us-east-1 --capabilities CAPABILITY_IAM
```

**注意**  
要使用 `sam package` 或 `sam deploy` 命令成功签署您的代码，必须为这些命令中使用的 Amazon S3 存储桶启用版本控制。如果您使用的是为您 AWS SAM 创建的 Amazon S3 存储桶，则会自动启用版本控制。有关 Amazon S3 存储桶版本控制的更多信息以及在您提供的 Amazon S3 存储桶上启用版本控制的说明，请参阅《Amazon Simple Storage Service 用户指南》**中的[在 Amazon S3 存储桶中使用版本控制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html)。

## 通过 `sam deploy --guided` 提供签名配置文件
<a name="authoring-codesigning-sam-deploy-guided"></a>

当您使用配置了代码签名的无服务器应用程序运行该`sam deploy --guided`命令时， AWS SAM 会提示您提供用于代码签名的签名配置文件。有关 `sam deploy --guided` 提示的更多信息，请参阅 AWS SAM CLI 命令参考中的 [sam deploy](sam-cli-command-reference-sam-deploy.md)。

# 验证 AWS SAM 模板文件
<a name="serverless-sam-cli-using-validate"></a>

使用 `sam validate` 验证模板。目前，此命令可验证所提供的模板是否为有效的 JSON /YAML。与大多数 AWS SAM CLI 命令一样，默认情况下，它会在当前工作目录中查找 `template.[yaml|yml]` 文件。您可以使用`-t`或`--template`选项指定其他模板 file/location 。

示例：

```
$ sam validate
<path-to-template>/template.yaml is a valid SAM Template
```

**注意**  
该`sam validate`命令需要配置 AWS 凭据。有关更多信息，请参阅 [配置 AWS SAM CLI](using-sam-cli-configure.md)。

# 使用构建您的应用程序 AWS SAM
<a name="serverless-building"></a>

将基础设施即代码 (IaC) 添加到 AWS SAM 模板后，就可以开始使用**sam build**命令构建应用程序了。此命令根据应用程序项目目录中的文件（即 AWS SAM 模板文件、应用程序代码以及任何适用的语言特定文件和依赖项）创建构建构件。这些构建工件为您的无服务器应用程序做好准备，以备应用程序开发的后续步骤，例如本地测试和部署到 AWS 云端。测试和部署都使用构建构件作为输入。

您可以使用 **sam build** 来构建整个无服务器应用程序。此外，您可以创建自定义构建，例如具有特定函数、层或自定义运行时的构建。要详细了解您使用 **sam build** 的方式和原因，请参阅本节中的主题。有关使用该 `sam build` 命令的简介，请参见 [搭建简介 AWS SAM](using-sam-cli-build.md)。

**Topics**
+ [

# 搭建简介 AWS SAM
](using-sam-cli-build.md)
+ [

# 默认版本使用 AWS SAM
](serverless-sam-cli-using-build.md)
+ [

# 使用自定义构建 AWS SAM
](building-lambda-functions.md)

# 搭建简介 AWS SAM
<a name="using-sam-cli-build"></a>

使用 AWS Serverless Application Model Command Line Interface (AWS SAMCLI) `sam build` 命令为开发工作流程中的后续步骤做好准备，例如本地测试或部署到。 AWS 云此命令会创建 `.aws-sam` 目录，该目录将以 `sam local` 和 `sam deploy` 所要求的格式和位置来编排应用程序的结构。
+ 有关简介 AWS SAMCLI，请参阅[那是什么 AWS SAMCLI？](what-is-sam-overview.md#what-is-sam-cli)。
+ 有关 `sam build` 命令选项的列表，请参阅 [sam build](sam-cli-command-reference-sam-build.md)。
+ 有关在典型开发工作流程中使用 `sam build` 的示例，请参阅[第 2 步：构建应用程序](serverless-getting-started-hello-world.md#serverless-getting-started-hello-world-build)。

**注意**  
使用 `sam build` 时，您需要从开发计算机上无服务器应用程序的基本组件开始。这包括 AWS SAM 模板、 AWS Lambda 函数代码以及任何特定于语言的文件和依赖关系。要了解更多信息，请参阅[在中创建您的应用程序 AWS SAM](using-sam-cli-init.md)。

**Topics**
+ [

## 使用 sam build 构建应用程序
](#using-sam-cli-build-apps)
+ [

## 本地测试和部署
](#using-sam-cli-build-test-deploy)
+ [

## 最佳实践
](#using-sam-cli-build-best)
+ [

## sam build 的选项
](#using-sam-cli-build-options)
+ [

## 问题排查
](#using-sam-cli-build-troubleshooting)
+ [

## 示例
](#using-sam-cli-build-examples)
+ [

## 了解详情
](#using-sam-cli-build-learn)

## 使用 sam build 构建应用程序
<a name="using-sam-cli-build-apps"></a>

使用 `sam build` 之前，请考虑配置以下各项：

1. **Lambda 函数和层** - `sam build` 命令可以构建 Lambda 函数和层。要了解有关 Lambda 层的更多信息，请参阅 [在中构建 Lambda 图层 AWS SAM](building-layers.md)。

1. **Lambda 运行时** – *运行时*提供在调用时在执行环境中运行函数的语言特定环境。您可以配置本机运行时和自定义运行时。

   1. **本机运行时** - 在受支持的 Lambda 运行时系统中编写 Lambda 函数，并构建函数以在 AWS 云中使用原生 Lambda 运行时。

   1. **自定义运行时** - 使用任何编程语言编写 Lambda 函数，并使用在 makefile 或第三方生成器（例如 esbuild）中定义的自定义流程来构建运行时。要了解更多信息，请参阅[在中使用自定义运行时构建 Lambda 函数 AWS SAM](building-custom-runtimes.md)。

1. **Lambda 包类型** - Lambda 函数可以打包成以下 Lambda 部署包类型：

   1. **.zip 文件归档** – 包括您的应用程序代码及其依赖项。

   1. **容器印象** – 包括基本操作系统、运行时系统、Lambda 扩展、应用程序代码及其依赖项。

可在使用 `sam init` 初始化应用程序时配置这些应用程序设置。
+ 要了解有关使用 `sam init` 的更多信息，请参阅 [在中创建您的应用程序 AWS SAM](using-sam-cli-init.md)。
+ 要了解有关在应用程序中配置这些设置的更多信息，请参阅 [默认版本使用 AWS SAM](serverless-sam-cli-using-build.md)。

**构建应用程序**

1. `cd` 到项目的根目录。此位置与您的 AWS SAM 模板相同。

   ```
   $ cd sam-app
   ```

1. 运行以下命令：

   ```
   sam-app $ sam build <arguments> <options>
   ```
**注意**  
常用选项是 `--use-container`。要了解更多信息，请参阅[在提供的容器内构建 Lambda 函数](#using-sam-cli-build-options-container)。

   下面是 AWS SAM CLI 输出的一个示例：

   ```
   sam-app $ sam build
   Starting Build use cache
   Manifest file is changed (new hash: 3298f1304...d4d421) or dependency folder (.aws-sam/deps/4d3dfad6-a267-47a6-a6cd-e07d6fae318c) is missing for (HelloWorldFunction), downloading dependencies and copying/building source
   Building codeuri: /Users/.../sam-app/hello_world runtime: python3.12 metadata: {} architecture: x86_64 functions: HelloWorldFunction
   Running PythonPipBuilder:CleanUp
   Running PythonPipBuilder:ResolveDependencies
   Running PythonPipBuilder:CopySource
   Running PythonPipBuilder:CopySource
   
   Build Succeeded
   
   Built Artifacts  : .aws-sam/build
   Built Template   : .aws-sam/build/template.yaml
   
   Commands you can use next
   =========================
   [*] Validate SAM template: sam validate
   [*] Invoke Function: sam local invoke
   [*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
   [*] Deploy: sam deploy --guided
   ```

1.  AWS SAM CLI 会创建 `.aws-sam` 构建目录。以下是示例：

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

根据应用程序的配置， AWS SAM CLI 会执行以下操作：

1. 在 `.aws-sam/build` 目录中下载、安装和组织依赖项。

1. 准备 Lambda 代码。这可能包括编译代码，创建可执行二进制文件，以及构建容器映像。

1. 将构建构件复制到 `.aws-sam` 目录中。格式因应用程序包类型而异。

   1. 对于 .zip 包类型，构件尚未压缩，因此可用于本地测试。使用 `sam deploy` 时， AWS SAM CLI 会压缩应用程序。

   1. 对于容器映像包类型，容器映像将在本地创建，在 `.aws-sam/build.toml` 文件中被引用。

1. 将 AWS SAM 模板复制到`.aws-sam`目录中，并在必要时使用新的文件路径对其进行修改。

以下是构成 `.aws-sam` 目录中的构建构件的主要组件：
+ **构建目录** - 包含在结构上彼此独立的 Lambda 函数和层。这使得 `.aws-sam/build` 目录中的每个函数或层都有唯一的结构。
+ ** AWS SAM 模板**-根据构建过程中的更改使用更新的值进行修改。
+ **build.toml 文件** — 包含使用的编译设置的配置文件。 AWS SAMCLI

## 本地测试和部署
<a name="using-sam-cli-build-test-deploy"></a>

使用 `sam local` 执行本地测试或使用 `sam deploy` 进行部署时， AWS SAM CLI 会执行以下操作：

1. 它首先检查`.aws-sam`目录是否存在以及 AWS SAM 模板是否位于该目录中。如果满足这些条件， AWS SAM CLI 会将该目录视为应用程序的根目录。

1. 如果不满足这些条件，则 AWS SAMCLI会将 AWS SAM 模板的原始位置视为应用程序的根目录。

开发时，如果对原始应用程序文件进行了更改，请在进行本地测试之前运行 `sam build` 以更新 `.aws-sam` 目录。

## 最佳实践
<a name="using-sam-cli-build-best"></a>
+ 不要编辑 `.aws-sam/build` 目录下的任何代码。而是应更新项目文件夹中的原始源代码，然后运行 `sam build` 以更新 `.aws-sam/build` 目录。
+ 修改原始文件时，运行 `sam build` 以更新 `.aws-sam/build` 目录。
+ 您可能希望 AWS SAM CLI 引用项目的原始根目录而不是 `.aws-sam` 目录，例如，在使用 `sam local` 进行开发和测试时。删除`.aws-sam`目录或`.aws-sam`目录中的 AWS SAM 模板，以便将您的原始项目目录 AWS SAMCLI识别为根项目目录。准备就绪后，再次运行 `sam build` 以创建 `.aws-sam` 目录。
+ 运行 `sam build` 时，`.aws-sam/build` 目录每次都会被覆盖。`.aws-sam` 目录不会被覆盖。如果您想要存储文件（例如日志），请将其存储在 `.aws-sam` 中，以防止它们被覆盖。

## sam build 的选项
<a name="using-sam-cli-build-options"></a>

### 构建单个资源
<a name="using-sam-cli-build-options-resource"></a>

提供资源的逻辑 ID，以仅构建该资源。以下是示例：

```
$ sam build HelloWorldFunction
```

要构建嵌套应用程序或堆栈的资源，请使用格式 `<stack-logical-id>/<resource-logical-id>` 提供应用程序或堆栈逻辑 ID 和资源逻辑 ID：

```
$ sam build MyNestedStack/MyFunction
```

### 在提供的容器内构建 Lambda 函数
<a name="using-sam-cli-build-options-container"></a>

通过 `--use-container` 选项可以下载容器映像，并使用下载的映像来构建 Lambda 函数。然后在 `.aws-sam/build.toml` 文件中引用本地容器。

此选项需要安装 Docker。有关说明，请参阅[安装 Docker](install-docker.md)。

以下是该命令的示例：

```
$ sam build --use-container
```

您可以通过 `--build-image` 选项指定要使用的容器映像。以下是示例：

```
$ sam build --use-container --build-image amazon/aws-sam-cli-build-image-nodejs20.x
```

要指定用于单个函数的容器映像，请提供函数逻辑 ID。以下是示例：

```
$ sam build --use-container --build-image Function1=amazon/aws-sam-cli-build-image-python3.12
```

### 传递环境变量给构建容器
<a name="using-sam-cli-build-options-env"></a>

使用 `--container-env-var` 传递环境变量给构建容器。以下是示例：

```
$ sam build --use-container --container-env-var Function1.GITHUB_TOKEN=<token1> --container-env-var GLOBAL_ENV_VAR=<global-token>
```

要传递文件中的环境变量，请使用 `--container-env-var-file` 选项。以下是示例：

```
$ sam build --use-container --container-env-var-file <env.json>
```

`env.json` 文件示例：

```
{
  "MyFunction1": {
    "GITHUB_TOKEN": "TOKEN1"
  },
  "MyFunction2": {
    "GITHUB_TOKEN": "TOKEN2"
  }
}
```

### 加快构建包含多个函数的应用程序
<a name="using-sam-cli-build-options-speed"></a>

在具有多个函数的应用程序上运行 `sam build` 时， AWS SAM CLI 会逐个构建每个函数。要加快构建过程，请使用 `--parallel` 选项。这样可以同时构建所有函数和层。

以下是该命令的示例：

```
$ sam build —-parallel
```

### 通过在源文件夹中构建项目来加快构建时间
<a name="using-sam-cli-build-options-source"></a>

对于受支持的运行时和构建方法，您可以使用 `--build-in-source` 选项直接在源文件夹中生成项目。默认情况下，在临时目录中 AWS SAM CLI构建，其中包括复制源代码和项目文件。使用`--build-in-source`， AWS SAM CLI可以直接在源文件夹中进行构建，无需将文件复制到临时目录，从而加快构建过程。

有关支持的运行时和构建方法的列表，请参阅 `--build-in-source`。

## 问题排查
<a name="using-sam-cli-build-troubleshooting"></a>

要排除故障 AWS SAMCLI，请参阅[AWS SAM CLI 故障排除](sam-cli-troubleshooting.md)。

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

### 构建使用原生运行时和 .zip 包类型的应用程序
<a name="using-sam-cli-build-examples-tutorial1"></a>

对于本示例，请参阅 [教程：使用以下命令部署 Hello World 应用程序 AWS SAM](serverless-getting-started-hello-world.md)。

### 构建使用原生运行时和映像包类型的应用程序
<a name="using-sam-cli-build-examples-image"></a>

首先，运行 `sam init` 以初始化新的应用程序。在交互式流程中，选择 `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
        3 - Serverless API
        4 - Scheduled task
        5 - Standalone function
        6 - Data processing
        7 - Hello World Example With Powertools
        8 - Infrastructure event management
        9 - Serverless Connector Hello World Example
        10 - Multi-step workflow with Connectors
        11 - Lambda EFS example
        12 - DynamoDB Example
        13 - Machine Learning
Template: 1

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

Which runtime would you like to use?
        ...
        10 - java8
        11 - nodejs20.x
        12 - nodejs18.x
        13 - nodejs16.x
        ...
Runtime: 12

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 npm.
We will proceed copying the template using npm.

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: ENTER

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER

Project name [sam-app]: ENTER

Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)

    -----------------------
    Generating application:
    -----------------------
    Name: sam-app
    Base Image: amazon/nodejs18.x-base
    Architectures: x86_64
    Dependency Manager: npm
    Output Directory: .
    Configuration file: sam-app/samconfig.toml

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

初 AWS SAMCLI始化应用程序并创建以下项目目录：

```
sam-app
├── README.md
├── events
│   └── event.json
├── hello-world
│   ├── Dockerfile
│   ├── app.mjs
│   ├── package.json
│   └── tests
│       └── unit
│           └── test-handler.mjs
├── samconfig.toml
└── template.yaml
```

然后，运行 `sam build` 以构建应用程序：

```
sam-app $ sam build
Building codeuri: /Users/.../build-demo/sam-app runtime: None metadata: {'DockerTag': 'nodejs18.x-v1', 'DockerContext': '/Users/.../build-demo/sam-app/hello-world', 'Dockerfile': 'Dockerfile'} architecture: arm64 functions: HelloWorldFunction
Building image for HelloWorldFunction function
Setting DockerBuildArgs: {} for HelloWorldFunction function
Step 1/4 : FROM public.ecr.aws/lambda/nodejs:18
 ---> f5b68038c080
Step 2/4 : COPY app.mjs package*.json ./
 ---> Using cache
 ---> 834e565aae80
Step 3/4 : RUN npm install
 ---> Using cache
 ---> 31c2209dd7b5
Step 4/4 : CMD ["app.lambdaHandler"]
 ---> Using cache
 ---> 2ce2a438e89d
Successfully built 2ce2a438e89d
Successfully tagged helloworldfunction:nodejs18.x-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
```

### 构建包含已编译编程语言的应用程序
<a name="using-sam-cli-build-examples-compiled"></a>

在此示例中，我们使用 Go 运行时构建一个包含 Lambda 函数的应用程序。

首先，使用 `sam init` 初始化新的应用程序，并将应用程序配置为使用 Go：

```
$ sam init

...

Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Multi-step workflow
        3 - Serverless API
        ...
Template: 1

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

Which runtime would you like to use?
        ...
        4 - dotnetcore3.1
        5 - go1.x
        6 - go (provided.al2)
        ...
Runtime: 5

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

Based on your selections, the only dependency manager available is mod.
We will proceed copying the template using mod.

Would you like to enable X-Ray tracing on the function(s) in your application?  [y/N]: ENTER

Would you like to enable monitoring using CloudWatch Application Insights?
For more info, please view https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-application-insights.html [y/N]: ENTER

Project name [sam-app]: ENTER

Cloning from https://github.com/aws/aws-sam-cli-app-templates (process may take a moment)

    -----------------------
    Generating application:
    -----------------------
    Name: sam-app
    Runtime: go1.x
    Architectures: x86_64
    Dependency Manager: mod
    Application Template: hello-world
    Output Directory: .
    Configuration file: sam-app/samconfig.toml
    
    Next steps can be found in the README file at sam-app-go/README.md
        
...
```

初 AWS SAMCLI始化应用程序。下面是应用程序目录结构的示例：

```
sam-app
├── Makefile
├── README.md
├── events
│   └── event.json
├── hello-world
│   ├── go.mod
│   ├── go.sum
│   ├── main.go
│   └── main_test.go
├── samconfig.toml
└── template.yaml
```

引用 `README.md` 文件以明确此应用程序的要求。

```
...
## Requirements
* AWS CLI already configured with Administrator permission
* [Docker installed](https://www.docker.com/community-edition)
* [Golang](https://golang.org)
* SAM CLI - [Install the SAM CLI](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html)
...
```

然后，运行 `sam local invoke` 以测试函数。由于本地计算机上未安装 Go，此命令出错：

```
sam-app $ sam local invoke
Invoking hello-world (go1.x)
Local image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-go1.x
Building image.................................................................................................................................................................................................................................................
Using local image: public.ecr.aws/lambda/go:1-rapid-x86_64.

Mounting /Users/.../Playground/build/sam-app/hello-world as /var/task:ro,delegated inside runtime container
START RequestId: c6c5eddf-042b-4e1e-ba66-745f7c86dd31 Version: $LATEST
fork/exec /var/task/hello-world: no such file or directory: PathError
null
END RequestId: c6c5eddf-042b-4e1e-ba66-745f7c86dd31
REPORT RequestId: c6c5eddf-042b-4e1e-ba66-745f7c86dd31  Init Duration: 0.88 ms  Duration: 175.75 ms Billed Duration: 176 ms Memory Size: 128 MB     Max Memory Used: 128 MB
{"errorMessage":"fork/exec /var/task/hello-world: no such file or directory","errorType":"PathError"}%
```

然后，运行 `sam build` 以构建应用程序。由于本地计算机上未安装 Go，我们遇到错误：

```
sam-app $ sam build
Starting Build use cache
Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../Playground/build/sam-app/hello-world runtime: go1.x metadata: {} architecture: x86_64 functions: HelloWorldFunction

Build Failed
Error: GoModulesBuilder:Resolver - Path resolution for runtime: go1.x of binary: go was not successful
```

虽然我们可以通过配置本地计算机来正确构建函数，但我们改为将 `--use-container` 选项与 `sam build` 结合使用。 AWS SAMCLI下载容器镜像，使用原生镜像构建我们的函数 GoModulesBuilder，然后将生成的二进制文件复制到我们的`.aws-sam/build/HelloWorldFunction`目录中。

```
sam-app $ sam build --use-container
Starting Build use cache
Starting Build inside a container
Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../build/sam-app/hello-world runtime: go1.x metadata: {} architecture: x86_64 functions: HelloWorldFunction

Fetching public.ecr.aws/sam/build-go1.x:latest-x86_64 Docker container image.....................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
Mounting /Users/.../build/sam-app/hello-world as /tmp/samcli/source:ro,delegated inside runtime container
Running GoModulesBuilder:Build

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided
```

以下是 `.aws-sam` 目录的示例：

```
.aws-sam
├── build
│   ├── HelloWorldFunction
│   │   └── hello-world
│   └── template.yaml
├── build.toml
├── cache
│   └── c860d011-4147-4010-addb-2eaa289f4d95
│       └── hello-world
└── deps
```

然后，运行 `sam local invoke`。这样就成功调用了函数：

```
sam-app $ sam local invoke
Invoking hello-world (go1.x)
Local image is up-to-date
Using local image: public.ecr.aws/lambda/go:1-rapid-x86_64.

Mounting /Users/.../Playground/build/sam-app/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated inside runtime container
START RequestId: cfc8ffa8-29f2-49d4-b461-45e8c7c80479 Version: $LATEST
END RequestId: cfc8ffa8-29f2-49d4-b461-45e8c7c80479
REPORT RequestId: cfc8ffa8-29f2-49d4-b461-45e8c7c80479  Init Duration: 1.20 ms  Duration: 1782.46 ms        Billed Duration: 1783 ms        Memory Size: 128 MB     Max Memory Used: 128 MB
{"statusCode":200,"headers":null,"multiValueHeaders":null,"body":"Hello, 72.21.198.67\n"}%
```

## 了解详情
<a name="using-sam-cli-build-learn"></a>

要了解有关使用 `sam build` 命令的更多信息，请参阅以下内容：
+ **[学习 AWS SAM：sam build](https://www.youtube.com/watch?v=fDhYKp4op_g)** — Serverless Land “学习 AWS SAM” 系列开启。YouTube
+ **[学习 AWS SAM \$1 sam build \$1 E3](https://www.youtube.com/watch?v=vsAvRyLnB7Y)** — Serverless Land “学习 AWS SAM” 系列开启。YouTube
+ **[AWS SAM 构建：它如何为部署提供工件（带有 SAM S2E8 的会话）](https://www.youtube.com/watch?v=bNbBd6XoDHg)**— 开启系列的 AWS SAM 会话。YouTube
+ **[AWS SAM 自定义构建：如何使用 Makefile 在 SAM (S2E9) 中自定义构建](https://www.youtube.com/watch?v=wpccutnSbAk)** — 开启系列的会话。 AWS SAM YouTube

# 默认版本使用 AWS SAM
<a name="serverless-sam-cli-using-build"></a>

要构建无服务器应用程序，请使用 `sam build` 命令。此命令还会收集应用程序依赖项的构建构件，并将其以适当的格式和位置放置以供后续步骤（例如本地测试、打包和部署）使用。

您可以在清单文件（例如 `requirements.txt` (Python) 或 `package.json` (Node.js)）中指定应用程序的依赖项，也可以使用函数资源的 `Layers` 属性来指定。`Layers` 属性包含 Lambda 函数所依赖的 [AWS Lambda 层](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)资源列表。

应用程序构建构件的格式取决于每个函数的 `PackageType` 属性。此属性的选项有：
+ **`Zip`** – .zip 文件归档，包括您的应用程序代码及其依赖项。如果您将代码打包为 .zip 文件存档，则必须为函数指定 Lambda 运行时。
+ **`Image`** – 容器映像，除了应用程序代码及其依赖项之外，还包括基本操作系统、运行时和扩展。

有关 Lambda 包类型的更多信息，请参阅《AWS Lambda 开发人员指南》**中的 [Lambda 部署包](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-package.html)。

**Topics**
+ [

## 创建 .zip 文件存档
](#build-zip-archive)
+ [

## 构建容器映像
](#build-container-image)
+ [

## 容器环境变量文件
](#serverless-sam-cli-using-container-environment-file)
+ [

## 通过在源文件夹中构建项目来加快构建时间
](#serverless-sam-cli-using-build-in-source)
+ [

## 示例
](#building-applications-examples)
+ [

## 在外部构建函数 AWS SAM
](#building-applications-skip)

## 创建 .zip 文件存档
<a name="build-zip-archive"></a>

要将无服务器应用程序构建为 .zip 文件存档，请为无服务器函数声明 `PackageType: Zip`。

AWS SAM 针对您指定的[架构](sam-resource-function.md#sam-function-architectures)构建应用程序。如果您未指定架构，则`x86_64`默认 AWS SAM 使用。

如果 Lambda 函数依赖于具有本地编译程序的包，请使用 `--use-container` 标志。此标志在本地将您的函数编译到一个行为类似于 Lambda 环境的容器中，因此当您将它们部署到云端时，它们的格式是正确的。 AWS 

当您使用该`--use-container`选项时，默认情况下会从 [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/public/what-is-ecr.html) Public 中 AWS SAM 提取容器映像。如果您想从其他存储库或特定版本的 AWS SAM CLI 中提取容器映像，则可以使用`--build-image`选项并提供备用容器镜像的 URI。以下是使用来自特定版本的 AWS SAM CLI 的容器镜像构建应用程序的两个示例命令：

```
# Build a Node.js 20 application using a container image for a specific version of AWS SAM CLI (1.136.0)
sam build --use-container --build-image public.ecr.aws/sam/build-nodejs22.x:1.136.0

# Build a function resource using the Python 3.13 container image from a specific version of AWS SAM CLI (1.136.0)(
sam build --use-container --build-image Function1=public.ecr.aws/sam/build-python3.13:1.136.0
```

有关构建 .zip 文件存档应用程序的其他示例，请参阅本主题后面的“示例”部分。

## 构建容器映像
<a name="build-container-image"></a>

要将无服务器应用程序构建为容器映像，请为无服务器函数声明 `PackageType: Image`。您还必须使用以下条目声明 `Metadata` 资源属性：

`Dockerfile`  
与 Lambda 函数关联的 Dockerfile 的名称。

`DockerContext`  
Dockerfile 的位置。

`DockerTag`  
（可选）应用于已构建映像的标签。

`DockerBuildArgs`  
为构建设置参数。  
 AWS SAMCLI 不会对包含在 `DockerBuildArgs` 参数中的任何信息进行编辑或模糊处理。我们强烈建议您不要使用此部分存储敏感信息，例如密码或密钥。

以下是 `Metadata` 资源属性部分的示例：

```
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./hello_world
      DockerTag: v1
```

要下载配置了 `Image` 软件包类型的示例应用程序，请参阅[教程：使用以下命令部署 Hello World 应用程序 AWS SAM](serverless-getting-started-hello-world.md)。当系统提示您要安装哪种软件包类型时，选择 `Image`。

**注意**  
如果您在 Dockerfile 中指定了多架构基础镜像，则需要为主机的架构 AWS SAM 构建容器镜像。要针对不同的架构进行构建，请指定使用特定目标架构的基础映像。

## 容器环境变量文件
<a name="serverless-sam-cli-using-container-environment-file"></a>

要为构建容器提供包含环境变量的 JSON 文件，请在 `sam build` 命令中使用 `--container-env-var-file` 参数。您可以提供适用于所有无服务器资源的单个环境变量，也可以为每种资源提供不同的环境变量。

### Format
<a name="serverless-sam-cli-using-container-environment-file-format"></a>

向构建容器传递环境变量的格式取决于您为资源提供的环境变量的数量。

要为所有资源提供单个环境变量，请指定如下所示的 `Parameters` 对象：

```
{
  "Parameters": {
    "GITHUB_TOKEN": "TOKEN_GLOBAL"
  }
}
```

要为每种资源提供不同的环境变量，请如下所示为每种资源指定对象：

```
{
  "MyFunction1": {
    "GITHUB_TOKEN": "TOKEN1"
  },
  "MyFunction2": {
    "GITHUB_TOKEN": "TOKEN2"
  }
}
```

将您的环境变量另存为文件，例如名为 `env.json`。以下命令使用此文件将环境变量传递到构建容器：

```
sam build --use-container --container-env-var-file env.json
```

### 优先级
<a name="serverless-sam-cli-using-container-environment-file-precedence"></a>
+ 您为特定资源提供的环境变量优先于所有资源的单个环境变量。
+ 您在命令行中提供的环境变量优先于文件中的环境变量。

## 通过在源文件夹中构建项目来加快构建时间
<a name="serverless-sam-cli-using-build-in-source"></a>

对于受支持的运行时和构建方法，您可以使用 `--build-in-source` 选项直接在源文件夹中生成项目。默认情况下，在临时目录中 AWS SAM CLI构建，其中包括复制源代码和项目文件。使用`--build-in-source`， AWS SAM CLI可以直接在源文件夹中进行构建，无需将文件复制到临时目录，从而加快构建过程。

有关支持的运行时和构建方法的列表，请参阅 `--build-in-source`。

## 示例
<a name="building-applications-examples"></a>

### 示例 1：.zip 文件存档
<a name="examples-zip-archives"></a>

以下 `sam build` 命令可创建 .zip 文件存档：

```
# Build all functions and layers, and their dependencies
sam build

# Run the build process inside a Docker container that functions like a Lambda environment
sam build --use-container

# Build a Node.js 20 application using a container image for a specific version of AWS SAM CLI (1.136.0)
sam build --use-container --build-image public.ecr.aws/sam/build-nodejs22.x:1.136.0

# Build a function resource using the Python 3.13 container image from a specific version of AWS SAM CLI (1.136.0)(
sam build --use-container --build-image Function1=public.ecr.aws/sam/build-python3.13:1.136.0

# Build and run your functions locally
sam build && sam local invoke

# For more options
sam build --help
```

### 示例 2：容器映像
<a name="examples-container-image-1"></a>

以下 AWS SAM 模板以容器镜像的形式构建：

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      PackageType: Image
      ImageConfig:
        Command: ["app.lambda_handler"]
    Metadata:
      Dockerfile: Dockerfile
      DockerContext: ./hello_world
      DockerTag: v1
```

以下是 Dockerfile 的示例：

```
FROM public.ecr.aws/lambda/python:3.12

COPY app.py requirements.txt ./

RUN python3.12 -m pip install -r requirements.txt

# Overwrite the command by providing a different command directly in the template.
CMD ["app.lambda_handler"]
```

### 示例 3：npm ci
<a name="examples-npm-ci"></a>

对于 Node.js 应用程序，您可以使用 `npm ci` 代替 `npm install` 来安装依赖项。要使用 `npm ci`，请在 Lambda 函数的 `Metadata` 资源属性中的 `BuildProperties` 下指定 `UseNpmCi: True`。要使用 `npm ci`，您的应用程序必须在 Lambda 函数的 `CodeUri` 中存在 `package-lock.json` 或 `npm-shrinkwrap.json` 文件。

以下示例使用 `npm ci` 在运行 `sam build` 时安装依赖项：

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.handler
      Runtime: nodejs20.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get
    Metadata:
      BuildProperties:
        UseNpmCi: True
```

### Python 父软件包
<a name="building-applications-python-parent-packages"></a>

对于 Python 应用程序，您可以在构建过程中保留软件包结构，从而启用绝对导入。保留软件包结构，请在您 Lambda 函数的 `Metadata` 资源属性的 `BuildProperties` 下指定 `ParentPackageMode`。

以下示例在您运行 `sam build` 时保留 `app` 软件包结构：

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.main.handler
      Runtime: python3.12
      Architectures:
        - x86_64
    Metadata:
      BuildProperties:
        ParentPackageMode: explicit
        ParentPackages: app
```

通过此配置，您的代码可以使用 `from app.utils import logger` 这样的绝对导入，而非 `from .utils import logger` 这样的相对导入。

## 在外部构建函数 AWS SAM
<a name="building-applications-skip"></a>

默认情况下，当您运行时**sam build**， AWS SAM 会生成所有函数资源。其他选项包括：
+ **在之外构建所有函数资源 AWS SAM** — 如果您手动或通过其他工具构建所有函数资源，**sam build**则不需要这样做。您可以跳过 **sam build** 并继续执行流程的下一步，例如执行本地测试或部署应用程序。
+ **在外部构建一些函数资源 AWS SAM** — 如果您 AWS SAM 想构建一些函数资源，同时在外部构建其他函数资源 AWS SAM，则可以在 AWS SAM 模板中指定这一点。

### 在之外构建一些函数资源 AWS SAM
<a name="building-applications-skip-some"></a>

要在使用时 AWS SAM 跳过某个函数**sam build**，请在 AWS SAM 模板中配置以下内容：

1. 向函数添加 `SkipBuild: True` 元数据属性。

1. 指定您构建的函数资源的路径。

以下是将 `TestFunction` 配置为跳过的示例。它的构建资源位于 `built-resources/TestFunction.zip`。

```
TestFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: built-resources/TestFunction.zip
    Handler: TimeHandler::handleRequest
    Runtime: java11
  Metadata:
    SkipBuild: True
```

现在，当你跑步时**sam build**， AWS SAM 将执行以下操作：

1. AWS SAM 将跳过配置的函数`SkipBuild: True`。

1. AWS SAM 将构建所有其他函数资源并将其缓存在`.aws-sam`构建目录中。

1. 对于跳过的函数，它们在 `.aws-sam` 构建目录中的模板将自动更新，以引用您构建的函数资源的指定路径。

   以下是 `.aws-sam` 构建目录中 `TestFunction` 的缓存模板的示例：

   ```
   TestFunction:
     Type: AWS::Serverless::Function
     Properties:
       CodeUri: ../../built-resources/TestFunction.zip
       Handler: TimeHandler::handleRequest
       Runtime: java11
     Metadata:
       SkipBuild: True
   ```

# 使用自定义构建 AWS SAM
<a name="building-lambda-functions"></a>

您可以自定义构建以包含特定的 Lambda 函数或 Lambda 层。函数是一种资源，您可以对其调用以在 Lambda 中运行您的代码。Lambda 层允许您从 Lambda 函数中提取代码，然后可以跨多个 Lambda 函数中重复使用这些代码。当您想专注于开发和部署单个无服务器函数，且免于管理共享依赖项或资源的复杂性时，则可以选择使用特定的 Lambda 函数自定义构建。此外，您可以选择构建 Lambda 层来帮助您缩小部署包的大小，将核心函数逻辑与依赖项分开，并允许您在多个函数之间共享依赖项。

本节中的主题探讨了您可以用来构建 Lambda 函数的一些不同方法。 AWS SAM其中包括使用客户运行时构建 Lambda 函数和构建 Lambda 层。自定义运行时允许您安装和使用开发人员指南中 Lambda 运行时中 AWS Lambda 未列出的语言。这样，您可以创建用于运行无服务器函数和应用程序的专业执行环境。仅构建 Lambda 层（而不是构建整个应用程序）可以在几个方面使您受益。它可以帮助您缩小部署包的大小，将核心函数逻辑与依赖项分开，并允许您在多个函数之间共享依赖项。

有关函数的更多信息，请参阅《AWS Lambda 开发人员指南》**中的 [Lambda 概念](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-concepts.html)。

**Topics**
+ [

# 在 esbuild 中构建 Node.js Lambda 函数 AWS SAM
](serverless-sam-cli-using-build-typescript.md)
+ [

# 使用原生 AOT 编译功能构建.NET Lambda 函数 AWS SAM
](build-dotnet7.md)
+ [

# 使用 in 构建 Rust Lambda 函数 Cargo Lambda AWS SAM
](building-rust.md)
+ [

# 使用输入构建 Python Lambda 函数 uv AWS SAM
](building-python-uv.md)
+ [

# 在中使用自定义运行时构建 Lambda 函数 AWS SAM
](building-custom-runtimes.md)
+ [

# 在中构建 Lambda 图层 AWS SAM
](building-layers.md)

# 在 esbuild 中构建 Node.js Lambda 函数 AWS SAM
<a name="serverless-sam-cli-using-build-typescript"></a>

要构建和打包 Node.js AWS Lambda 函数，可以将与 esbuild JavaScript 捆绑器 AWS SAMCLI一起使用。esbuild 捆绑器支持你写入的 Lambda 函数。 TypeScript

要使用 esbuild 构建 Node.js Lambda 函数，请向您的 `AWS:Serverless::Function` 资源添加一个 `Metadata` 对象并为 `BuildMethod` 指定 `esbuild`。当你运行**sam build**命令时， AWS SAM 使用 esbuild 来捆绑你的 Lambda 函数代码。

## 元数据属性
<a name="serverless-sam-cli-using-build-typescript-metadata"></a>

`Metadata` 对象针对 esbuild 支持以下属性：

### BuildMethod
<a name="serverless-sam-cli-using-build-typescript-metadata-buildmethod"></a>

为应用程序指定捆绑程序。`esbuild` 是唯一受支持的值。

### BuildProperties
<a name="serverless-sam-cli-using-build-typescript-metadata-buildproperties"></a>

为 Lambda 函数代码指定构建属性。

`BuildProperties` 对象针对 esbuild 支持以下属性：所有属性均为可选属性。默认情况下， AWS SAM 使用您的 Lambda 函数处理程序作为入口点。

**EntryPoints**  
为应用程序指定入口点。

**外部**  
指定要从构建中省略的程序包列表。有关更多信息，请参阅 *esbuild 网站*上的[外部](https://esbuild.github.io/api/#external)。

**Format**  
指定应用程序中生成 JavaScript 文件的输出格式。有关更多信息，请参阅 *esbuild 网站*中的[格式](https://esbuild.github.io/api/#format)。

**加载程序**  
指定用于加载给定文件类型的数据的配置列表。

**MainFields**  
指定解析程序包时要尝试导入哪些 `package.json` 字段。默认值为 `main,module`。

**缩小**  
指定是否缩小捆绑的输出代码。默认值为 `true`。

**OutExtension**  
自定义 esbuild 生成的文件的扩展名。有关更多信息，请参阅 *esbuild 网站*上的[向外扩展](https://esbuild.github.io/api/#out-extension)。

**源映射**  
指定捆绑程序是否生成源映射文件。默认值为 `false`。  
如果设置为 `true`，则 `NODE_OPTIONS: --enable-source-maps` 会附加到 Lambda 函数的环境变量中，生成源映射并将其包含在函数中。  
或者，如果 `NODE_OPTIONS: --enable-source-maps` 包含在函数的环境变量中，则 `Sourcemap` 会自动设置为 `true`。  
发生冲突时，`Sourcemap: false` 优先于 `NODE_OPTIONS: --enable-source-maps`。  
默认情况下，Lambda 使用 AWS Key Management Service (AWS KMS) 加密所有静态环境变量。使用源映射时，要成功部署，您的函数的执行角色必须具有执行 `kms:Encrypt` 操作的权限。

**SourcesContent**  
指定是否在源映射文件中包含源代码。当 `Sourcemap` 设置为 `'true'` 时，可配置此属性。  
+ 指定 `SourcesContent: 'true'` 包含所有源代码。
+ 指定 `SourcesContent: 'false'` 排除所有源代码。这样可以缩小源映射文件的大小，缩短启动时间，从而在生产中非常有用。但是，调试器中将无法使用源代码。
默认值为 `SourcesContent: true`。  
有关更多信息，请参阅 *esbuild 网站*中的[源内容](https://esbuild.github.io/api/#sources-content)。

**Target**  
指定目标 ECMAScript 版本。默认值为 `es2020`。

## TypeScript Lambda 函数示例
<a name="serverless-sam-cli-using-build-typescript-example"></a>

以下示例 AWS SAM 模板片段使用 esbuild 根据中的代码创建 Node.js Lambda 函数。 TypeScript `hello-world/app.ts`

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello-world/
      Handler: app.handler
      Runtime: nodejs20.x
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api 
          Properties:
            Path: /hello
            Method: get
      Environment:
        Variables:
          NODE_OPTIONS: --enable-source-maps
    Metadata:
      BuildMethod: esbuild
      BuildProperties:
        Format: esm
        Minify: false
        OutExtension:
          - .js=.mjs
        Target: "es2020"
        Sourcemap: true
        EntryPoints: 
          - app.ts
        External:
          - "<package-to-exclude>"
```

# 使用原生 AOT 编译功能构建.NET Lambda 函数 AWS SAM
<a name="build-dotnet7"></a>

使用 AWS Serverless Application Model (AWS SAM) 构建和打包您的.NET 8 AWS Lambda 函数，利用原生 Ahead-of-Time (AOT) 编译来缩短 AWS Lambda 冷启动时间。

**Topics**
+ [

## .NET 8 本机 AOT 概览
](#build-dotnet7-overview)
+ [

## AWS SAM 与您的.NET 8 Lambda 函数一起使用
](#build-dotnet7-sam)
+ [

## 安装必备组件
](#build-dotnet7-prerequisites)
+ [

## 在模板中定义.NET 8 Lambda 函数 AWS SAM
](#build-dotnet7-sam-define)
+ [

## 使用 AWS SAM CLI 构建应用程序
](#build-dotnet7-sam-build)
+ [

## 了解详情
](#build-dotnet7-learn-more)

## .NET 8 本机 AOT 概览
<a name="build-dotnet7-overview"></a>

过去，.NET Lambda 函数的冷启动时间会影响无服务器应用程序的用户体验、系统延迟和使用成本。凭借 .NET 本机 AOT 编译，您可以缩短 Lambda 函数的冷启动时间。要了解有关.NET 8 原生 AOT 的更多信息，请参阅在 D [otnet 存储库中使用原生 A](https://github.com/dotnet/runtime/tree/main/src/coreclr/nativeaot#readme) *O GitHub * T。

## AWS SAM 与您的.NET 8 Lambda 函数一起使用
<a name="build-dotnet7-sam"></a>

执行以下操作，使用 AWS Serverless Application Model （AWS SAM）配置 .NET 8 Lambda 函数：
+ 在开发计算机上安装必备组件。
+ 在模板中定义.NET 8 Lambda 函数。 AWS SAM 
+ 使用构建您的应用程序 AWS SAMCLI。

## 安装必备组件
<a name="build-dotnet7-prerequisites"></a>

以下是所需的先决条件：
+ 的 AWS SAMCLI
+ .NET Core CLI
+ Amazon.Lambda.Tools .NET Core Global Tool
+ Docker

**安装 AWS SAM CLI**

1. 要检查是否已安装 AWS SAM CLI，请运行以下命令：

   ```
   sam --version
   ```

1. 要安装 AWS SAMCLI，请参阅[安装 AWS SAM CLI](install-sam-cli.md)。

1. 要升级的已安装版本 AWS SAMCLI，请参阅[升级 AWS SAM CLI](manage-sam-cli-versions.md#manage-sam-cli-versions-upgrade)。

**安装 .NET Core CLI**

1. 要下载和安装 .NET Core CLI，请参阅从 Microsoft 网站[下载 .NET](https://dotnet.microsoft.com/download)。

1. 有关 .NET Core CLI 的更多信息，请参阅*《AWS Lambda 开发人员指南》*中的 [.NET Core CLI](https://docs.aws.amazon.com/lambda/latest/dg/csharp-package-cli.html)。

**安装 Amazon.Lambda.Tools .NET Core Global Tool**

1. 运行如下命令：

   ```
   dotnet tool install -g Amazon.Lambda.Tools
   ```

1. 如果您已安装该工具，请确保该工具是使用以下命令的最新版本：

   ```
   dotnet tool update -g Amazon.Lambda.Tools
   ```

1. 有关 Amazon.Lambda.Tools .NET 核心全球工具的更多信息，请参阅上的.NE [T CLI 存储AWS 库](https://github.com/aws/aws-extensions-for-dotnet-cli)扩展。 GitHub

**安装 Docker**
+ 使用本机 AOT 进行构建需要安装 Docker。有关安装说明，请参阅[安装 Docker 以与 AWS SAM CLI 一起使用](install-docker.md)。

## 在模板中定义.NET 8 Lambda 函数 AWS SAM
<a name="build-dotnet7-sam-define"></a>

要定义. NET8 在您的 AWS SAM 模板中使用 Lambda 函数，请执行以下操作：

1. 从您选择的起始目录运行以下命令：

   ```
   sam init
   ```

1. 选择 `AWS Quick Start Templates` 以选择起始模板。

1. 选择 `Hello World Example`模板。

1. 通过输入 `n`，选择不使用最流行的运行时和包类型。

1. 对于运行时，选择 `dotnet8`。

1. 对于包类型，选择 `Zip`。

1. 对于您的入门模板，选择 `Hello World Example using native AOT`。

**安装 Docker**
+ 使用本机 AOT 进行构建需要安装 Docker。有关安装说明，请参阅[安装 Docker 以与 AWS SAM CLI 一起使用](install-docker.md)。

```
Resources:
HelloWorldFunction:
  Type: AWS::Serverless::Function
  Properties:
    CodeUri: ./src/HelloWorldAot/
    Handler: bootstrap
    Runtime: dotnet8
    Architectures:
      - x86_64
    Events:
      HelloWorldAot:
        Type: Api 
        Properties:
          Path: /hello
          Method: get
```

**注意**  
如果的`Event`属性设置`AWS::Serverless::Function`为`Api`，但未指定该`RestApiId`属性，则 AWS SAM 生成`AWS::ApiGateway::RestApi` CloudFormation 资源。

## 使用 AWS SAM CLI 构建应用程序
<a name="build-dotnet7-sam-build"></a>

 在您的项目根目录中，运行 `sam build` 命令以开始构建应用程序。如果 `PublishAot` 属性已在 .NET 8 项目文件中定义，则 AWS SAM CLI 将使用本机 AOT 编译进行构建。要了解有关 `PublishAot` 属性的更多信息，请参阅 Microsoft *.NET 文档*中的[本机 AOT 部署](https://learn.microsoft.com/en-us/dotnet/core/deploying/native-aot/)。

要构建您的函数， AWS SAM CLI 会调用使用 Amazon.Lambda.Tools .NET Core Global Tool 的 .NET Core CLI。

**注意**  
构建时，如果项目所在目录或父目录中存在 `.sln` 文件，则包含该 `.sln` 文件的目录将挂载到容器中。如果找不到 `.sln` 文件，则只会挂载项目文件夹。因此，如果您要构建多项目应用程序，请确保 `.sln` 文件位于属性中。

## 了解详情
<a name="build-dotnet7-learn-more"></a>

有关构建 .NET 8 Lambda 函数的更多信息，请参阅 [Introducing the .NET 8 runtime for AWS Lambda](https://aws.amazon.com/blogs/compute/introducing-the-net-8-runtime-for-aws-lambda/)。

有关 **sam build** 命令的参考，请参阅 [sam build](sam-cli-command-reference-sam-build.md)。

# 使用 in 构建 Rust Lambda 函数 Cargo Lambda AWS SAM
<a name="building-rust"></a>


|  | 
| --- |
| 此功能为预览版 AWS SAM ，可能会发生变化。 | 

使用 AWS Serverless Application Model 命令行界面 (AWS SAMCLI) 和 Rust AWS Lambda 函数。

**Topics**
+ [

## 先决条件
](#building-rust-prerequisites)
+ [

## 配置 AWS SAM 为与 Rust Lambda 函数一起使用
](#building-rust-configure)
+ [

## 示例
](#building-rust-examples)

## 先决条件
<a name="building-rust-prerequisites"></a>

**Rust 语言**  
要安装 Rust，请参阅 *Rust 语言网站*上的[安装 Rust](https://www.rust-lang.org/tools/install)。

**Cargo Lambda**  
 AWS SAM CLI 要求安装 [https://www.cargo-lambda.info/guide/what-is-cargo-lambda.html](https://www.cargo-lambda.info/guide/what-is-cargo-lambda.html)，是 Cargo 的子命令。有关安装说明，请参阅 *Cargo Lambda 文档*中的[安装](https://www.cargo-lambda.info/guide/installation.html)。

**Docker**  
构建和测试 Rust Lambda 函数需要 Docker。有关安装说明，请参阅[安装 Docker](install-docker.md)。

**选择加入 AWS SAM CLI 测试版功能**  
由于此功能为预览版，因此您必须使用以下方法之一选择加入：  

1. 使用环境变量：`SAM_CLI_BETA_RUST_CARGO_LAMBDA=1`。

1. 在您的 `samconfig.toml` 文件中添加以下内容：

   ```
   [default.build.parameters]
   beta_features = true
   [default.sync.parameters]
   beta_features = true
   ```

1. 使用支持的 AWS SAM CLI 命令时使用 `--beta-features` 选项。例如：

   ```
   $ sam build --beta-features
   ```

1. 当 AWS SAM CLI 提示您选择加入时，请选择选项 `y`。以下是示例：

   ```
   $ sam build
   Starting Build use cache
   Build method "rust-cargolambda" is a beta feature.
   Please confirm if you would like to proceed
   You can also enable this beta feature with "sam build --beta-features". [y/N]: y
   ```

## 配置 AWS SAM 为与 Rust Lambda 函数一起使用
<a name="building-rust-configure"></a>

### 第 1 步：配置您的 AWS SAM 模板
<a name="building-rust-configure-template"></a>

使用以下内容配置您的 AWS SAM 模板：
+ **二进制** – 可选。指定模板何时包含多个 Rust Lambda 函数。
+ **BuildMethod** – `rust-cargolambda`.
+ **CodeUri**— `Cargo.toml` 文件路径。
+ **处理程序** – `bootstrap`.
+ **运行时系统** – `provided.al2`.

要了解有关自定义运行时的更多信息，请参阅《*AWS Lambda 开发者*指南[AWS Lambda 》中的自定义运行时](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-custom.html)。

以下是已配置 AWS SAM 模板的示例：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties: function_a
    Properties:
      CodeUri: ./rust_app
      Handler: bootstrap
      Runtime: provided.al2
...
```

### 第 2 步：将 AWS SAM CLI 与 Rust Lambda 函数一起使用
<a name="building-rust-configure-cli"></a>

在 AWS SAM 模板中使用任意 AWS SAMCLI命令。有关更多信息，请参阅 [AWS SAM CLI](using-sam-cli.md)。

## 示例
<a name="building-rust-examples"></a>

### Hello World 示例
<a name="building-rust-examples-hello"></a>

**在此示例中，我们使用 Rust 作为运行时系统来构建示例 Hello World 应用程序。**

首先，我们使用 `sam init` 初始化新的无服务器应用程序。在交互式流程中，我们选择 **Hello World 应用程序**并选择 **Rust** 运行时系统。

```
$ sam init
...
Which template source would you like to use?
        1 - AWS Quick Start Templates
        2 - Custom Template Location
Choice: 1

Choose an AWS Quick Start application template
        1 - Hello World Example
        2 - Multi-step workflow
        3 - Serverless API
        ...
Template: 1

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

Which runtime would you like to use?
        1 - dotnet8
        2 - dotnet6
        3 - go (provided.al2)
        ...
        18 - python3.11
        19 - python3.10
        20 - ruby3.3
        21 - ruby3.2
        22 - rust (provided.al2)
        23 - rust (provided.al2023)
Runtime: 22

Based on your selections, the only Package type available is Zip.
We will proceed to selecting the Package type as Zip.

Based on your selections, the only dependency manager available is cargo.
We will proceed copying the template using cargo.

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]: hello-rust

    -----------------------
    Generating application:
    -----------------------
    Name: hello-rust
    Runtime: rust (provided.al2)
    Architectures: x86_64
    Dependency Manager: cargo
    Application Template: hello-world
    Output Directory: .
    Configuration file: hello-rust/samconfig.toml
    
    Next steps can be found in the README file at hello-rust/README.md
        

Commands you can use next
=========================
[*] Create pipeline: cd hello-rust && sam pipeline init --bootstrap
[*] Validate SAM template: cd hello-rust && sam validate
[*] Test Function in the Cloud: cd hello-rust && sam sync --stack-name {stack-name} --watch
```

以下是 Hello World 应用程序的结构：

```
hello-rust
├── README.md
├── events
│   └── event.json
├── rust_app
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── samconfig.toml
└── template.yaml
```

在我们的 AWS SAM 模板中，我们的Rust函数定义如下：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function 
    Metadata:
      BuildMethod: rust-cargolambda 
    Properties:
      CodeUri: ./rust_app 
      Handler: bootstrap   
      Runtime: provided.al2
      Architectures:
        - x86_64
      Events:
        HelloWorld:
          Type: Api
            Path: /hello
            Method: get
```

接下来，运行 `sam build` 以构建应用程序并准备部署。 AWS SAM CLI 创建一个 `.aws-sam` 目录并在其中整理构建构件。函数是使用 Cargo Lambda 构建，并以可执行二进制文件的形式存储于 `.aws-sam/build/HelloWorldFunction/bootstrap`。

**注意**  
如果您计划在 MacOS 中运行 **sam local invoke** 命令，则需要在调用之前构建不同的函数。要执行此操作，请使用以下命令：  
**SAM\$1BUILD\$1MODE=debug sam build**
仅在完成本地测试时才需要此命令。在为部署构建时，不建议这样做。

```
hello-rust$ sam build
Starting Build use cache
Build method "rust-cargolambda" is a beta feature.
Please confirm if you would like to proceed
You can also enable this beta feature with "sam build --beta-features". [y/N]: y

Experimental features are enabled for this session.
Visit the docs page to learn more about the AWS Beta terms https://aws.amazon.com/service-terms/.

Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../hello-rust/rust_app runtime: provided.al2 metadata: {'BuildMethod': 'rust-cargolambda'} architecture: x86_64 functions: HelloWorldFunction
Running RustCargoLambdaBuilder:CargoLambdaBuild
Running RustCargoLambdaBuilder:RustCopyAndRename

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` 部署应用程序。

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

        ...

        Uploading to hello-rust/56ba6585d80577dd82a7eaaee5945c0b  817973 / 817973  (100.00%)

        Deploying with following values
        ===============================
        Stack name                   : hello-rust
        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 hello-rust/a4fc54cb6ab75dd0129e4cdb564b5e89.template  1239 / 1239  (100.00%)


Waiting for changeset to be created..

CloudFormation stack changeset
---------------------------------------------------------------------------------------------------------
Operation                  LogicalResourceId          ResourceType               Replacement              
---------------------------------------------------------------------------------------------------------
+ Add                      HelloWorldFunctionHelloW   AWS::Lambda::Permission    N/A                      
                           orldPermissionProd                                                             
...                    
---------------------------------------------------------------------------------------------------------

Changeset created successfully. arn:aws:cloudformation:us-west-2:012345678910:changeSet/samcli-deploy1681427201/f0ef1563-5ab6-4b07-9361-864ca3de6ad6


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

2023-04-13 13:07:17 - 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        
...
---------------------------------------------------------------------------------------------------------

CloudFormation outputs from deployed stack
---------------------------------------------------------------------------------------------------------
Outputs                                                                                                 
---------------------------------------------------------------------------------------------------------
Key                 HelloWorldFunctionIamRole                                                           
Description         Implicit IAM Role created for Hello World function                                  
Value               arn:aws:iam::012345678910:role/hello-rust-HelloWorldFunctionRole-10II2P13AUDUY      

Key                 HelloWorldApi                                                                       
Description         API Gateway endpoint URL for Prod stage for Hello World function                    
Value               https://ggdxec9le9.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:hello-rust-HelloWorldFunction-       
yk4HzGzYeZBj                                                                                            
---------------------------------------------------------------------------------------------------------


Successfully created/updated stack - hello-rust in us-west-2
```

为了进行测试，我们可以使用 API 端点调用 Lambda 函数。

```
$ curl https://ggdxec9le9.execute-api.us-west-2.amazonaws.com/Prod/hello/
Hello World!%
```

要在本地测试函数，首先我们要确保函数的 `Architectures` 属性与本地计算机相匹配。

```
...
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
    Metadata:
      BuildMethod: rust-cargolambda # More info about Cargo Lambda: https://github.com/cargo-lambda/cargo-lambda
    Properties:
      CodeUri: ./rust_app   # Points to dir of Cargo.toml
      Handler: bootstrap    # Do not change, as this is the default executable name produced by Cargo Lambda
      Runtime: provided.al2
      Architectures:
        - arm64
...
```

由于我们在此示例中将基础设施从 `x86_64` 修改为 `arm64`，因此我们运行 `sam build` 以更新构建构件。然后运行 `sam local invoke` 在本地调用函数。

```
hello-rust$ sam local invoke
Invoking bootstrap (provided.al2)
Local image was not found.
Removing rapid images for repo public.ecr.aws/sam/emulation-provided.al2
Building image.....................................................................................................................................
Using local image: public.ecr.aws/lambda/provided:al2-rapid-arm64.

Mounting /Users/.../hello-rust/.aws-sam/build/HelloWorldFunction as /var/task:ro,delegated, inside runtime container
START RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6 Version: $LATEST
{"statusCode":200,"body":"Hello World!"}END RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6
REPORT RequestId: fbc55e6e-0068-45f9-9f01-8e2276597fc6  Init Duration: 0.68 ms  Duration: 130.63 ms     Billed Duration: 131 ms     Memory Size: 128 MB     Max Memory Used: 128 MB
```

### 单个 Lambda 函数项目
<a name="building-rust-examples-single"></a>

**以下是一个包含单个 Rust Lambda 函数的无服务器应用程序的示例。**

项目目录结构：

```
.
├── Cargo.lock
├── Cargo.toml
├── src
│   └── main.rs
└── template.yaml
```

AWS SAM 模板：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
    Properties:
      CodeUri: ./             
      Handler: bootstrap
      Runtime: provided.al2
...
```

### 多个 Lambda 函数项目
<a name="building-rust-examples-multiple"></a>

**以下是一个包含多个 Rust Lambda 函数的无服务器应用程序的示例。**

项目目录结构：

```
.
├── Cargo.lock
├── Cargo.toml
├── src
│   ├── function_a.rs
│   └── function_b.rs
└── template.yaml
```

AWS SAM 模板：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  FunctionA:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties:
        Binary: function_a 
    Properties:
      CodeUri: ./           
      Handler: bootstrap     
      Runtime: provided.al2
  FunctionB:
    Type: AWS::Serverless::Function
    Metadata:
      BuildMethod: rust-cargolambda
      BuildProperties:
        Binary: function_b
    Properties:
      CodeUri: ./
      Handler: bootstrap
      Runtime: provided.al2
```

`Cargo.toml` 文件：

```
[package]
name = "test-handler"
version = "0.1.0"
edition = "2021"

[dependencies]
lambda_runtime = "0.6.0"
serde = "1.0.136"
tokio = { version = "1", features = ["macros"] }
tracing = { version = "0.1", features = ["log"] }
tracing-subscriber = { version = "0.3", default-features = false, features = ["fmt"] }

[[bin]]
name = "function_a"
path = "src/function_a.rs"

[[bin]]
name = "function_b"
path = "src/function_b.rs"
```

# 使用输入构建 Python Lambda 函数 uv AWS SAM
<a name="building-python-uv"></a>


|  | 
| --- |
| 此功能为预览版 AWS SAM ，可能会发生变化。 | 

使用带有uv快速 Python 包安装程序和解析器的 AWS Serverless Application Model 命令行界面 (AWS SAMCLI) 来构建 Python AWS Lambda 函数。

**Topics**
+ [

## 先决条件
](#building-python-uv-prerequisites)
+ [

## 配置 AWS SAM 为与 Python Lambda 函数一起使用以及 uv
](#building-python-uv-configure)
+ [

## 示例
](#building-python-uv-examples)

## 先决条件
<a name="building-python-uv-prerequisites"></a>

**Python**  
要安装 Python，请参阅在 [Python 网站上下载](https://www.python.org/downloads/) *Python*。

**uv**  
 AWS SAMCLI需要安装速度极快的 [https://docs.astral.sh/uv/](https://docs.astral.sh/uv/)Python 包安装程序和解析器。有关安装说明，请参阅 *uv 文档*中的[安装](https://docs.astral.sh/uv/getting-started/installation/)。

**选择加入 AWS SAM CLI 测试版功能**  
由于此功能为预览版，因此您必须使用以下方法之一选择加入：  

1. 使用环境变量：`SAM_CLI_BETA_PYTHON_UV=1`。

1. 在您的 `samconfig.toml` 文件中添加以下内容：

   ```
   [default.build.parameters]
   beta_features = true
   [default.sync.parameters]
   beta_features = true
   ```

1. 使用支持的 AWS SAM CLI 命令时使用 `--beta-features` 选项。例如：

   ```
   $ sam build --beta-features
   ```

1. 当 AWS SAM CLI 提示您选择加入时，请选择选项 `y`。以下是示例：

   ```
   $ sam build
   Starting Build use cache
   Build method "python-uv" is a beta feature.
   Please confirm if you would like to proceed
   You can also enable this beta feature with "sam build --beta-features". [y/N]: y
   ```

## 配置 AWS SAM 为与 Python Lambda 函数一起使用以及 uv
<a name="building-python-uv-configure"></a>

### 第 1 步：配置您的 AWS SAM 模板
<a name="building-python-uv-configure-template"></a>

使用以下内容配置您的 AWS SAM 模板：
+ **BuildMethod** – `python-uv`.
+ **CodeUri**— 包含`pyproject.toml`或的函数代码目录的路径`requirements.txt`。
+ **H** andler — 你的函数处理器（例如`app.lambda_handler`）。
+ **运行时** — Python 运行时版本（例如`python3.12`）。

以下是已配置 AWS SAM 模板的示例：

```
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
...
Resources:
  MyFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: ./my_function
      Handler: app.lambda_handler
      Runtime: python3.12
    Metadata:
      BuildMethod: python-uv
...
```

## 示例
<a name="building-python-uv-examples"></a>

### Hello World 示例
<a name="building-python-uv-examples-hello"></a>

**在此示例中，我们使用 Python uv 作为包管理器构建了一个示例 Hello World 应用程序。**

uv可以使用`pyproject.toml`或来读`requirements.txt`取依赖关系。如果两者都给出，`sam build`将从中读`requirements.txt`取依赖关系。

以下是 Hello World 应用程序的结构：

```
hello-python-uv
├── README.md
├── events
│   └── event.json
├── hello_world
│   ├── __init__.py
│   ├── app.py
│   └── pyproject.toml
├── samconfig.toml
└── template.yaml
```

`pyproject.toml` 文件：

```
[project]
name = "my-function"
version = "0.1.0"
requires-python = ">=3.12"
dependencies = [
    "requests>=2.31.0",
    "boto3>=1.28.0",
]
```

在我们的 AWS SAM 模板中，我们的 Python 函数定义如下：

```
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.12
      Architectures:
        - x86_64
    Metadata:
      BuildMethod: python-uv
```

接下来，运行 `sam build` 以构建应用程序并准备部署。 AWS SAM CLI 创建一个 `.aws-sam` 目录并在其中整理构建构件。我们的函数依赖项是使用安装uv并存储在的`.aws-sam/build/HelloWorldFunction/`。

```
hello-python-uv$ sam build
Starting Build use cache
Build method "python-uv" is a beta feature.
Please confirm if you would like to proceed
You can also enable this beta feature with "sam build --beta-features". [y/N]: y

Experimental features are enabled for this session.
Visit the docs page to learn more about the AWS Beta terms https://aws.amazon.com/service-terms/.

Cache is invalid, running build and copying resources for following functions (HelloWorldFunction)
Building codeuri: /Users/.../hello-python-uv/hello_world runtime: python3.12 metadata: {'BuildMethod': 'python-uv'} architecture: x86_64 functions: HelloWorldFunction
Running PythonUvBuilder:UvBuild
Running PythonUvBuilder:CopySource

Build Succeeded

Built Artifacts  : .aws-sam/build
Built Template   : .aws-sam/build/template.yaml

Commands you can use next
=========================
[*] Validate SAM template: sam validate
[*] Invoke Function: sam local invoke
[*] Test Function in the Cloud: sam sync --stack-name {{stack-name}} --watch
[*] Deploy: sam deploy --guided
```

**注意**  
`python-uv`构建方法是按`Metadata`部分中的每个函数配置的。模板中的每个函数都可以使用不同的构建方法，从而允许您在同一个 AWS SAM 模板中将uv基于的函数与`pip`基于的函数混合使用。如果未指定构建方法，`pip`则默认使用。

# 在中使用自定义运行时构建 Lambda 函数 AWS SAM
<a name="building-custom-runtimes"></a>

您可以使用 `sam build` 命令构建 Lambda 函数所需的自定义运行时系统。您可以通过为函数指定 `Runtime: provided` 来声明 Lambda 函数以使用自定义运行时系统。

要构建自定义运行时系统，请使用 `BuildMethod: makefile` 条目声明 `Metadata` 资源属性。您提供自定义 makefile，在其中声明包含运行时构建命令的表单 `build-function-logical-id` 的构建目标。如有必要，您的 makefile 负责编译自定义运行时系统，并将构建构件复制到工作流程中后续步骤所需的适当位置。Makefile 的位置由函数资源的 `CodeUri` 属性指定，并且必须命名为 `Makefile`。

## 示例
<a name="building-custom-runtimes-examples"></a>

### 示例 1：用 Rust 编写的函数的自定义运行时系统
<a name="building-custom-runtimes-examples-rust"></a>

**注意**  
我们建议使用 Cargo Lambda 构建 Lambda 函数。要了解更多信息，请参阅[使用 in 构建 Rust Lambda 函数 Cargo Lambda AWS SAM](building-rust.md)。

以下 AWS SAM 模板声明了一个函数，该函数为用 Rust 编写的 Lambda 函数使用自定义运行时，并指示`sam build`为构建目标执行命令。`build-HelloRustFunction`

```
Resources:
  HelloRustFunction:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: HelloRust
      Handler: bootstrap.is.real.handler
      Runtime: provided
      MemorySize: 512
      CodeUri: .
    Metadata:
      BuildMethod: makefile
```

以下 makefile 包含构建目标和将要执行的命令。请注意，`CodeUri` 属性设置为 `.`，因此 makefile 必须位于项目根目录（即与应用程序 AWS SAM 模板文件相同的目录）。文件名必须是 `Makefile`。

```
build-HelloRustFunction:
	cargo build --release --target x86_64-unknown-linux-musl
	cp ./target/x86_64-unknown-linux-musl/release/bootstrap $(ARTIFACTS_DIR)
```

有关设置开发环境以执行前面 `makefile` 中的 `cargo build` 命令的更多信息，请参阅博客文章 [AWS Lambda的 Rust 运行时系统](https://aws.amazon.com/blogs/opensource/rust-runtime-for-aws-lambda/)。

### 示例 2：适用于 Python3.12 的 makefile 生成器（替代使用捆绑生成器）
<a name="building-custom-runtimes-examples-python"></a>

您可能需要使用未包含在捆绑生成器中的库或模块。此示例显示了带有 makefile 生成器的 Python3.12 运行时的 AWS SAM 模板。

```
Resources:
  HelloWorldFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: hello_world/
      Handler: app.lambda_handler
      Runtime: python3.12
    Metadata:
      BuildMethod: makefile
```

以下 makefile 包含构建目标和将要执行的命令。请注意，`CodeUri` 属性设置为 `hello_world`，因此 makefile 必须位于 `hello_world` 子目录的根目录中，并且文件名必须为 `Makefile`。

```
build-HelloWorldFunction:
	cp *.py $(ARTIFACTS_DIR)
	cp requirements.txt $(ARTIFACTS_DIR)
	python -m pip install -r requirements.txt -t $(ARTIFACTS_DIR)
	rm -rf $(ARTIFACTS_DIR)/bin
```

# 在中构建 Lambda 图层 AWS SAM
<a name="building-layers"></a>



您可以使用 AWS SAM 来构建自定义 Lambda 层。Lambda 层允许您从 Lambda 函数中提取代码，然后可以在多个 Lambda 函数中重复使用这些代码。仅构建 Lambda 层（而不是构建整个应用程序）可以在几个方面使您受益。它可以帮助您缩小部署包的大小，将核心函数逻辑与依赖项分开，并允许您在多个函数之间共享依赖项。有关层的信息，请参阅*《AWS Lambda 开发人员指南》*中的 [AWS Lambda 层](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)。

## 如何在中构建 Lambda 层 AWS SAM
<a name="w2aac18c23c19c34b7"></a>

**注意**  
在构建 Lambda 层之前，必须先在模板中写一个 Lambda 层。 AWS SAM 有关执行此操作的信息和示例，请参阅[使用带有 Lambda 层的 Lambda 层来提高效率 AWS SAM](serverless-sam-cli-layers.md)。

要构建自定义层，请在您的 AWS Serverless Application Model (AWS SAM) 模板文件中对其进行声明，并在`Metadata`资源属性部分中`BuildMethod`加入一个条目。`BuildMethod` 的有效值是 [AWS Lambda 运行时系统](https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html)或 `makefile` 的标识符。纳入一个 `BuildArchitecture` 条目以指定您的层支持的指令集架构。`BuildArchitecture` 的有效值是 [Lambda 指令集架构](https://docs.aws.amazon.com/lambda/latest/dg/foundation-arch.html)。

如果指定 `makefile`，请提供自定义 makefile，在其中声明包含层构建命令的表单 `build-layer-logical-id` 的构建目标。如有必要，您的 makefile 负责编译层，并将构建构件复制到工作流程中后续步骤所需的适当位置。Makefile 的位置由层资源的 `ContentUri` 属性指定，并且必须命名为 `Makefile`。

**注意**  
创建自定义图层时，需要 AWS Lambda 依靠环境变量来查找图层代码。Lambda 运行时系统包含将您的层代码复制到的 `/opt` 目录中的路径。项目的构建构件文件夹结构必须与运行时系统的预期文件夹结构相匹配，这样才能找到自定义层代码。  
例如，对于 Python，您可以将代码放在 `python/` 子目录中。对于 NodeJS，您可以将代码放在 `nodejs/node_modules/` 子目录中。  
有关更多信息，请参阅*《AWS Lambda 开发人员指南》*中的[在层中包括库依赖项](https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html#configuration-layers-path)。

以下是 `Metadata` 资源属性部分的示例。

```
    Metadata:
      BuildMethod: python3.12
      BuildArchitecture: arm64
```

**注意**  
如果您不包括`Metadata`资源属性部分，则 AWS SAM 不构建图层。相反，它会从层资源 `CodeUri` 属性中指定的位置复制构建构件。有关更多信息，请参阅 `AWS::Serverless::LayerVersion` 资源类型中 [ContentUri](sam-resource-layerversion.md#sam-layerversion-contenturi) 属性。

当包含`Metadata`资源属性部分时，您可以使用`sam build`命令来构建层，既可以作为独立对象，也可以作为 AWS Lambda 函数的依赖项。
+ ****作为独立对象。****您可能只想构建层对象，例如，当您在本地测试层的代码更改并且不需要构建整个应用程序时。要独立构建层，请使用 `sam build layer-logical-id` 命令指定层资源。
+ **作为 Lambda 函数的依赖项。**当您在同一 AWS SAM 模板文件的 Lambda 函数的 `Layers` 属性中包含层的逻辑 ID 时，该层就是该 Lambda 函数的依赖项。当该层还包括带有 `BuildMethod` 条目的 `Metadata` 资源属性部分时，您可以通过使用 `sam build` 命令构建整个应用程序或使用 `sam build function-logical-id` 命令指定函数资源来构建该层。

## 示例
<a name="building-applications-examples"></a>

### 模板示例 1：针对 Python 3.12 运行时环境构建一个层
<a name="building-applications-examples-python"></a>

以下示例 AWS SAM 模板基于 Python 3.12 运行时环境构建了一个层。

```
Resources:
  MyLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: my_layer
      CompatibleRuntimes:
        - python3.12
    Metadata:
      BuildMethod: python3.12   # Required to have AWS SAM build this layer
```

### 模板示例 2：使用自定义 makefile 构建层
<a name="building-applications-examples-makefile"></a>

以下示例 AWS SAM 模板使用自定义模板`makefile`来构建图层。

```
Resources:
  MyLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      ContentUri: my_layer
      CompatibleRuntimes:
        - python3.12
    Metadata:
      BuildMethod: makefile
```

以下 `makefile` 包含构建目标和将要执行的命令。请注意，`ContentUri` 属性设置为 `my_layer`，因此 makefile 必须位于 `my_layer` 子目录的根目录中，并且文件名必须为 `Makefile`。另请注意，构建工件被复制到`python/`子目录中，以便 AWS Lambda 能够找到层代码。

```
build-MyLayer:
  mkdir -p "$(ARTIFACTS_DIR)/python"
  cp *.py "$(ARTIFACTS_DIR)/python"
  python -m pip install -r requirements.txt -t "$(ARTIFACTS_DIR)/python"
```

**注意**  
当调用 `makefile` 时，将触发相应目标，并应将构件复制到暴露的环境变量 `$ARTIFACTS_DIR` 中。有关更多信息，请参阅[aws-lambda-builders 中的 GitHub](https://github.com/aws/aws-lambda-builders/blob/develop/aws_lambda_builders/workflows/custom_make/DESIGN.md)。

### sam 构建命令示例
<a name="building-applications-examples-commands"></a>

以下 `sam build` 命令构建包含 `Metadata` 资源属性部分的层。

```
# Build the 'layer-logical-id' resource independently
$ sam build layer-logical-id
            
# Build the 'function-logical-id' resource and layers that this function depends on
$ sam build function-logical-id

# Build the entire application, including the layers that any function depends on
$ sam build
```