

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

# 使用以下方式定义您的基础架构 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)。