

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

# 使用 定義您的基礎設施 AWS SAM
<a name="serverless-authoring"></a>

現在您已建立專案，即可使用 定義應用程式基礎設施 AWS SAM。透過設定您的 AWS SAM 範本來定義應用程式的資源和屬性來執行此操作，這是您 AWS SAM 專案中的 `template.yaml` 檔案。

本節中的主題提供有關在 AWS SAM 範本 （您的 `template.yaml` 檔案） 中定義基礎設施的內容。它還包含針對特定使用案例定義資源的主題，例如使用 Lambda 層、使用巢狀應用程式、控制 API Gateway APIs存取、使用 Step Functions 協調 AWS 資源、程式碼簽署應用程式，以及驗證 AWS SAM 範本。

**Topics**
+ [在 AWS SAM 範本中定義應用程式資源](authoring-define-resources.md)
+ [在 AWS SAM 範本中設定和管理資源存取](sam-permissions.md)
+ [使用 AWS SAM 範本控制 API 存取](serverless-controlling-access-to-apis.md)
+ [透過 使用 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 API 更低延遲和成本的 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_tw/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 函數來源資源中。DynamoDB 資料表是使用 `Id` 屬性定義為目的地資源。連接器將在這兩個資源之間佈建`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`和 `Write` 中 AWS SAM，許可可以在單一連接器中佈建：

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

在來源資源中，您可以定義具有多個目的地資源的單一連接器。以下是連線至 Amazon Simple Storage Service (Amazon S3) 儲存貯體和 DynamoDB 資料表的 Lambda 函數來源資源範例：

```
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. 針對 AWS SAM GitHub 專案`develop`分支中的 policy\$1templates.json 來源檔案提交提取請求。您可以在 GitHub 網站上的 [policy\$1templates.json](https://github.com/aws/serverless-application-model/blob/develop/samtranslator/policy_templates_data/policy_templates.json) 中找到來源檔案。

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>

下列範例包含 AmazonSQSFullAcess 政策和[DynamoDBCrudPolicy](serverless-policy-template-list.md#dynamo-db-crud-policy)政策範本。AmazonSQSFullAccess 政策是 IAM 政策而非 AWS SAM 政策，因此您不需要指定空物件，因為政策會直接傳遞給 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>

以下是可用政策範本的資料表。


****  

| 政策範本 | Description | 
| --- | --- | 
| [AcmGetCertificatePolicy](serverless-policy-template-list.md#acm-get-certificate-policy) | 授予從中讀取憑證的許可 AWS Certificate Manager。 | 
| [AMIDescribePolicy](serverless-policy-template-list.md#ami-describe-policy) | 提供描述 Amazon Machine Image (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/刪除物件的許可。 | 
| [CodeCommitReadPolicy](serverless-policy-template-list.md#codecommit-read-policy) | 准許讀取特定 CodeCommit 儲存庫中的物件。 | 
| [CodePipelineLambdaExecutionPolicy](serverless-policy-template-list.md#code-pipeline-lambda-execution-policy) | 准許 CodePipeline 調用 Lambda 函數來報告任務的狀態。 | 
| [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) | 將 POST 許可提供給 Amazon OpenSearch Service。 | 
| [EventBridgePutEventsPolicy](serverless-policy-template-list.md#eventbridge-put-events-policy) | 提供將事件傳送至 EventBridge 的許可。 | 
| [FilterLogEventsPolicy](serverless-policy-template-list.md#filter-log-events-policy) | 提供從指定日誌群組篩選 CloudWatch Logs 事件的許可。 | 
| [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 Simple Email Service (Amazon SES身分。 | 
| [SNSCrudPolicy](serverless-policy-template-list.md#sns-crud-policy) | 提供建立、發佈和訂閱 Amazon SNS 主題的許可。 | 
| [SNSPublishMessagePolicy](serverless-policy-template-list.md#sqs-publish-message-policy) | 准許將訊息發佈至 Amazon Simple Notification 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) 參數存放區存取參數，以載入此帳戶中的秘密。當參數名稱沒有斜線字首時，請使用 。 | 
| [SSMParameterWithSlashPrefixReadPolicy](serverless-policy-template-list.md#ssm-parameter-slash-read-policy) | 准許從 Amazon EC2 Systems Manager (SSM) 參數存放區存取參數，以載入此帳戶中的秘密。當參數名稱具有斜線字首時，請使用 。 | 
| [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 Machine Image (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>

提供描述 Amazon 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 Elastic Compute Cloud (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>

提供 POST 和 PUT 許可給 Amazon OpenSearch Service。

```
"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 Logs 事件的許可。

```
"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 Simple Email Service (Amazon SES身分。

```
"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 Notification 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 EC2 Systems 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 EC2 Systems 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
+ IAMFullAccess
+ AWSLambda\$1FullAccess
+ AmazonAPIGatewayAdministrator
+ AmazonS3FullAccess
+ AmazonEC2ContainerRegistryFullAccess

 如需將政策連接至 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 政策的詳細資訊，請參閱《[IAM 使用者指南》中的管理 IAM 政策](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 授權方 （先前稱為*自訂授權方*) 是您提供的 Lambda 函數，用於控制對 API 的存取。呼叫 API 時，會使用用戶端應用程式提供的請求內容或授權字符叫用此 Lambda 函數。Lambda 函數會回應發起人是否有權執行請求的操作。

  `AWS::Serverless::HttpApi` 和 `AWS::Serverless::Api` 資源類型都支援 Lambda 授權方。

  如需使用 的 Lambda 授權方詳細資訊`AWS::Serverless::HttpApi`，請參閱 *API Gateway 開發人員指南*中的[使用 HTTP APIs的授權 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 登入資料進行身分驗證。只有在連接至 IAM 使用者的 IAM 政策代表 API 呼叫者、包含使用者的 IAM 群組，或使用者擔任的 IAM 角色時，呼叫 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 Connect (OIDC)](https://openid.net/specs/openid-connect-core-1_0.html) 和 [OAuth 2.0](https://oauth.net/2/) 架構的一部分，以控制對 APIs存取。API Gateway 會驗證用戶端隨 API 請求提交JWTs，並根據權杖驗證以及可選擇權杖中的範圍來允許或拒絕請求。

  只有 `AWS::Serverless::HttpApi` 資源類型支援 OAuth 2.0/JWT 授權方。

  如需詳細資訊，請參閱《*API Gateway 開發人員指南*》中的[使用 JWT 授權方控制對 HTTP API 的存取](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 開發人員指南](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-gatewayResponse-definition.html)*》中的 API Gateway* 回應。如需自訂回應的範例，請參閱 [的自訂回應範例 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>

您可以在 AWS SAM 範本中定義 Lambda `TOKEN`授權方，以控制對 APIs存取。若要這樣做，請使用 [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>

您可以在 AWS SAM 範本中定義 Lambda `REQUEST`授權方，以控制對 APIs存取。若要這樣做，請使用 [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>

您可以在 AWS SAM 範本中定義 Lambda 授權方，以控制對 HTTP APIs存取。若要這樣做，請使用 [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>

您可以在範本中定義 IAM 許可，以控制對 AWS SAM APIs存取。若要這樣做，請使用 [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>

您可以在範本中定義 Amazon Cognito 使用者集區，以控制對 AWS SAM APIs 的存取。若要這樣做，請使用 [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>

您可以在 AWS SAM 範本中要求 API 金鑰，以控制對 API APIs存取。若要這樣做，請使用 [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>

您可以在範本中附加資源政策，以控制對 AWS SAM APIs存取。若要這樣做，請使用 [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>

您可以在 [OpenID Connect (OIDC)](https://openid.net/specs/openid-connect-core-1_0.html) 和 OAuth 2.0 架構中使用 JWTs控制對 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 授權方的詳細資訊，請參閱《 [ APIs Gateway 開發人員指南》中的使用 JWT 授權方控制 HTTP API 的存取](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 開發人員指南](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-gatewayResponse-definition.html)*》中的 API Gateway* 回應。

# 透過 使用 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)。

本主題提供有關下列項目的資訊：
+ 在應用程式中包含圖層
+ 如何在本機快取層

如需建置自訂 layer 的資訊，請參閱 [在 中建置 Lambda 層 AWS SAM](building-layers.md)。

## 在應用程式中包含圖層
<a name="including-layers"></a>

若要在您的應用程式中包含圖層，請使用 [AWS::Serverless::Function](sam-resource-function.md) 資源類型的 `Layers` 屬性。

以下是包含 layer 的 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`命令叫用函數時，函數的 layer 套件會下載並在本機主機上快取。

下表顯示不同作業系統的預設快取目錄位置。


****  

| 作業系統 | Location | 
| --- | --- | 
| 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 SAM CLI 會產生其建置的映像名稱，以及快取中保留的 LayerVersions。您可以在以下章節中找到結構描述的詳細資訊。

若要檢查重疊圖層，請執行下列命令，在您要檢查的映像中啟動 bash 工作階段：

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

**Layer 快取目錄名稱結構描述**

假設範本中定義的 LayerVersionArn， AWS SAM CLI會從 ARN 擷取 LayerName 和版本。它會建立目錄，將 layer 內容放置在名為 的 中`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 Image 標籤結構描述**

若要計算唯一圖層雜湊，請將所有唯一圖層名稱與 '-' 分隔符號結合，採用 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
```

唯一名稱的運算方式與 Layer Caching Directory 名稱結構描述相同：

```
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 SDK 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:`區段。

以下是 中託管之巢狀應用程式的 SAM 範本範例區段 AWS Serverless Application Repository：

```
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 EventBridge 排程器、支援 AWS SAM 提供什麼、如何建立排程器事件，以及在建立排程器事件時可以參考的範例的詳細資訊。

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

使用 EventBridge 排程器來排程 AWS SAM 範本中的事件。Amazon EventBridge Scheduler 是一種排程服務，可讓您在所有 AWS 服務中建立、啟動和管理數百萬個事件和任務。此服務對於時間相關事件特別有用。您可以使用它來排程事件和週期性的時間型調用。它還支援一次性事件，以及具有開始和結束時間的速率和時間運算式。

若要進一步了解 Amazon EventBridge 排程器，請參閱 [ EventBridge 排程器使用者指南中的什麼是 Amazon 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) 範本規格提供簡單的速記語法，您可以使用 AWS Lambda 和 的 EventBridge 排程器來排程事件 AWS Step Functions。

## 在 中建立 EventBridge 排程器事件 AWS SAM
<a name="using-eventbridge-scheduler-sam-create"></a>

將 `ScheduleV2` 屬性設定為 AWS SAM 範本中的事件類型，以定義 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 排程器使用者指南》中的為 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 排程器屬性，請參閱：
+ [ScheduleV2](sam-property-function-schedulev2.md) 適用於 `AWS::Serverless::Function`。
+ [ScheduleV2](sam-property-statemachine-statemachineschedulev2.md) 適用於 `AWS::Serverless::StateMachine`。

# 使用 協調 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 SAM CLI。若要檢查您擁有的版本，請執行命令 `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#/)會顯示狀態機器結構的圖形檢視，讓您可以以視覺化方式檢查狀態機器的邏輯並監控執行。

透過 Step Functions 支援 in AWS Serverless Application Model (AWS SAM)，您可以執行下列動作：
+ 直接在 AWS SAM 範本內或在個別檔案中定義狀態機器 
+ 透過 AWS SAM 政策範本、內嵌政策或受管政策建立狀態機器執行角色 
+ 使用 API Gateway 或 Amazon EventBridge 事件、依照 AWS SAM 範本中的排程，或直接呼叫 APIs 來觸發狀態機器執行
+ 針對常見的 Step Functions 開發模式使用可用的[AWS SAM 政策範本](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-policy-templates.html)。

## 範例
<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 開發人員指南*》中的[使用 建立 Step Functions 狀態機器 AWS SAM](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 函數中執行。這有助於讓組織免於在其部署管道中建置 gatekeeper 元件的負擔。

如需程式碼簽署的詳細資訊，請參閱《 *AWS Lambda 開發人員指南*》中的[設定 Lambda 函數的程式碼簽署](https://docs.aws.amazon.com/lambda/latest/dg/configuration-codesigning.html)。

您必須先使用 Signer 建立簽署設定檔，才能為無伺服器應用程式設定程式碼 AWS 簽署。您可以針對下列任務使用此簽署描述檔：

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 Resource Name (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. **簽署您的程式碼** – 使用 [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)命令搭配 `--signing-profiles`選項。

**注意**  
若要使用 `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
```

簽署函數程式碼和 layer，然後執行部署：

```
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`提示的詳細資訊，請參閱 命令參考[sam deploy](sam-cli-command-reference-sam-deploy.md)中的 AWS SAM CLI 。

# 驗證 AWS SAM 範本檔案
<a name="serverless-sam-cli-using-validate"></a>

使用 驗證您的範本`sam validate`。目前，此命令會驗證提供的範本是否為有效的 JSON/YAML。與大多數 AWS SAM CLI命令一樣，它預設會在您目前的工作目錄中尋找`template.[yaml|yml]`檔案。您可以使用 `-t`或 `--template`選項指定不同的範本檔案/位置。

範例：

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

**注意**  
`sam validate` 命令需要設定 AWS 登入資料。如需詳細資訊，請參閱[設定 AWS SAM CLI](using-sam-cli-configure.md)。