

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

# 無伺服器
<a name="serverless-pattern-list"></a>

**Topics**
+ [使用 AWS Amplify 建置無伺服器 React Native 行動應用程式](build-a-serverless-react-native-mobile-app-by-using-aws-amplify.md)
+ [透過單一控制平面管理多個 SaaS 產品的租用戶](manage-tenants-across-multiple-saas-products-on-a-single-control-plane.md)
+ [使用與靜態 IP 地址相關聯的端點，整合 Amazon S3 預先簽章的 URL 產生和物件下載](consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses.md)
+ [在組織中建立跨帳戶 Amazon EventBridge 連線](create-cross-account-amazon-eventbridge-connection-organization.md)
+ [使用 Kinesis Data Streams 和 Firehose 搭配 將 DynamoDB 記錄交付至 Amazon S3 AWS CDK](deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk.md)
+ [在 Amazon API Gateway 中使用自訂網域實作路徑型 API 版本控制](implement-path-based-api-versioning-by-using-custom-domains.md)
+ [將 psycopg2 程式庫匯入 AWS Lambda ，以與您的 PostgreSQL 資料庫互動](import-psycopg2-library-lambda.md)
+ [將 Amazon API Gateway 與 Amazon SQS 整合，以處理非同步 REST APIs](integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.md)
+ [使用 Amazon API Gateway 和 AWS Lambda 非同步處理事件](process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda.md)
+ [使用 Amazon API Gateway 和 Amazon DynamoDB Streams 非同步處理事件](processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams.md)
+ [使用 Amazon API Gateway、Amazon SQS 和 AWS Fargate 非同步處理事件](process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate.md)
+ [從 AWS Step Functions 同步執行 AWS Systems Manager 自動化任務 AWS Step Functions](run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions.md)
+ [在 AWS Lambda 函數中使用 Python 執行 S3 物件的平行讀取](run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function.md)
+ [將遙測資料從 AWS Lambda 傳送至 OpenSearch，以進行即時分析和視覺化](send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization.md)
+ [為以儲存格為基礎的架構設定無伺服器儲存格路由器](serverless-cell-router-architecture.md)
+ [透過 VPC 端點設定 Amazon S3 儲存貯體的私有存取權](set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint.md)
+ [AWS Step Functions 使用 Amazon Bedrock 對 中的狀態進行故障診斷](troubleshooting-states-in-aws-step-functions.md)
+ [更多模式](serverless-more-patterns-pattern-list.md)

# 使用 AWS Amplify 建置無伺服器 React Native 行動應用程式
<a name="build-a-serverless-react-native-mobile-app-by-using-aws-amplify"></a>

*Deekshitulu Pentakota，Amazon Web Services*

## 總結
<a name="build-a-serverless-react-native-mobile-app-by-using-aws-amplify-summary"></a>

此模式示範如何使用 AWS Amplify 和下列 AWS 服務，為 React Native 行動應用程式建立無伺服器後端：
+ AWS AppSync
+ Amazon Cognito
+ Amazon DynamoDB

在您使用 Amplify 設定和部署應用程式的後端之後，Amazon Cognito 會驗證應用程式使用者，並授權他們存取應用程式。然後AWS AppSync 會與前端應用程式和後端 DynamoDB 資料表互動，以建立和擷取資料。

**注意**  
此模式使用簡單的「ToDoList」應用程式做為範例，但您可以使用類似的程序來建立任何 React Native 行動應用程式。

## 先決條件和限制
<a name="build-a-serverless-react-native-mobile-app-by-using-aws-amplify-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ [Amplify 命令列界面 (Amplify CLI)](https://docs.amplify.aws/cli/start/install/)，已安裝並設定
+ XCode （任何版本）
+ Microsoft Visual Studio （任何版本、任何程式碼編輯器、任何文字編輯器）
+ 熟悉 Amplify
+ 熟悉 Amazon Cognito
+ 熟悉 AWS AppSync
+ 熟悉 DynamoDB
+ 熟悉 Node.js
+ 熟悉 npm
+ 熟悉 React 和 React Native
+ 熟悉 JavaScript 和 ECMAScript 6 (ES6)
+ 熟悉 GraphQL

## Architecture
<a name="build-a-serverless-react-native-mobile-app-by-using-aws-amplify-architecture"></a>

下圖顯示在 AWS 雲端中執行 React Native 行動應用程式後端的範例架構：

![\[使用 AWS 服務執行 React Native 行動應用程式的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/c95e0150-5762-4c90-946c-efa3a22913e4/images/5beff5f9-9d14-49dc-a046-b74e5bfbd13f.png)


圖表顯示下列架構：

1. Amazon Cognito 會驗證應用程式使用者，並授權他們存取應用程式。

1. 若要建立和擷取資料，AWS AppSync 會使用 GraphQL API 與前端應用程式和後端 DynamoDB 資料表互動。

## 工具
<a name="build-a-serverless-react-native-mobile-app-by-using-aws-amplify-tools"></a>

**AWS 服務**
+ [AWS Amplify](https://docs.aws.amazon.com/amplify/latest/userguide/welcome.html) 是一組專門建置的工具和功能，可協助前端 Web 和行動開發人員在 AWS 上快速建置完整堆疊的應用程式。
+ [AWS AppSync](https://docs.aws.amazon.com/appsync/latest/devguide/what-is-appsync.html) 提供可擴展的 GraphQL 介面，可協助應用程式開發人員結合來自多個來源的資料，包括 Amazon DynamoDB、AWS Lambda 和 HTTP APIs。
+ [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) 為 Web 和行動應用程式提供身分驗證、授權和使用者管理。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一項全受管 NoSQL 資料庫服務，可提供快速、可預期且可擴展的效能。

**Code**

此模式中使用的範例應用程式的程式碼可在 GitHub [aws-amplify-react-native-ios-todo-app](https://github.com/aws-samples/aws-amplify-react-native-ios-todo-app) 儲存庫中找到。若要使用範例檔案，請遵循此模式的** Epics** 區段中的指示。

## 史詩
<a name="build-a-serverless-react-native-mobile-app-by-using-aws-amplify-epics"></a>

### 建立並執行您的 React Native 應用程式
<a name="create-and-run-your-react-native-app"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 React Native 開發環境。 | 如需說明，請參閱 React Native 文件中的[設定開發環境](https://reactnative.dev/docs/next/environment-setup)。 | 應用程式開發人員 | 
| 在 iOS 模擬器中建立並執行 ToDoList React Native 行動應用程式。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html) | 應用程式開發人員 | 

### 初始化應用程式的新後端環境
<a name="initialize-a-new-backend-environment-for-the-app"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 Amplify 中建立支援應用程式所需的後端服務。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html)對於此模式中使用的 ToDoList 應用程式設定，請套用下列範例組態。**React Native Amplify 應用程式組態設定範例**<pre>? Name: ToDoListAmplify<br /><br />? Environment: dev<br /><br />? Default editor: Visual Studio Code<br /><br />? App type: javascript<br /><br />? Javascript framework: react-native<br /><br />? Source Directory Path: src<br /><br />? Distribution Directory Path: /<br /><br />? Build Command: npm run-script build<br /><br />? Start Command: npm run-script start<br /><br />? Select the authentication method you want to use: AWS profile<br /><br />? Please choose the profile you want to use: default</pre>如需詳細資訊，請參閱 [Amplify 開發中心文件中建立新的 Amplify 後端](https://docs.amplify.aws/lib/project-setup/create-application/q/platform/js/#create-a-new-amplify-backend)。`amplify init` 命令會使用 [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 佈建下列資源： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html) | 應用程式開發人員 | 

### 將 Amazon Cognito 身分驗證新增至 Amplify React Native 應用程式
<a name="add-amazon-cognito-authentication-to-your-amplify-react-native-app"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Amazon Cognito 身分驗證服務。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html)對於此模式中使用的 ToDoList 應用程式設定，請套用下列範例組態。**範例身分驗證服務組態設定**<pre>? Do you want to use the default authentication and security configuration? \ <br />Default configuration<br /> <br />? How do you want users to be able to sign in? \ <br />Username <br /><br />? Do you want to configure advanced settings? \ <br />No, I am done</pre>`amplify add auth` 命令會在專案根目錄中的本機資料夾 (**擴增**) 中建立必要的資料夾、檔案和相依性檔案。對於此模式中使用的 ToDoList 應用程式設定，系統會為此目的建立 **aws-exports.js**。 | 應用程式開發人員 | 
| 將 Amazon Cognito 服務部署至 AWS 雲端。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html)若要查看專案中已部署的服務，請執行下列命令，前往 Amplify 主控台：`amplify console` | 應用程式開發人員 | 
| 安裝 React Native 所需的 Amplify 程式庫，以及 iOS 的 CocoaPods 相依性。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html) | 應用程式開發人員 | 
| 匯入並設定 Amplify 服務。 | 在應用程式的進入點檔案中 （例如** App.js**)，輸入以下幾行程式碼匯入並載入 Amplify 服務的組態檔案：<pre>import Amplify from 'aws-amplify'<br />import config from './src/aws-exports'<br />Amplify.configure(config)</pre>如果您在應用程式進入點檔案中匯入 Amplify 服務後收到錯誤，請停止應用程式。然後，開啟 XCode 並從專案的 iOS 資料夾選取 **ToDoListAmplify.xcworkspace**，然後執行應用程式。 | 應用程式開發人員 | 
| 更新應用程式的進入點檔案，以使用 withAuthenticator 高階元件 (HOC)。 | `withAuthenticator` HOC 只會使用幾行程式碼，在您的應用程式中提供登入、註冊和忘記密碼工作流程。如需詳細資訊，請參閱 Amplify 開發中心中的[選項 1：使用預先建置的 UI 元件](https://docs.amplify.aws/lib/auth/getting-started/q/platform/js/#option-1-use-pre-built-ui-components)。此外，React 文件中的[高階元件](https://reactjs.org/docs/higher-order-components.html)。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html)**withAuthenticator HOC 程式碼範例**<pre>import Amplify from 'aws-amplify'<br />import config from './src/aws-exports'<br />Amplify.configure(config)<br />import { withAuthenticator } from 'aws-amplify-react-native';<br /><br /><br />const App = () => {<br />  return null;<br />};<br /><br /><br />export default withAuthenticator(App);</pre>在 iOS 模擬器中，應用程式會顯示 Amazon Cognito 服務提供的登入畫面。 | 應用程式開發人員 | 
| 測試身分驗證服務設定。 | 在 iOS 模擬器中，執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html)您也可以開啟 [Amazon Cognito 主控台](https://console.aws.amazon.com/cognito/)，並檢查是否已在**身分集**區中建立新的使用者。 | 應用程式開發人員 | 

### 將 AWS AppSync API 和 DynamoDB 資料庫連線至應用程式
<a name="connect-an-aws-appsync-api-and-dynamodb-database-to-the-app"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 AWS AppSync API 和 DynamoDB 資料庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html)對於此模式中使用的 ToDoList 應用程式設定，請套用下列範例組態。**範例 API 和資料庫組態設定**<pre>? Please select from one of the below mentioned services: \ <br />GraphQL <br /><br />? Provide API name: todolistamplify<br /><br />? Choose the default authorization type for the API \ <br />Amazon Cognito User Pool<br /><br />Do you want to use the default authentication and security configuration<br /><br />? Default configuration How do you want users to be able to sign in? \ <br />Username<br /><br />Do you want to configure advanced settings? \ <br />No, I am done.<br /><br />? Do you want to configure advanced settings for the GraphQL API \ <br />No, I am done.<br /><br />? Do you have an annotated GraphQL schema? \ <br />No<br /><br />? Choose a schema template: \ <br />Single object with fields (e.g., "Todo" with ID, name, description)<br /><br />? Do you want to edit the schema now? \ <br />Yes</pre>**GraphQL 結構描述範例**<pre> type Todo @model {<br />   id: ID!<br />   name: String!<br />   description: String<br />}</pre> | 應用程式開發人員 | 
| 部署 AWS AppSync API。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html)對於此模式中使用的 ToDoList 應用程式設定，請套用下列範例組態。**AWS AppSync API 組態設定範例**下列組態會在 AWS AppSync 中建立 GraphQL API，並在 Dynamo DB中建立 **Todo** 資料表。<pre> ? Are you sure you want to continue? Yes<br />? Do you want to generate code for your newly created GraphQL API Yes<br />? Choose the code generation language target javascript<br />? Enter the file name pattern of graphql queries, mutations and subscriptions src/graphql/**/*.js<br />? Do you want to generate/update all possible GraphQL operations - \ <br />queries, mutations and subscriptions Yes<br />? Enter maximum statement depth \<br />[increase from default if your schema is deeply nested] 2</pre> | 應用程式開發人員 | 
| 將應用程式的前端連接至 AWS AppSync API。 | 若要使用此模式中提供的範例 ToDoList 應用程式，請從 [aws-amplify-react-native-ios-todo-app](https://github.com/aws-samples/aws-amplify-react-native-ios-todo-app) GitHub 儲存庫中的 **App.js** 檔案複製程式碼。然後，將範例程式碼整合到您的本機環境。儲存庫的 **App.js** 檔案中提供的範例程式碼執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-serverless-react-native-mobile-app-by-using-aws-amplify.html) | 應用程式開發人員 | 

## 相關資源
<a name="build-a-serverless-react-native-mobile-app-by-using-aws-amplify-resources"></a>
+ [AWS Amplify](https://aws.amazon.com/amplify/)
+ [Amazon Cognito](https://aws.amazon.com/cognito/)
+ [AWS AppSync](https://aws.amazon.com/appsync/)
+ [Amazon DynamoDB](https://aws.amazon.com/dynamodb/)
+ [React](https://reactjs.org/) (React 文件） 

# 透過單一控制平面管理多個 SaaS 產品的租用戶
<a name="manage-tenants-across-multiple-saas-products-on-a-single-control-plane"></a>

*Ramanna Avancha、Kishan Kavala、Anusha Mandava 和 Jenifer Pascal，Amazon Web Services*

## 總結
<a name="manage-tenants-across-multiple-saas-products-on-a-single-control-plane-summary"></a>

此模式說明如何在 AWS 雲端的單一控制平面上管理多個軟體即服務 (SaaS) 產品的租用戶生命週期。提供的參考架構可協助組織減少其個別 SaaS 產品的備援、共用功能的實作，並提供大規模的控管效率。

大型企業可以在各種業務單位擁有多個 SaaS 產品。這些產品通常需要佈建供不同訂閱層級的外部租戶使用。如果沒有常見的租用戶解決方案，IT 管理員必須花時間跨多個 SaaS APIs 管理未區分的功能，而不是專注於核心產品功能開發。

此模式中提供的常見租戶解決方案有助於集中管理組織的許多共用 SaaS 產品功能，包括下列項目：
+ 安全
+ 租戶佈建
+ 租戶資料儲存
+ 租戶通訊
+ 產品管理
+ 指標記錄和監控

## 先決條件和限制
<a name="manage-tenants-across-multiple-saas-products-on-a-single-control-plane-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ Amazon Cognito 或第三方身分提供者 (IdP) 的知識
+ Amazon API Gateway 的知識
+ AWS Lambda 的知識
+ Amazon DynamoDB 的知識
+ 了解 AWS Identity and Access Management (IAM)
+ AWS Step Functions 的知識
+ 了解 AWS CloudTrail 和 Amazon CloudWatch
+ Python 程式庫和程式碼的知識
+ 了解 SaaS APIs，包括不同類型的使用者 （組織、租戶、管理員和應用程式使用者）、訂閱模型和租戶隔離模型
+ 了解組織的多產品 SaaS 需求和多租戶訂閱

**限制**
+ 此模式未涵蓋常見租用戶解決方案與個別 SaaS 產品之間的整合。
+ 此模式只會在單一 AWS 區域中部署 Amazon Cognito 服務。

## Architecture
<a name="manage-tenants-across-multiple-saas-products-on-a-single-control-plane-architecture"></a>

**目標技術堆疊**
+ Amazon API Gateway
+ Amazon Cognito
+ AWS CloudTrail
+ Amazon CloudWatch
+ Amazon DynamoDB
+ IAM
+ AWS Lambda
+ Amazon Simple Storage Service (Amazon S3)
+ Amazon Simple Notification Service (Amazon SNS)
+ AWS Step 函數

**目標架構**

下圖顯示管理 AWS 雲端中單一控制平面上多個 SaaS 產品的租用戶生命週期的範例工作流程。

![\[在單一控制平面上管理租用戶生命週期的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/4306bc76-22a7-45ca-a107-43df6c6f7ac8/images/700faf4d-c28f-4814-96aa-2d895cdcb518.png)


 該圖顯示以下工作流程：

1. AWS 使用者透過呼叫 API Gateway 端點，啟動租戶佈建、產品佈建或管理相關動作。

1. 使用者透過從 Amazon Cognito 使用者集區或其他 IdP 擷取的存取字符進行身分驗證。

1. 個別佈建或管理任務是由與 API Gateway API 端點整合的 Lambda 函數執行。

1. 通用租戶解決方案APIs （適用於租戶、產品和使用者） 會收集所有必要的輸入參數、標頭和字符。然後，管理 APIs會叫用相關聯的 Lambda 函數。

1. 管理 APIs和 Lambda 函數的 IAM 許可都由 IAM 服務驗證。

1. Lambda 函數會從 DynamoDB 和 Amazon S3 中的目錄 （適用於租戶、產品和使用者） 存放和擷取資料。

1. 驗證許可後，會叫用 AWS Step Functions 工作流程來執行特定任務。圖表中的範例顯示租用戶佈建工作流程。

1. 個別 AWS Step Functions 工作流程任務會在預先定義的工作流程 （狀態機器） 中執行。

1. 從 DynamoDB 或 Amazon S3 擷取執行與每個工作流程任務相關聯的 Lambda 函數所需的任何必要資料。可能需要使用 AWS CloudFormation 範本佈建其他 AWS 資源。

1. 如有需要，工作流程會傳送請求，為特定 SaaS 產品佈建額外的 AWS 資源到該產品的 AWS 帳戶。

1. 當請求成功或失敗時，工作流程會將狀態更新作為訊息發佈至 Amazon SNS 主題。

1. Amazon SNS 已訂閱 Step Functions 工作流程的 Amazon SNS 主題。

1. 然後，Amazon SNS 會將工作流程狀態更新傳回給 AWS 使用者。

1. 每個 AWS 服務動作的日誌，包括 API 呼叫的稽核線索，都會傳送至 CloudWatch。您可以在 CloudWatch 中為每個使用案例設定特定規則和警示。

1. 日誌會封存在 Amazon S3 儲存貯體中以供稽核之用。

**自動化和擴展**

此模式使用 CloudFormation 範本來協助自動化常見租用戶解決方案的部署。範本也可以協助您快速擴展或縮減相關聯的資源。

如需詳細資訊，請參閱《[AWS CloudFormation 使用者指南》中的使用](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html) *AWS CloudFormation *範本。

## 工具
<a name="manage-tenants-across-multiple-saas-products-on-a-single-control-plane-tools"></a>

**AWS 服務**
+ [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 可協助您建立、發佈、維護、監控和保護任何規模的 REST、HTTP 和 WebSocket APIs。
+ [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) 為 Web 和行動應用程式提供身分驗證、授權和使用者管理。
+ [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) 可協助您稽核 AWS 帳戶的控管、合規和營運風險。
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可協助您即時監控 AWS 資源的指標，以及您在 AWS 上執行的應用程式。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一項全受管 NoSQL 資料庫服務，可提供快速、可預期且可擴展的效能。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 可透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一種運算服務，可協助您執行程式碼，而無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [Amazon Simple Notification Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可協助您協調和管理發佈者和用戶端之間的訊息交換，包括 Web 伺服器和電子郵件地址。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 AWS Lambda 函數和其他 AWS 服務來建置業務關鍵應用程式。

## 最佳實務
<a name="manage-tenants-across-multiple-saas-products-on-a-single-control-plane-best-practices"></a>

此模式中的解決方案使用單一控制平面來管理多個租用戶的加入，以及佈建對多個 SaaS 產品的存取。控制平面可協助管理使用者管理其他四個功能特定的平面：
+ 安全平面
+ 工作流程平面
+ 通訊平面
+ 記錄和監控平面

## 史詩
<a name="manage-tenants-across-multiple-saas-products-on-a-single-control-plane-epics"></a>

### 設定安全平面
<a name="configure-the-security-plane"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 為您的多租戶 SaaS 平台建立需求。 | 建立下列項目的詳細需求：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html) | 雲端架構師、AWS 系統管理員 | 
| 設定 Amazon Cognito 服務。 | 請遵循《[Amazon Cognito 開發人員指南》](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-getting-started.html)*中的 Amazon Cognito *入門中的指示。 | 雲端架構師 | 
| 設定所需的 IAM 政策。 | 為您的使用案例建立所需的 IAM 政策。然後，將政策映射至 Amazon Cognito 中的 IAM 角色。如需詳細資訊，請參閱《*Amazon Cognito 開發人員指南*》中的[使用政策和](https://docs.aws.amazon.com/cognito/latest/developerguide/security-iam.html#security_iam_access-manage)[角色型存取控制管理存取權](https://docs.aws.amazon.com/cognito/latest/developerguide/role-based-access-control.html)。 | 雲端管理員、雲端架構師、AWS IAM 安全性 | 
| 設定所需的 API 許可。 | 使用 IAM 角色和政策以及 Lambda 授權方來設定 API Gateway 存取許可。如需說明，請參閱《*Amazon API Gateway 開發人員指南*》中的下列章節：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html) | 雲端管理員、雲端架構師 | 

### 設定資料平面
<a name="configure-the-data-plane"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立所需的資料目錄。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html)如需詳細資訊，請參閱《Amazon [ DynamoDB 開發人員指南》中的設定 ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SettingUp.html)DynamoDB。 * DynamoDB * | DBA | 

### 設定控制平面
<a name="configure-the-control-plane"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Lambda 函數和 API Gateway APIs 以執行必要的控制平面任務。 | 建立個別的 Lambda 函數和 API Gateway APIs，以新增、刪除和管理下列項目：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html)如需詳細資訊，請參閱《[AWS Lambda 開發人員指南》中的搭配 Amazon API Gateway 使用](https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html) AWS Lambda。 *AWS Lambda * | 應用程式開發人員 | 

### 設定工作流程平面
<a name="configure-the-workflow-plane"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 識別 AWS Step Functions 工作流程必須執行的任務。 | 識別並記錄下列項目的詳細 AWS Step Functions 工作流程需求：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html)確定主要利益相關者核准要求。 | 應用程式擁有者 | 
| 建立所需的 AWS Step Functions 工作流程。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html) | 應用程式開發人員、建置領導 | 

### 設定通訊平面
<a name="configure-the-communication-plane"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Amazon SNS 主題。 | 建立 Amazon SNS 主題以接收有關下列項目的通知：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html)如需詳細資訊，請參閱《*Amazon SNS * [SNS 開發人員指南》中的建立 SNS 主題](https://docs.aws.amazon.com/sns/latest/dg/sns-create-topic.html)。 | 應用程式擁有者、雲端架構師 | 
| 訂閱端點至每個 Amazon SNS 主題。 | 若要接收發佈至 Amazon SNS 主題的訊息，您必須訂閱每個主題的端點。如需詳細資訊，請參閱《[Amazon SNS 開發人員指南》中的訂閱 Amazon SNS 主題](https://docs.aws.amazon.com/sns/latest/dg/sns-create-subscribe-endpoint-to-topic.html)。 *Amazon SNS * | 應用程式開發人員、雲端架構師 | 

### 設定記錄和監控平面
<a name="configure-the-logging-and-monitoring-plane"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 為常用租用戶解決方案的每個元件啟用記錄。 | 為您建立的通用租用戶解決方案中的每個資源在元件層級啟用記錄。如需詳細說明，請參閱下列主題：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html)您可以使用 IAM 政策，將每個資源的日誌合併到集中式日誌帳戶。如需詳細資訊，請參閱[集中式記錄和多帳戶安全護欄](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/centralized-logging-and-multiple-account-security-guardrails.html)。 | 應用程式開發人員、AWS 系統管理員、雲端管理員 | 

### 佈建和部署通用租戶解決方案
<a name="provision-and-deploy-the-common-tenant-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 CloudFormation 範本。 | 使用 CloudFormation 範本，自動化完整通用租用戶解決方案及其所有元件的部署和維護。如需詳細資訊，請參閱 [https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)。 | 應用程式開發人員、DevOps 工程師、CloudFormation 開發人員 | 

## 相關資源
<a name="manage-tenants-across-multiple-saas-products-on-a-single-control-plane-resources"></a>
+ [使用 Amazon Cognito 使用者集區做為授權方控制對 REST API 的存取](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html) (*Amazon API Gateway 開發人員指南*)
+ [使用 API Gateway Lambda 授權方](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html) (*Amazon API Gateway 開發人員指南*)
+ [Amazon Cognito 使用者集區 ](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools.html)(*Amazon Cognito 開發人員指南*)
+ [跨帳戶跨區域 CloudWatch 主控台](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Cross-Account-Cross-Region.html) (*Amazon CloudWatch 使用者指南*)

# 使用與靜態 IP 地址相關聯的端點，整合 Amazon S3 預先簽章的 URL 產生和物件下載
<a name="consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses"></a>

*Song Jin、Eunhye Jo 和 Amazon Web Services Jun Soung Lee*

## 總結
<a name="consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses-summary"></a>

此模式透過為物件下載建立安全的自訂預先簽章 URLs，簡化對 Amazon Simple Storage Service (Amazon S3) 的存取。解決方案提供具有唯一網域和靜態 IP 地址的單一端點。它專為需要在具有靜態 IP 地址的統一網域下整合 API 和 Amazon S3 端點的客戶量身打造。使用案例涉及遵循 IP 和網域允許清單防火牆政策的使用者，限制對特定網域和 IP 地址的 API 存取。

架構採用金鑰 AWS 服務，包括 AWS Global Accelerator Amazon API Gateway、 AWS Lambda Application Load Balancer AWS PrivateLink和 Amazon S3。此設計集中在單一網域下產生預先簽章 URLs和 Amazon S3 端點的 API，並連結至具有兩個靜態 IP 地址的 加速器。因此，使用者可以輕鬆地請求預先簽章URLs，並透過具有靜態 IP 地址的統一網域端點下載 Amazon S3 物件。

此架構特別有利於具有嚴格政策或合規要求的客戶，例如公有、醫療和金融領域的客戶。

## 先決條件和限制
<a name="consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ 自訂網域名稱的公有託管區域
+ 在您選擇的 AWS Certificate Manager (ACM) 中匯入 AWS 區域 的網域

**限制**
+ Amazon S3 儲存貯體名稱必須符合端點的網域名稱。此要求旨在確保可透過單一 API 端點提供 Amazon S3 端點。
+ API Gateway 中使用的自訂網域名稱應與單一 API 端點的網域名稱相符。
+ 有些 AWS 服務 完全無法使用 AWS 區域。如需區域可用性，請參閱[AWS 依區域的服務](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然後選擇服務的連結。

## Architecture
<a name="consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses-architecture"></a>

下圖顯示此模式的目標架構和工作流程。

![\[預先簽章 URL 產生和物件下載的元件和工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e19ebcb5-2138-481e-952e-3cfee9ad9e97/images/effd197c-d4d7-4990-8b66-3eb1c64aab4c.png)


圖表說明下列概念和工作流程：

1. 使用者使用透過 提供的自訂端點 AWS Global Accelerator，使用自訂網域名稱和相關聯的 IP 地址，啟動產生預先簽章 URL 的請求。

1. Lambda 函數會產生預先簽章的 URL，指向自訂端點。它會以 301 重新導向回應，其中包含產生的預先簽章 URL。透過重新導向的預先簽章 URL，使用者會使用透過 Global Accelerator 提供的自訂端點自動下載物件。

預先簽章 URL 產生和物件下載工作流程的整體架構元件如下：
+ 由 Global Accelerator 佈建靜態 IP 地址。
+ 使用自訂網域名稱，將加速器的別名註冊為 Amazon Route 53 公有託管區域的 A 記錄。
+ 建立儲存貯體名稱符合已註冊自訂網域名稱的 Amazon S3 儲存貯體。
+ 建立 API Gateway 和 Amazon S3 服務的 VPC 端點。
+ 要連線至 Global Accelerator 的內部 Application Load Balancer 組態。
+ 指派已連接 ACM 憑證之 API Gateway 的自訂網域名稱。
+ 部署與 Lambda 函數整合的私有 API Gateway。
+ Lambda 函數配備連接的 AWS Identity and Access Management (IAM) 角色 （具有 [GetObject](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html) 許可）。

## 工具
<a name="consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses-tools"></a>

**AWS 服務**
+ [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 可協助您建立、發佈、維護、監控和保護任何規模的 REST、HTTP 和 WebSocket APIs。
+ [Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/) 會將傳入的應用程式流量分散到多個可用區域中的多個目標，例如 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。
+ [AWS Certificate Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) 可協助您建立、存放和續約公有和私有 SSL/TLS X.509 憑證和金鑰，以保護 AWS 網站和應用程式。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端 基礎設施。
+ [AWS Global Accelerator](https://docs.aws.amazon.com/global-accelerator/latest/dg/what-is-global-accelerator.html) 是一種全域服務，支援多個 中的端點 AWS 區域。您可以建立加速器，透過 AWS 全球網路將流量導向最佳端點。如此可改善網際網路應用程式的可用性和效能，提升全球觀眾的使用體驗。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需支付使用的運算時間。
+ [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html) 可協助您建立從虛擬私有雲端 (VPCs) 到 VPC 外部服務的單向私有連線。
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一種可用性高、可擴展性強的 DNS Web 服務。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

**其他工具**
+ [Terraform](https://www.terraform.io/) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。

**程式碼儲存庫**

您可以根據您的偏好，使用 AWS CDK 或 Terraform 部署此模式。[Epics](#consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses-epics) 區段包含兩種部署方法的說明。此模式的程式碼可在下列 GitHub 儲存庫中使用：
+ **AWS CDK** – [s3-presignedurl-staticips-endpoint-with-cdk](https://github.com/aws-samples/s3-presignedurl-staticips-endpoint-with-cdk)
+ **Terraform** – [s3-presignedurl-staticips-endpoint-with-terraform](https://github.com/aws-samples/s3-presignedurl-staticips-endpoint-with-terraform)

## 最佳實務
<a name="consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses-best-practices"></a>
+ 為了增強生產環境中的安全性，請務必實作授權機制，例如 [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html)，以限制對`PresignedUrl`世代 API 的存取。
+ 遵循最低權限原則，並授予執行任務所需的最低許可。如需詳細資訊，請參閱 IAM 文件中的[授予最低權限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv)和[安全最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)。

## 史詩
<a name="consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses-epics"></a>

### 準備環境
<a name="prepare-the-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 決定網域名稱。 | 決定統一 Amazon S3 端點的公有網域名稱。網域名稱也會用作 Amazon S3 儲存貯體名稱。 | AWS 管理員、網路管理員 | 
| 建立公有的託管區域。 | 在 Amazon Route 53 中建立[公有託管區域](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingHostedZone.html)。其網域名稱必須與 API Gateway 中使用的網域名稱相符。 | AWS 管理員、網路管理員 | 
| 準備 SSL 憑證。 | 使用 AWS Certificate Manager (ACM) 為您的 Web 應用程式網域[請求](https://docs.aws.amazon.com/acm/latest/userguide/acm-public-certificates.html)或[匯入](https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html) SSL 憑證。 | AWS 管理員、網路管理員 | 

### 使用 Terraform 部署模式
<a name="deploy-the-pattern-with-terraform"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 Terraform 開發環境。 | 若要設定開發環境，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses.html) | AWS 管理員、雲端管理員 | 
| 修改 `.tfvars`和 ** **`provider.tf` 檔案。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses.html)**注意下列事項：**[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses.html) | AWS 管理員、雲端管理員 | 
| 佈建網路資源。 | 若要佈建網路資源，請執行下列命令：<pre>cd ./2.vpc_alb_ga<br />terraform init<br />terraform plan --var-file=apg.tfvars<br />terraform apply --var-file=apg.tfvars</pre>在`apply `命令執行期間，出現提示時輸入 **yes**。 | AWS 管理員、雲端管理員 | 
| 佈建 API Gateway、Amazon S3 和 Lambda。 | 若要佈建網路資源，請使用下列命令：<pre>cd ./2.apigw_s3_lambda<br />terraform init<br />terraform plan --var-file=apg.tfvars<br />terraform apply --var-file=apg.tfvars</pre> | AWS 管理員、雲端管理員 | 

### 使用 部署模式 AWS CDK
<a name="deploy-the-pattern-with-cdk"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 AWS CDK 開發環境。 | 若要設定開發環境，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses.html) | AWS 管理員、雲端管理員 | 
| 在 `config/index.ts` 檔案中設定網域設定。 | 若要編輯常數變數的選項，請使用下列命令：<pre>export const options = {<br />    certificateArn: '{arn of the acm which created before}',<br />    dnsAttr: {<br />        zoneName: '{public hosted zone name}',<br />        hostedZoneId: 'hosted zone Id',<br />    },<br />    domainNamePrefix: '{Prefix for the domain}',<br />    presignPath: 'presign',<br />    objectsPath: 'objects',<br />};</pre>在命令中，將每個預留位置取代為您自己的資訊：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses.html) | AWS 管理員、雲端管理員 | 
| 部署堆疊。 | 若要部署兩個堆疊，一個用於虛擬私有雲端 (VPC)，另一個用於應用程式，請使用下列命令：<pre>$ npm install <br />$ cdk synth <br />$ cdk deploy --all</pre> | AWS 管理員、雲端管理員 | 

### 測試模式
<a name="test-the-pattern"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證端點的 IP 地址。 | 若要驗證此模式的網域具有靜態 IP 地址，請使用下列命令：<pre>nslookup ${s3-bucket-prefix}.${domain}</pre> | 網路管理員 | 
| 上傳您稍後可以下載的測試檔案。 | 將測試檔案上傳至 Amazon S3 儲存貯體中的 `'/objects'` 資料夾。 | AWS 管理員、雲端管理員 | 
| 叫用 API 以產生預先簽章的 URL。 | 若要產生預先簽章的 URL，請使用下列格式從瀏覽器或 API 用戶端 （例如 [Postman](https://www.postman.com/product/what-is-postman/)) 呼叫 URL：<pre>https://${s3-bucket-prefix}.${domain}/presign/objects/${uploaded-filename}</pre>將 `${s3-bucket-prefix}`和 中的預留位置值取代為您在先前步驟中設定`${domain}`的值。 | 應用程式擁有者 | 
| 檢查結果。 | 預期的結果是您應該會收到 301 （移動永久） 重新導向狀態碼。此回應將包含預先簽章的 URL，應會自動啟動測試檔案的下載。 | 測試工程師 | 

### 使用 Terraform 清除
<a name="clean-up-with-terraform"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 銷毀 API Gateway、Amazon S3 和 Lambda 資源。 | 若要刪除資源，請使用下列命令：<pre>cd ./2.apigw_s3_lambda<br />terraform init<br />terraform plan --destroy --var-file=apg.tfvars<br />terraform destroy --var-file=apg.tfvars<br /></pre> | AWS 管理員、雲端管理員 | 
| 銷毀網路資源。 | 若要刪除網路資源，請使用下列命令：<pre>cd ./1.vpc_alb_ga<br />terraform init<br />terraform plan --destroy --var-file=apg.tfvars<br />terraform destroy --var-file=apg.tfvars<br /></pre> | AWS 管理員、雲端管理員 | 

### 使用 清除 AWS CDK
<a name="clean-up-with-cdk"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 銷毀堆疊。 | 若要同時銷毀 VPC 和應用程式堆疊，請使用下列命令：<pre>$ cdk destroy --all</pre> | AWS 管理員、雲端管理員 | 
| 清空並刪除 Amazon S3 儲存貯體。 | [清空](https://docs.aws.amazon.com/AmazonS3/latest/userguide/empty-bucket.html)並[刪除](https://docs.aws.amazon.com/AmazonS3/latest/userguide/delete-bucket.html)物件 Amazon S3 儲存貯體，以及預設不會刪除的日誌 Amazon S3 儲存貯體。Amazon S3 儲存貯體名稱為 `${s3-bucket-prefix}.${domain}`和 `${s3-bucket-prefix}.${domain}-logs`。如果您偏好使用 [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 刪除儲存貯體，請使用下列命令：<pre>$ aws s3 rm s3://${s3-bucket-prefix}.${domain} --recursive<br />$ aws s3 rb s3://${s3-bucket-prefix}.${domain} --force<br />$ aws s3 rm s3://${s3-bucket-prefix}.${domain}-logs --recursive<br />$ aws s3 rb s3://${s3-bucket-prefix}.${domain}-logs --force</pre>將 `${s3-bucket-prefix}`和 取代`${domain}`為您在先前步驟中設定的值。，/p> | AWS 管理員、雲端管理員 | 

## 相關資源
<a name="consolidate-amazon-s3-presigned-url-generation-and-object-downloads-by-using-an-endpoint-associated-with-static-ip-addresses-resources"></a>

**AWS 部落格**
+ [透過 提供的靜態 IP 地址存取 Amazon API Gateway AWS Global Accelerator](https://aws.amazon.com/blogs/networking-and-content-delivery/accessing-an-aws-api-gateway-via-static-ip-addresses-provided-by-aws-global-accelerator/) 
+ [在 JavaScript 的模組化中產生預先簽章 AWS CDK 的 URL JavaScript](https://aws.amazon.com/blogs/developer/generate-presigned-url-modular-aws-sdk-javascript/) 
+ [使用 ALB、S3 和 PrivateLink 託管內部 HTTPS 靜態網站](https://aws.amazon.com/blogs/networking-and-content-delivery/hosting-internal-https-static-websites-with-alb-s3-and-privatelink/) 

# 在組織中建立跨帳戶 Amazon EventBridge 連線
<a name="create-cross-account-amazon-eventbridge-connection-organization"></a>

*Sam Wilson 和 Robertstone，Amazon Web Services*

## 總結
<a name="create-cross-account-amazon-eventbridge-connection-organization-summary"></a>

大型分散式系統使用 Amazon EventBridge 來傳達 AWS Organizations 組織中各種 Amazon Web Services (AWS) 帳戶之間的狀態變更。不過，EventBridge 通常只能以相同 中的端點或取用者為目標 AWS 帳戶。例外狀況是不同帳戶中的事件匯流排。該事件匯流排是有效的目標。若要使用來自另一個帳戶中事件匯流排的事件，必須將事件從來源帳戶的事件匯流排推送到目的地帳戶的事件匯流排。為了避免在不同應用程式中管理關鍵事件時遇到挑戰 AWS 帳戶，請使用此模式中顯示的建議方法。

此模式說明如何使用涉及 AWS 帳戶 AWS Organizations 組織中多個 的 EventBridge 實作事件驅動型架構。模式使用 AWS Cloud Development Kit (AWS CDK) Toolkit 和 AWS CloudFormation。

EventBridge 提供無伺服器事件匯流排，可協助您接收、篩選、轉換、路由和交付事件。EventBridge 是事件驅動架構的關鍵元件，支援訊息生產者與這些訊息消費者之間的區隔。在單一帳戶中，這是直接的。多帳戶結構需要一個帳戶中事件匯流排上的事件的額外考量，才能在相同組織內的其他帳戶中使用。

如需生產者和消費者帳戶特定考量的相關資訊，請參閱[其他資訊](#create-cross-account-amazon-eventbridge-connection-organization-additional)一節。

## 先決條件和限制
<a name="create-cross-account-amazon-eventbridge-connection-organization-prereqs"></a>

**先決條件**
+ 至少有兩個關聯的 AWS Organizations 組織 AWS 帳戶
+ 兩者中的 AWS Identity and Access Management (IAM) 角色 AWS 帳戶 ，可讓您 AWS 帳戶 使用 在兩者中佈建基礎設施 AWS CloudFormation
+ [本機安裝](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)的 Git
+ AWS Command Line Interface 在[本機安裝](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (AWS CLI)
+ 在AWS CDK [本機安裝](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) ，並在兩者中[引導](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html#bootstrapping-howto) AWS 帳戶

**產品版本**

此模式已使用下列工具和版本建置和測試：
+ AWS CDK 工具組 2.126.0
+ Node.js 18.19.0
+ npm 10.2.3
+ Python 3.12

此模式應適用於任何版本的 AWS CDK v2 或 npm。Node.js 13.0.0 到 13 AWS CDK.6.0 版與 不相容。

## Architecture
<a name="create-cross-account-amazon-eventbridge-connection-organization-architecture"></a>

**目標架構**

下圖顯示從一個帳戶推送事件並在另一個帳戶中使用事件的架構工作流程。

![\[連接來源生產者帳戶和目的地消費者帳戶的三個步驟程序。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/34a5f3ae-511d-4636-999f-c73396770117/images/ccc4878a-6281-4a77-a483-4e6f299d7807.png)


工作流程包含下列步驟：

1. 來源帳戶中的生產者 AWS Lambda 函數會在帳戶的 EventBridge 事件匯流排上放置事件。

1. 跨帳戶 EventBridge 規則會將事件路由到目的地帳戶中的 EventBridge 事件匯流排。

1. 目的地帳戶中的 EventBridge 事件匯流排具有目標 Lambda 規則，可叫用 Consumer Lambda 函數。

最佳實務是使用[無效字母佇列 (DLQ)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-dead-letter-queues.html) 來處理消費者 Lambda 函數的失敗調用。不過，為了清楚起見，此解決方案省略了 DLQ。若要進一步了解如何在工作流程中實作 DLQ，並改善工作流程從失敗中復原的能力，請參閱[實作 AWS Lambda 錯誤處理模式](https://aws.amazon.com/blogs/compute/implementing-aws-lambda-error-handling-patterns/)部落格文章。

**自動化和擴展**

AWS CDK 會自動佈建所需的架構。EventBridge 可以根據 擴展到每秒數千筆記錄 AWS 區域。如需詳細資訊，請參閱 [Amazon EventBridge 配額文件](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-quota.html)。

## 工具
<a name="create-cross-account-amazon-eventbridge-connection-organization-tools"></a>

**AWS 服務**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端 基礎設施。此模式使用 [AWS CDK Toolkit](https://docs.aws.amazon.com/cdk/latest/guide/cli.html)，這是一個命令列雲端開發套件，可協助您與 AWS CDK 應用程式互動。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一種無伺服器事件匯流排服務，可協助您將應用程式與來自各種來源的即時資料連線。例如， AWS Lambda 函數、使用 API 目的地的 HTTP 調用端點，或其他事件匯流排 AWS 帳戶。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需支付使用的運算時間。
+ [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html) 是一種帳戶管理服務，可協助您將多個 合併 AWS 帳戶 到您建立並集中管理的組織。

**其他工具**
+ [Node.js](https://nodejs.org/en/docs/) 是一種事件驅動的 JavaScript 執行期環境，旨在建置可擴展的網路應用程式。
+ [npm](https://docs.npmjs.com/about-npm) 是在 Node.js 環境中執行的軟體登錄檔，用於共用或借用套件和管理私有套件的部署。
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [cross-account-eventbridge-in-organization](https://github.com/aws-samples/aws-cdk-examples/tree/main/python/cross-account-eventbridge-in-organization) 儲存庫中使用。

## 最佳實務
<a name="create-cross-account-amazon-eventbridge-connection-organization-best-practices"></a>

如需使用 EventBridge 時的最佳實務，請參閱下列資源：
+ [Amazon EventBridge 事件模式的最佳實務](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-patterns-best-practices.html)
+ [在 Amazon EventBridge 中定義規則時的最佳實務](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-rules-best-practices.html)

## 史詩
<a name="create-cross-account-amazon-eventbridge-connection-organization-epics"></a>

### 準備您的本機 AWS CDK 部署環境
<a name="prepare-your-local-cdk-deployment-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定來源帳戶和目的地帳戶的本機登入資料。 | 檢閱[設定新的組態和登入](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-quickstart.html#getting-started-quickstart-new)資料，並使用對您的環境最有意義的身分驗證和登入資料方法。請務必 AWS CLI 為來源帳戶和目的地帳戶身分驗證設定 。這些指示假設您已在本機設定兩個 AWS 設定檔： `sourceAccount`和 `destinationAccount`。 | 應用程式開發人員 | 
| 同時引導兩者 AWS 帳戶。 | 若要引導帳戶，請執行下列命令：<pre>cdk bootstrap --profile sourceAccount<br />cdk bootstrap --profile destinationAccount</pre> | 應用程式開發人員 | 
| 複製模式程式碼。 | 若要複製儲存庫，請執行下列命令：<pre>git clone git@github.com:aws-samples/aws-cdk-examples.git</pre>然後，將目錄變更為新複製的專案資料夾：<pre>cd aws-cdk-examples/python/cross-account-eventbridge-in-organization</pre> | 應用程式開發人員 | 

### 將 ProducerStack 部署至來源帳戶
<a name="deploy-producerstack-to-the-source-account"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| `cdk.json` 使用 AWS Organizations 和 帳戶詳細資訊修改 。 | 在專案的根資料夾中，對 進行下列變更`cdk.json`：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-cross-account-amazon-eventbridge-connection-organization.html) | 應用程式開發人員 | 
| 部署 ProducerStack 資源。 | 從專案的根目錄執行下列命令：<pre>cdk deploy ProducerStack --profile sourceAccount</pre>出現提示時，請接受透過 建立的新 IAM 角色和其他安全相關許可 AWS CloudFormation。 | 應用程式開發人員 | 
| 確認已部署 ProducerStack 資源。 | 若要驗證資源，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-cross-account-amazon-eventbridge-connection-organization.html) | 應用程式開發人員 | 

### 將 ConsumerStack 部署至目的地帳戶
<a name="deploy-consumerstack-to-the-destination-account"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 ConsumerStack 資源。 | 從專案的根目錄執行下列命令：<pre>cdk deploy ConsumerStack --profile destinationAccount</pre>出現提示時，請接受透過 建立的新 IAM 角色和其他安全相關許可 CloudFormation。 | 應用程式開發人員 | 
| 確認已部署 ConsumerStack 資源 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-cross-account-amazon-eventbridge-connection-organization.html) | 應用程式開發人員 | 

### 產生和使用事件
<a name="produce-and-consume-events"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 叫用 Producer Lambda 函數。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-cross-account-amazon-eventbridge-connection-organization.html) | 應用程式開發人員 | 
| 確認已收到事件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-cross-account-amazon-eventbridge-connection-organization.html) | 應用程式開發人員 | 

### 清除
<a name="cleanup"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 銷毀 ConsumerStack 資源。 | 如果您使用此模式做為測試，請清除已部署的資源，以避免產生額外費用。從專案的根目錄執行下列命令：<pre>cdk destroy ConsumerStack --profile destinationAccount</pre>系統會提示您確認刪除堆疊。 | 應用程式開發人員 | 
| 銷毀 ProducerStack 資源。 | 從專案的根目錄執行下列命令：<pre>cdk destroy ProducerStack --profile sourceAccount</pre>系統會提示您確認刪除堆疊。 | 應用程式開發人員 | 

## 疑難排解
<a name="create-cross-account-amazon-eventbridge-connection-organization-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 目的地帳戶中未收到任何事件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-cross-account-amazon-eventbridge-connection-organization.html) | 
| 從主控台叫用 Lambda 函數會傳回下列錯誤：`User: arn:aws:iam::123456789012:user/XXXXX is not authorized to perform: lambda:Invoke` | 請聯絡您的 AWS 帳戶 管理員，以取得 `ProducerStack-ProducerLambdaXXXX` Lambda 函數的適當`lambda:Invoke`動作許可。 | 

## 相關資源
<a name="create-cross-account-amazon-eventbridge-connection-organization-resources"></a>

**參考**
+ [AWS Organizations 使用者指南](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)
+ [Amazon EventBridge 事件模式](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-patterns.html)
+ [Amazon EventBridge 中的規則](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-rules.html)

**教學課程和影片**
+ [教學課程：建立和設定組織](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_tutorials_basic.html)
+ [AWS re：Invent 2023 - 使用 Amazon EventBridge (COM301-R) 的進階事件驅動模式](https://www.youtube.com/watch?v=6X4lSPkn4ps)

## 其他資訊
<a name="create-cross-account-amazon-eventbridge-connection-organization-additional"></a>

**製作者規則**

在來源帳戶中，建立 EventBridge 事件匯流排以接受來自生產者的訊息 （如*架構*一節所示）。在此事件匯流排上建立具有隨附 IAM 許可的規則。這些規則會根據下列`cdk.json`結構，以目的地帳戶中的 EventBridge 事件匯流排為目標：

```
"rules": [
  {
    "id": "CrossAccount",
    "sources": ["Producer"],
    "detail_types": ["TestType"],
    "targets": [
      {
        "id": "ConsumerEventBus",
        "arn": "arn:aws:events:us-east-2:012345678901:event-bus/CrossAccount"
      }
    ]
  }
]
```

對於每個耗用事件匯流排，必須包含事件模式和目標事件匯流排。

*事件模式*

[事件模式](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-patterns.html)會篩選此規則將套用的事件。基於此範例，事件來源和記錄會`detail_types`識別要從來源帳戶的事件匯流排傳輸哪些事件到目的地帳戶的事件匯流排。

*目標事件匯流排*

此規則以另一個帳戶中存在的事件匯流排為目標。需要完整 `arn`(Amazon Resource Name) 才能唯一識別目標事件匯流排，而 `id`是 使用的[邏輯 ID](https://docs.aws.amazon.com/cdk/v2/guide/identifiers.html#identifiers_logical_ids) AWS CloudFormation。建立目標規則時，目標事件匯流排實際上不需要存在。

**目的地帳戶特定的考量事項**

在目的地帳戶中，會建立 EventBridge 事件匯流排，以從來源帳戶的事件匯流排接收訊息。若要允許從來源帳戶發佈事件，您必須建立以[資源為基礎的政策](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-use-resource-based.html)：

```
{
  "Version": "2012-10-17",		 	 	 
  "Statement": [{
    "Sid": "AllowOrgToPutEvents",
    "Effect": "Allow",
    "Principal": "*",
    "Action": "events:PutEvents",
    "Resource": "arn:aws:events:us-east-2:012345678901:event-bus/CrossAccount",
    "Condition": {
      "StringEquals": {
        "aws:PrincipalOrgID": "o-XXXXXXXXX"
      }
    }
  }]
}
```

特別重要的是授予`events:PutEvents`許可，允許同一組織中的任何其他帳戶發佈事件到此事件匯流排。將 `aws:PrincipalOrgId`設定為組織 ID 會授予所需的許可。

**事件模式**

您可以修改包含的事件模式，以符合您的使用案例：

```
rule = events.Rule(
    self,
    self.id + 'Rule' + rule_definition['id'],
    event_bus=event_bus,
    event_pattern=events.EventPattern(
        source=rule_definition['sources'],
        detail_type=rule_definition['detail_types'],
    )
)
```

為了減少不必要的處理，事件模式應指定只有目的地帳戶要處理的事件才會傳輸到目的地帳戶的事件匯流排。

*以資源為基礎的政策*

此範例使用組織 ID 來控制允許哪些帳戶在目的地帳戶的事件匯流排上放置事件。考慮使用更嚴格的政策，例如指定來源帳戶。

*EventBridge 配額*

請記住下列[配額](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-quota.html)：
+ 每個事件匯流排 300 個規則是預設配額。這可以視需要擴展，但應該適合大多數的使用案例。
+ 每個規則允許五個目標。我們建議應用程式架構師為每個目的地帳戶使用不同的規則，以支援對事件模式的精細控制。

# 使用 Kinesis Data Streams 和 Firehose 搭配 將 DynamoDB 記錄交付至 Amazon S3 AWS CDK
<a name="deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk"></a>

*Shashank Shrivastava 和 Daniel Matuki da Cunha，Amazon Web Services*

## 摘要
<a name="deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk-summary"></a>

此模式提供範例程式碼和應用程式，以使用 Amazon Kinesis Data Streams 和 Amazon Data Firehose，將記錄從 Amazon DynamoDB 交付至 Amazon Simple Storage Service (Amazon S3)。模式的方法使用 [AWS Cloud Development Kit (AWS CDK) L3 建構](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)，並包含如何在資料交付至 Amazon Web Services (AWS) 雲端上的目標 S3 儲存貯體 AWS Lambda 之前使用 執行資料轉換的範例。

Kinesis Data Streams 會在 DynamoDB 資料表中記錄項目層級修改，並將其複寫至所需的 Kinesis 資料串流。您的應用程式可以存取 Kinesis 資料串流，並以近乎即時的速度檢視項目層級的變更。Kinesis Data Streams 也提供其他 Amazon Kinesis 服務的存取權，例如 Firehose 和 Amazon Managed Service for Apache Flink。這表示您可以建置應用程式，以提供即時儀表板、產生提醒、實作動態定價和廣告，以及執行複雜的資料分析。

您可以將此模式用於資料整合使用案例。例如，運輸車輛或工業設備可以將大量資料傳送至 DynamoDB 資料表。然後，這些資料可以轉換並存放在 Amazon S3 中託管的資料湖中。然後，您可以使用 Amazon Athena、Amazon Redshift Spectrum、Amazon Rekognition 和 等無伺服器服務來查詢和處理資料，並預測任何潛在的瑕疵 AWS Glue。

## 先決條件和限制
<a name="deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk-prereqs"></a>

*先決條件*
+ 作用中 AWS 帳戶。
+ AWS Command Line Interface (AWS CLI)，已安裝並設定。如需詳細資訊，請參閱 AWS CLI 文件中的 [入門 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)。
+ Node.js (18.x\$1) 和 npm，已安裝並設定。如需詳細資訊，請參閱 `npm` 文件中的[下載並安裝 Node.js 和 npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)。
+ aws-cdk (2.x\$1)，已安裝並設定。如需詳細資訊，請參閱 AWS CDK 文件中的 [入門 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)。
+ GitHub [aws-dynamodb-kinesisfirehose-s3-ingestion](https://github.com/aws-samples/aws-dynamodb-kinesisfirehose-s3-ingestion/) 儲存庫，在您的本機電腦上複製和設定。
+ DynamoDB 資料表的現有範例資料。資料必須使用下列格式： `{"SourceDataId": {"S": "123"},"MessageData":{"S": "Hello World"}}`

## Architecture
<a name="deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk-architecture"></a>

下圖顯示使用 Kinesis Data Streams 和 Firehose 將記錄從 DynamoDB 交付至 Amazon S3 的範例工作流程。

![\[使用 Kinesis Data Streams 和 Firehose 將記錄從 DynamoDB 交付至 Amazon S3 的範例工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e2a9c412-312e-4900-9774-19a281c578e4/images/6e6df998-e6c2-4eaf-b263-ace752194689.png)


該圖顯示以下工作流程：

1. 使用 Amazon API Gateway 做為 DynamoDB 的代理來擷取資料。您也可以使用任何其他來源將資料擷取至 DynamoDB。 

1. 項目層級變更會在 Kinesis Data Streams 中以近乎即時的方式產生，以交付至 Amazon S3。

1. Kinesis Data Streams 會將記錄傳送至 Firehose 以進行轉換和交付。 

1. Lambda 函數會將記錄從 DynamoDB 記錄格式轉換為 JSON 格式，其中僅包含記錄項目屬性名稱和值。

## 工具
<a name="deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk-tools"></a>

*AWS 服務*
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端基礎設施。
+ [AWS CDK Toolkit](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) 是命令列雲端開發套件，可協助您與 AWS CDK 應用程式互動。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您 AWS 服務 透過命令列 shell 中的命令與 互動。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 生命週期中管理資源 AWS 區域。

*程式碼儲存庫*

此模式的程式碼可在 GitHub [aws-dynamodb-kinesisfirehose-s3-ingestion](https://github.com/aws-samples/aws-dynamodb-kinesisfirehose-s3-ingestion/) 儲存庫中使用。

## 史詩
<a name="deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk-epics"></a>

### 設定範例程式碼
<a name="set-up-and-configure-the-sample-code"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝相依性。 | 在本機電腦上，執行下列命令，從 `pattern/aws-dynamodb-kinesisstreams-s3`和 `sample-application` 目錄中`package.json`的檔案安裝相依性：<pre>cd <project_root>/pattern/aws-dynamodb-kinesisstreams-s3 </pre><pre>npm install && npm run build</pre><pre>cd <project_root>/sample-application/</pre><pre>npm install && npm run build</pre>  | 應用程式開發人員，一般 AWS | 
| 產生 CloudFormation 範本。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk.html) | 應用程式開發人員、一般 AWS、AWS DevOps | 

### 部署 資源
<a name="deploy-the-resources"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢查並部署 資源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk.html) | 應用程式開發人員、一般 AWS、AWS DevOps | 

### 將資料擷取至 DynamoDB 資料表以測試解決方案
<a name="ingest-data-into-the-dynamodb-table-to-test-the-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將範例資料擷取至 DynamoDB 資料表。 | 在 中執行下列命令，將請求傳送至 DynamoDB 資料表 AWS CLI：`aws dynamodb put-item --table-name <your_table_name> --item '{"<table_partition_key>": {"S": "<partition_key_ID>"},"MessageData":{"S": "<data>"}}'`範例：`aws dynamodb put-item --table-name SourceData_table --item '{"SourceDataId": {"S": "123"},"MessageData":{"S": "Hello World"}}'`根據預設，如果操作成功， `put-item`不會傳回任何值做為輸出。如果操作失敗，則會傳回錯誤。資料存放在 DynamoDB 中，然後傳送至 Kinesis Data Streams 和 Firehose。 您可以使用不同的方法來將資料新增至 DynamoDB 資料表。如需詳細資訊，請參閱 DynamoDB 文件中的將[資料載入資料表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/SampleData.LoadData.html)。 | 應用程式開發人員 | 
| 確認已在 S3 儲存貯體中建立新的物件。 | 登入 AWS 管理主控台 並監控 S3 儲存貯體，以確認已使用您傳送的資料建立新物件。 如需詳細資訊，請參閱 Amazon S3 文件中的 [GetObject](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html)。 | 應用程式開發人員，一般 AWS | 

### 清除資源
<a name="clean-up-resources"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除資源。 | 執行 `cdk destroy`命令來刪除此模式使用的所有資源。 | 應用程式開發人員，一般 AWS | 

## 相關資源
<a name="deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk-resources"></a>
+ [s3-static-site-stack.ts](https://github.com/awslabs/aws-solutions-constructs/blob/main/source/use_cases/aws-s3-static-website/lib/s3-static-site-stack.ts#L25) (GitHub 儲存庫）
+ [aws-apigateway-dynamodb 模組](https://github.com/awslabs/aws-solutions-constructs/tree/main/source/patterns/%40aws-solutions-constructs/aws-apigateway-dynamodb) (GitHub 儲存庫）
+ [aws-kinesisstreams-kinesisfirehose-s3 模組](https://github.com/awslabs/aws-solutions-constructs/tree/main/source/patterns/%40aws-solutions-constructs/aws-kinesisstreams-kinesisfirehose-s3) (GitHub 儲存庫）
+ [變更 DynamoDB Streams 的資料擷取 ](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)(DynamoDB 文件）
+ [使用 Kinesis Data Streams 擷取對 DynamoDB 的變更](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/kds.html) (DynamoDB 文件）

# 在 Amazon API Gateway 中使用自訂網域實作路徑型 API 版本控制
<a name="implement-path-based-api-versioning-by-using-custom-domains"></a>

*Corey Schnedl、Marcel Barbosa、Mario Lopez Martinez、Anbazhagan Ponnuswamy、Gaurav Samudra 和 Abhilash Vinod、Amazon Web Services*

## 摘要
<a name="implement-path-based-api-versioning-by-using-custom-domains-summary"></a>

此模式示範如何使用[自訂網域](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-custom-domains.html)的 [API 映射](https://docs.aws.amazon.com/apigateway/latest/developerguide/rest-api-mappings.html)功能，為 Amazon API Gateway 實作以路徑為基礎的 API 版本控制解決方案。

Amazon API Gateway 是一項全受管服務，可用於建立、發佈、維護、監控和保護任何規模APIs。透過使用服務的自訂網域功能，您可以建立更簡單的自訂網域名稱，並提供更直覺URLs 給您的 API 使用者。您可以使用 API 映射將 API 階段連線至自訂網域名稱。建立網域名稱並設定 DNS 記錄之後，您可以使用 API 映射，透過自訂網域名稱將流量傳送至您的 API。

在 API 公開可用之後，消費者會使用它。隨著公有 API 的演進，其服務合約也會演進以反映新功能。不過，變更或移除現有功能並不明智。任何中斷變更都可能會影響消費者的應用程式，並在執行時間中斷它們。API 版本控制對於避免破壞回溯相容性和破壞合約非常重要。

您需要明確的 API 版本控制策略，以協助消費者採用這些策略。使用路徑型 URLs版本控制 APIs 是最直接且常用的方法。在此類型的版本控制中，版本會明確定義為 API URIs的一部分。下列範例 URLs顯示消費者如何使用 URI 為其請求指定 API 版本：

`https://api.example.com/api/v1/orders `

`https://api.example.com/api/v2/orders `

`https://api.example.com/api/vX/orders`

此模式使用 AWS Cloud Development Kit (AWS CDK) 為您的 API 建置、部署和測試可擴展路徑型版本控制解決方案的範例實作。 AWS CDK 是一種開放原始碼軟體開發架構，可使用熟悉的程式設計語言來建模和佈建雲端應用程式資源。

## 先決條件和限制
<a name="implement-path-based-api-versioning-by-using-custom-domains-prereqs"></a>

**先決條件 **
+ 作用中 AWS 帳戶。
+ 需要擁有網域才能使用此模式的範例儲存庫，以及使用 Amazon API Gateway 自訂網域功能。您可以使用 Amazon Route 53 為您的組織建立和管理網域。如需有關如何使用 Route 53 註冊或轉移網域的資訊，請參閱 Route 53 文件中的[註冊新網域](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/domain-register-update.html)。
+ 在設定 API 的自訂網域名稱之前，您必須備妥 [SSL/TLS 憑證](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-specify-certificate-for-custom-domain-name.html) AWS Certificate Manager。
+ 您必須建立或更新 DNS 提供者的資源記錄，以映射至您的 API 端點。如果沒有這類映射，則綁定自訂網域名稱的 API 請求無法到達 API Gateway。

**限制 **
+  AWS 區域 在所有 中，自訂網域名稱必須是唯一的 AWS 帳戶。
+ 若要設定具有多個層級的 API 映射，您必須使用區域性自訂網域名稱和 TLS 1.2 安全政策。
+ 在 API 映射中，自訂網域名稱和映射APIs 必須位於相同的 中 AWS 帳戶。
+ API 映射只能包含字母、數字和下列字元： `$-_.+!*'()/`
+ API 映射中路徑的最大長度為 300 個字元。
+ 您可以為每個域名設定具有 200 個具多個層級的 API 映射。
+ 您只能將 HTTP APIs 映射至具有 TLS 1.2 安全政策的區域性自訂網域名稱。
+ 您無法將 WebSocket APIs對應至與 HTTP API 或 REST API 相同的自訂網域名稱。
+ 有些 AWS 服務 無法全部使用 AWS 區域。如需區域可用性，請參閱[AWS 依區域的服務](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然後選擇服務的連結。

**產品版本**
+ 此範例實作在 [AWS CDK TypeScript 2.149.0 ](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-typescript.html)版中使用 。

## Architecture
<a name="implement-path-based-api-versioning-by-using-custom-domains-architecture"></a>

下圖顯示架構工作流程。

![\[使用 API 映射和自訂網域來實作路徑型 API 版本控制解決方案的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e1b32d2b-410f-4ace-967e-f0b8aaf0304c/images/fa9f04f1-efa6-4fb1-a541-ae3da4076b00.png)


此圖展示了以下要點：

1. API 使用者向 Amazon API Gateway 傳送具有自訂網域名稱的請求。

1. API Gateway 會根據請求 URL 中指定的路徑，將使用者的請求動態路由到 API Gateway 的適當執行個體和階段。下表顯示如何將不同 URL 型路徑路由至不同 API Gateway 執行個體之特定階段的範例。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/implement-path-based-api-versioning-by-using-custom-domains.html)

1. 目的地 API Gateway 執行個體會處理請求，並將結果傳回給使用者。

**自動化和擴展**

我們建議您針對 API 的每個版本使用不同的 AWS CloudFormation 堆疊。透過此方法，您可以在可由自訂網域 APIs 的後端 API 之間進行完全隔離。這種方法的優點是，您可以獨立部署或刪除不同版本的 API，而不會帶來修改其他 API 的風險。這種方法透過隔離 CloudFormation 堆疊來提高彈性。此外，它還為您的 API 提供不同的後端選項 AWS Lambda AWS Fargate，例如 HTTP 端點和 的動作 AWS 服務。

您可以使用 Git 分支策略，例如 [Gitflow](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/gitflow-branching-strategy.html)，搭配隔離的 CloudFormation 堆疊來管理部署到不同 API 版本的原始碼。透過使用此選項，您可以維護不同版本的 API，而不需要複製新版本的原始程式碼。使用 Gitflow，您可以在執行版本時，將標籤新增至 git 儲存庫中的遞交。因此，您擁有與特定版本相關的原始程式碼的完整快照。由於需要執行更新，您可以查看特定版本的程式碼、進行更新，然後將更新的原始程式碼部署到與對應主要版本一致的 CloudFormation 堆疊。這種方法可降低破壞另一個 API 版本的風險，因為每個 API 版本都有隔離的原始程式碼，並部署到單獨的 CloudFormation 堆疊。

## 工具
<a name="implement-path-based-api-versioning-by-using-custom-domains-tools"></a>

**AWS 服務**
+ [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 可協助您建立、發佈、維護、監控和保護任何規模的 REST、HTTP 和 WebSocket APIs。
+ [AWS Certificate Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) 可協助您建立、存放和續約公有和私有 SSL/TLS X.509 憑證和金鑰，以保護 AWS 網站和應用程式。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 是一種開放原始碼軟體開發架構，可讓您在程式碼中定義雲端基礎設施並透過其佈建 CloudFormation。此模式的範例實作使用 [AWS CDK TypeScript 中的](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-typescript.html) 。在 TypeScript AWS CDK 中使用 會使用熟悉的工具，包括 Microsoft TypeScript 編譯器 (`tsc`)、[Node.js](https://nodejs.org/) 和節點套件管理員 (`npm`)。如果您願意，雖然此模式中的範例使用 ，但您可以使用 [Yarn](https://yarnpkg.com/)`npm`。構成[AWS 建構程式庫](https://docs.aws.amazon.com/cdk/v2/guide/libraries.html#libraries-construct)的模組會透過儲存`npm `庫 [npmjs.org](https://docs.npmjs.com/) 進行分發。
+ [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 生命週期中管理資源 AWS 區域。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一種可用性高、可擴展性強的 DNS Web 服務。
+ [AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html) 是一種 Web 應用程式防火牆，可協助您監控轉送至受保護 Web 應用程式資源的 HTTP 和 HTTPS 請求。

**其他工具**
+ [Bruno](https://www.usebruno.com/) 是開放原始碼且易於 Git 的 API 測試用戶端。
+ [cdk-nag](https://github.com/cdklabs/cdk-nag) 是一種開放原始碼公用程式，可透過使用規則套件來檢查 AWS CDK 應用程式是否有最佳實務。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [path-based-versioning-with-api-gateway](https://github.com/aws-samples/path-based-versioning-with-api-gateway)儲存庫中使用。

## 最佳實務
<a name="implement-path-based-api-versioning-by-using-custom-domains-best-practices"></a>
+ 使用強大的持續整合和持續交付 (CI/CD) 管道，自動化使用 建置之 CloudFormation 堆疊的測試和部署 AWS CDK。如需有關此建議的詳細資訊，請參閱 [AWS Well-Architected DevOps 指南](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)。
+ AWS WAF 是受管防火牆，可輕鬆與 Amazon API Gateway 等服務整合。雖然 AWS WAF 不是此版本控制模式運作的必要元件，但我們建議將 做為安全最佳實務， AWS WAF 納入 API Gateway。
+ 鼓勵 API 取用者定期升級至最新版本的 API，以便有效棄用和移除舊版的 API。
+ 在生產設定中使用此方法之前，請為您的 API 實作防火牆和授權策略。
+  AWS 帳戶 使用最低權限存取模型實作對 AWS 資源管理的存取。 [https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)
+ 若要針對使用 建置的應用程式強制執行最佳實務和安全性建議 AWS CDK，建議您使用 [cdk-nag 公用程式](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/check-aws-cdk-applications-or-cloudformation-templates-for-best-practices-by-using-cdk-nag-rule-packs.html)。

## 史詩
<a name="implement-path-based-api-versioning-by-using-custom-domains-epics"></a>

### 準備您的本機環境
<a name="prepare-your-local-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要複製範例應用程式儲存庫，請執行下列命令：<pre>git clone https://github.com/aws-samples/path-based-versioning-with-api-gateway</pre> | 應用程式開發人員 | 
| 導覽至複製的儲存庫。 | 若要導覽至複製的儲存庫資料夾位置，請執行下列命令：<pre>cd api-gateway-custom-domain-versioning</pre> | 應用程式開發人員 | 
| 安裝所需的依存項目。 | 若要安裝必要的相依性，請執行下列命令：<pre>npm install </pre> | 應用程式開發人員 | 

### 部署 CloudFormation 路由堆疊
<a name="deploy-the-cfnshort-routing-stack"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動路由堆疊的部署。 | 若要啟動 CloudFormation 路由堆疊 的部署`CustomDomainRouterStack`，請執行下列命令，`example.com`將 取代為您擁有的網域名稱：<pre>npx cdk deploy CustomDomainRouterStack --parameters PrerequisiteDomainName=example.com</pre>在下列網域 DNS 驗證任務成功執行之前，堆疊部署不會成功。 | 應用程式開發人員 | 

### 驗證網域所有權
<a name="verify-domain-ownership"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證網域的擁有權。 | 在您證明相關聯網域的擁有權之前，憑證將保持**待定驗證**狀態。若要證明擁有權，請將 CNAME 記錄新增至與網域相關聯的託管區域。如需詳細資訊，請參閱 AWS Certificate Manager 文件中的 [DNS 驗證](https://docs.aws.amazon.com/acm/latest/userguide/dns-validation.html)。新增適當的記錄可讓`CustomDomainRouterStack`部署成功。 | 應用程式開發人員、AWS 系統管理員、網路管理員 | 
| 建立別名記錄以指向您的 API Gateway 自訂網域。 | 成功發出並驗證憑證後，[請建立指向 Amazon API Gateway 自訂網域 URL 的 DNS 記錄](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-regional-api-custom-domain-create.html#apigateway-regional-api-custom-domain-dns-record)。 Amazon API Gateway 自訂網域 URL 由自訂網域的佈建唯一產生，並指定為 CloudFormation 輸出參數。以下是[記錄的範例](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-values-basic.html)：**路由政策**：簡易路由**記錄名稱**： `demo.api-gateway-custom-domain-versioning.example.com`**Alias (別名)**：是**記錄類型**：指向 AWS 資源的 "A" 類型的 DNS 記錄**Value (值)**：`d-xxxxxxxxxx.execute-api.xx-xxxx-x.amazonaws.com`**TTL （秒）**：300 | 應用程式開發人員、AWS 系統管理員、網路管理員 | 

### 部署 CloudFormation 堆疊並叫用 API
<a name="deploy-cfnshort-stacks-and-invoke-the-api"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署`ApiStackV1`堆疊。 | 若要部署`ApiStackV1`堆疊，請使用下列命令：<pre>npm run deploy-v1</pre>下列 CDK 程式碼新增 API 映射：<pre>var apiMapping = new CfnApiMapping(this, "ApiMapping", {<br />      apiId: this.lambdaRestApi.restApiId,<br />      domainName: props.customDomainName.domainName,<br />      stage: "api",<br />      apiMappingKey: "api/v1",<br />    });</pre> | 應用程式開發人員 | 
| 部署`ApiStackV2`堆疊。 | 若要部署`ApiStackV2`堆疊，請使用下列命令：<pre>npm run deploy-v2</pre> | 應用程式開發人員 | 
| 叫用 API。 | 若要使用 Bruno 叫用 API 並測試 API 端點，請參閱[其他資訊](#implement-path-based-api-versioning-by-using-custom-domains-additional)中的指示。 | 應用程式開發人員 | 

### 清除資源
<a name="clean-up-resources"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除資源。 | 若要銷毀與此範例應用程式相關聯的資源，請使用下列命令：<pre>npx cdk destroy --all</pre>請務必清除為網域擁有權驗證程序手動新增的任何 Route 53 DNS 記錄。 | 應用程式開發人員 | 

## 疑難排解
<a name="implement-path-based-api-versioning-by-using-custom-domains-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 部署`CustomDomainRouterStack`因為無法驗證憑證而逾時。 | 請確定您已新增適當的 DNS 驗證 CNAME 記錄，如先前任務所述。在新增 DNS **驗證**記錄之後，您的新憑證可能會繼續顯示等待驗證狀態長達 30 分鐘。如需詳細資訊，請參閱 AWS Certificate Manager 文件中的 [DNS 驗證](https://docs.aws.amazon.com/acm/latest/userguide/dns-validation.html)。 | 

## 相關資源
<a name="implement-path-based-api-versioning-by-using-custom-domains-resources"></a>
+ [使用 Amazon CloudFront 實作標頭型 API Gateway 版本控制](https://aws.amazon.com/blogs/compute/implementing-header-based-api-gateway-versioning-with-amazon-cloudfront/) – 此 AWS 運算部落格文章提供標頭型版本控制策略，以替代此模式中概述的路徑型版本控制策略。
+ [AWS CDK 研討會](https://cdkworkshop.com/20-typescript.html) – 此簡介研討會著重於 AWS 使用 在 上建置和部署應用程式 AWS Cloud Development Kit (AWS CDK)。此研討會支援 Go、Python 和 TypeScript。

## 其他資訊
<a name="implement-path-based-api-versioning-by-using-custom-domains-additional"></a>

**使用 Bruno 測試您的 API**

我們建議您使用開放原始碼 API 測試工具 [Bruno](https://www.usebruno.com/)，來驗證範例應用程式的路徑型路由是否正常運作。此模式提供範例集合，以協助測試您的範例 API。

若要叫用和測試您的 API，請使用下列步驟：

1. [安裝 Bruno。](https://www.usebruno.com/downloads)

1. 開啟 Bruno。

1. 在此模式的[程式碼儲存庫](https://github.com/aws-samples/path-based-versioning-with-api-gateway)中，選取 **Bruno/Sample-API-Gateway-Custom-Domain-Versioning**，然後開啟集合。

1. 若要查看使用者介面 (UI) 右上角**的環境**下拉式清單，請選取集合中的任何請求。

1. 在**環境**下拉式清單中，選取**設定**。

1. 將 `REPLACE_ME_WITH_YOUR_DOMAIN`值取代為您的自訂網域。

1. 選擇**儲存**，然後關閉**組態**區段。

1. 針對**沙盒環境**，** **確認已選取**作用中**選項。

1. 使用所選請求的 **->** 按鈕調用您的 API。

1. 請注意，與 V1 中如何處理驗證 （傳遞非數值）。 V2

若要查看範例 API 呼叫的螢幕擷取畫面，以及 V1 和 V2 驗證的比較，請參閱此模式[程式碼儲存庫](https://github.com/aws-samples/path-based-versioning-with-api-gateway)中的測試`README.md`檔案中**的範例 API**。

# 將 psycopg2 程式庫匯入 AWS Lambda ，以與您的 PostgreSQL 資料庫互動
<a name="import-psycopg2-library-lambda"></a>

*Louis Hourcade，Amazon Web Services*

## 總結
<a name="import-psycopg2-library-lambda-summary"></a>

[Psycopg](https://www.psycopg.org/docs/) 是適用於 Python 的 PostgresSQL 資料庫轉接器。開發人員使用 `psycopg2`程式庫撰寫與 PostgreSQL 資料庫互動的 Python 應用程式。

在 Amazon Web Services (AWS) 上，開發人員也會使用 [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)來執行應用程式或後端服務的程式碼。Lambda 是一種無伺服器、事件驅動的運算服務，無需佈建或管理伺服器即可執行程式碼。

根據預設，當您建立使用 [Lambda 支援的 Python 執行期](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html)的新函數時，Lambda 執行期環境會從 提供的 [Lambda 基礎映像](https://github.com/aws/aws-lambda-base-images)建立 AWS。基本映像`psycopg2`中不包含 `pandas`或 等程式庫。若要使用程式庫，您需要將其封裝在自訂套件中，並將其連接到 Lambda。

有多種方式可以綁定和連接程式庫，包括下列項目：
+ 從 [.zip 檔案封存](https://docs.aws.amazon.com/lambda/latest/dg/configuration-function-zip.html)部署 Lambda 函數。
+ 從自訂容器映像部署 Lambda 函數。
+ 建立 [Lambda 層](https://docs.aws.amazon.com/lambda/latest/dg/chapter-layers.html#lambda-layer-versions)，並將其連接至您的 Lambda 函數。

此模式示範前兩個選項。

使用 .zip 部署套件，將程式`pandas`庫新增至 Lambda 函數相對簡單。在 Linux 機器上建立資料夾、將 Lambda 指令碼與程式`pandas`庫和程式庫的相依性新增至資料夾、壓縮資料夾，並將其做為 Lambda 函數的來源。

雖然使用 .zip 部署套件是常見的做法，但該方法不適用於程式`psycopg2`庫。如果您使用 .zip 部署套件將程式`psycopg2`庫新增至 Lambda 函數，此模式會先顯示您遇到的錯誤。此模式接著會示範如何從 Dockerfile 部署 Lambda，並編輯 Lambda 映像，讓`psycopg2`程式庫運作。

如需模式部署的三個資源的相關資訊，請參閱[其他資訊](#import-psycopg2-library-lambda-additional)一節。

## 先決條件和限制
<a name="import-psycopg2-library-lambda-prereqs"></a>

**先決條件 **
+  AWS 帳戶 具有足夠許可的作用中 ，可部署此模式使用 AWS 的資源
+ AWS Cloud Development Kit (AWS CDK) 透過執行 全域安裝 `npm install -g aws-cdk`
+ Git 用戶端
+ Python
+ Docker

**限制 **
+ 有些 AWS 服務 完全無法使用 AWS 區域。如需區域可用性，請參閱[AWS 服務 依區域](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)頁面，然後選擇服務的連結。

**產品版本**
+ [Lambda 支援的](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html) Python 執行時間版本
+ Psycopg2 2.9.3 版
+ Pandas 1.5.2 版

## Architecture
<a name="import-psycopg2-library-lambda-architecture"></a>

**解決方案概觀 **

為了說明在 Lambda 中使用程式`psycopg2`庫時可能面臨的挑戰， 模式會部署兩個 Lambda 函數：
+ 一個 Lambda 函數，其中包含從 .zip 檔案建立的 Python 執行期。`psycopg2` 和 `pandas`程式庫是使用 [pip](https://pypi.org/project/pip/) 安裝在此 .zip 部署套件中。
+ 一個 Lambda 函數，其中包含從 Dockerfile 建立的 Python 執行期。Dockerfile 會將 `psycopg2`和 `pandas`程式庫安裝到 Lambda 容器映像中。

第一個 Lambda 函數會在 .zip 檔案中安裝程式`pandas`庫及其相依性，Lambda 可以使用該程式庫。

第二個 Lambda 函數示範，透過為 Lambda 函數建置容器映像，您可以在 Lambda 中執行 `pandas`和 `psycopg2`程式庫。

## 工具
<a name="import-psycopg2-library-lambda-tools"></a>

**AWS 服務**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端基礎設施。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。

**其他工具**
+ [Docker](https://www.docker.com/) 是一組平台即服務 (PaaS) 產品，可在作業系統層級使用虛擬化在容器中交付軟體。
+ [pandas](https://pandas.pydata.org/) 是以 Python 為基礎的開放原始碼工具，用於資料分析和操作。
+ [Psycopg](https://www.psycopg.org/docs/) 是適用於 Python 語言的 PostgreSQL 資料庫轉接器，專為多執行緒應用程式而設計。此模式使用 Psycopg 2。
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。

**程式碼儲存庫**

此模式的程式碼可在 GitHub 的 [import-psycopg2-in-lambda-to-interact-with-postgres-database](https://github.com/aws-samples/import-psycopg2-in-lambda-to-interact-with-postgres-database) 儲存庫中使用。

## 最佳實務
<a name="import-psycopg2-library-lambda-best-practices"></a>

此模式提供您使用 從 Dockerfile AWS CDK 建立 Lambda 函數的工作範例。如果您在應用程式中重複使用此程式碼，請確定部署的資源符合所有安全需求。使用 [Checkov](https://www.checkov.io/) 等工具，在部署基礎設施之前掃描雲端基礎設施組態以尋找組態錯誤。

## 史詩
<a name="import-psycopg2-library-lambda-epics"></a>

### 複製儲存庫並設定部署
<a name="clone-the-repository-and-configure-the-deployment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要在本機電腦上複製 GitHub 儲存庫，請執行下列命令：<pre>git clone https://github.com/aws-samples/import-psycopg2-in-lambda-to-interact-with-postgres-database.git<br />cd AWS-lambda-psycopg2</pre> | 一般 AWS | 
| 設定您的部署。 | 使用下列資訊編輯 `app.py` 檔案 AWS 帳戶：<pre>aws_acccount = "AWS_ACCOUNT_ID"<br />region = "AWS_REGION"<br /># Select the CPU architecture you are using to build the image (ARM or X86)<br />architecture = "ARM"</pre> | 一般 AWS | 

### 引導您的 AWS 帳戶並部署應用程式
<a name="bootstrap-your-aws-account-and-deploy-the-application"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 引導您的 AWS 帳戶。 | 如果您尚未[啟動 AWS 環境](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)，請使用您 AWS 帳戶的 AWS 登入資料執行下列命令：<pre>cdk bootstrap aws://<tooling-account-id>/<aws-region></pre> | 一般 AWS | 
| 部署程式碼。 | 若要部署 AWS CDK 應用程式，請執行下列命令：<pre>cdk deploy AWSLambdaPyscopg2</pre> | 一般 AWS | 

### 從 AWS 管理主控台測試 Lambda 函數
<a name="test-the-lambda-functions-from-the-aws-management-console"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 測試從 .zip 檔案建立的 Lambda 函數。 | 若要測試從 .zip 檔案建立的 Lambda 函數，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/import-psycopg2-library-lambda.html)由於 Lambda 在預設映像中找不到所需的 PostgreSQL 程式庫，因此無法使用程式`psycopg2`庫。 | 一般 AWS | 
| 測試從 Dockerfile 建立的 Lambda 函數。 | 若要在 Lambda 函數中使用程式`psycopg2`庫，您必須編輯 Lambda Amazon Machine Image (AMI)。若要測試從 Dockerfile 建立的 Lambda 函數，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/import-psycopg2-library-lambda.html)下列程式碼顯示 AWS CDK 範本建立的 Dockerfile：<pre># Start from lambda Python3.13 image<br />FROM public.ecr.aws/lambda/python:3.13<br /><br /># Copy the lambda code, together with its requirements<br />COPY lambda/requirements.txt ${LAMBDA_TASK_ROOT}<br />COPY lambda/lambda_code.py ${LAMBDA_TASK_ROOT}<br /><br /># Install postgresql-devel in your image<br />RUN yum install -y gcc postgresql-devel<br /><br /># install the requirements for the Lambda code<br />RUN pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}"<br /><br /># Command can be overwritten by providing a different command in the template directly.<br />CMD ["lambda_code.handler"]</pre>Dockerfile 會為 Python 執行時間取得 AWS 提供的 Lambda 映像，並安裝 [postgresql-devel](https://yum-info.contradodigital.com/view-package/updates/postgresql-devel/)，其中包含編譯直接與 PostgreSQL 管理伺服器互動之應用程式所需的程式庫。Dockerfile 也會安裝 `pandas`和 `psycopg2`程式庫，這些程式庫會顯示在 `requirements.txt` 檔案中。 | 一般 AWS | 

## 相關資源
<a name="import-psycopg2-library-lambda-resources"></a>
+ [AWS CDK 文件](https://docs.aws.amazon.com/cdk/v2/guide/home.html)
+ [AWS Lambda 文件](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)

## 其他資訊
<a name="import-psycopg2-library-lambda-additional"></a>

在此模式中， AWS CDK 範本會提供具有三個資源的 AWS 堆疊：
+ Lambda 函數的 [AWS Identity and Access Management (IAM) 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)。
+ 具有 Python 執行時間的 Lambda 函數。函數是從部署套件`Constructs/lambda/lambda_deploy.zip`部署。
+ 具有 Python 執行時間的 Lambda 函數。函數是從 `Constructs` 資料夾下的 Dockerfile 部署

兩個 Lambda 函數的指令碼會檢查 `pandas`和 `psycopg2`程式庫是否已成功匯入：

```
import pandas
print("pandas successfully imported")

import psycopg2
print("psycopg2 successfully imported")

def handler(event, context):
    """Function that checks whether psycopg2  and pandas are successfully imported or not"""
    return {"Status": "psycopg2 and pandas successfully imported"}
```

`lambda_deploy.zip` 部署套件是以 `Constructs/lambda/build.sh` bash 指令碼建置。此指令碼會建立資料夾、複製 Lambda 指令碼、安裝 `pandas`和 `psycopg2`程式庫，以及產生 .zip 檔案。若要自行產生 .zip 檔案，請執行此 bash 指令碼並重新部署 AWS CDK 堆疊。

Dockerfile 一開始是使用 Python 執行時間為 Lambda AWS 提供的基礎映像。Dockerfile 會在預設映像上方安裝 `pandas`和 `psycopg2`程式庫。

# 將 Amazon API Gateway 與 Amazon SQS 整合，以處理非同步 REST APIs
<a name="integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis"></a>

*Natalia Colantonio Favero 和 Gustavo Martim，Amazon Web Services*

## 總結
<a name="integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis-summary"></a>

部署 REST APIs 時，有時您需要公開用戶端應用程式可以發佈的訊息佇列。例如，您可能會遇到第三方 APIs 延遲和回應延遲的問題，或者您可能想要避免資料庫查詢的回應時間，或避免在有大量並行 APIs時擴展伺服器。在這些情況下，發佈到佇列的用戶端應用程式只需要知道 API 收到資料，而不是收到資料之後會發生什麼情況。

此模式使用 [Amazon API Gateway](https://aws.amazon.com/api-gateway/) 將訊息傳送至 Amazon Simple Queue Service (Amazon SQS) 來建立 REST API 端點。 [Amazon SQS](https://aws.amazon.com/sqs/) 它會在兩個服務之間建立easy-to-implement的整合，以避免直接存取 SQS 佇列。

## 先決條件和限制
<a name="integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis-prereqs"></a>
+ [作用中 AWS 的帳戶](https://portal.aws.amazon.com/billing/signup/iam)

## Architecture
<a name="integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis-architecture"></a>

![\[整合 API Gateway 與 Amazon SQS 的架構\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/70984dee-e49f-4446-9d52-49ce826c3909/images/737ba0b2-da8f-4478-8c54-0a4835fd69f9.png)


圖表說明這些步驟：

1. 使用 Postman、其他 API 或其他技術等工具請求 POST REST API 端點。

1. API Gateway 會在佇列上張貼在請求內文上接收的訊息。

1. Amazon SQS 會收到訊息，並以成功或失敗代碼傳送答案給 API Gateway。

## 工具
<a name="integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis-tools"></a>
+ [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 可協助您建立、發佈、維護、監控和保護任何規模的 REST、HTTP 和 WebSocket APIs。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) 提供安全、耐用且可用的託管佇列，可協助您整合和分離分散式軟體系統和元件。  

## 史詩
<a name="integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis-epics"></a>

### 建立 SQS 佇列
<a name="create-an-sqs-queue"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立佇列。 | 若要建立接收來自 REST API 訊息的 SQS 佇列：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | 應用程式開發人員 | 

### 提供 Amazon SQS 的存取權
<a name="provide-access-to-sqs"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 IAM 角色。 | 此 IAM 角色可讓 API Gateway 資源完整存取 Amazon SQS。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | 應用程式開發人員、AWS 管理員 | 

### 建立 REST API
<a name="create-a-rest-api"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 REST API。 | 這是傳送 HTTP 請求的 REST API。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | 應用程式開發人員 | 
| 將 API Gateway 連接至 Amazon SQS。 | 此步驟可讓訊息從 HTTP 請求的內文內部流向 Amazon SQS。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | 應用程式開發人員 | 

### 測試 REST API
<a name="test-the-rest-api"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 測試 REST API。 | 執行測試以檢查缺少的組態：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | 應用程式開發人員 | 
| 變更 API 整合以將請求正確轉送至 Amazon SQS。 | 完成組態以修正整合錯誤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | 應用程式開發人員 | 
| 在 Amazon SQS 中測試和驗證訊息。 | 執行測試以確認測試已成功完成：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | 應用程式開發人員 | 
| 使用特殊字元測試 API Gateway。 | 執行測試，其中包含訊息中無法接受的特殊字元 （例如 &)：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html)這是因為訊息內文中預設不支援特殊字元。在下一個步驟中，您將設定 API Gateway 以支援特殊字元。如需內容類型轉換的詳細資訊，請參閱 [API Gateway 文件](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-workflow.html)。 | 應用程式開發人員 | 
| 變更 API 組態以支援特殊字元。 | 調整組態以接受訊息中的特殊字元：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html)新訊息應包含特殊字元。 | 應用程式開發人員 | 

### 部署 REST API
<a name="deploy-the-rest-api"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 API。 |  若要部署 REST API：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | 應用程式開發人員 | 
| 使用外部工具進行測試。 | 使用外部工具執行測試，以確認已成功接收訊息：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | 應用程式開發人員 | 

### 清除
<a name="clean-up"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除 API。 | 在 [API Gateway 主控台](https://console.aws.amazon.com/apigateway/)上，選擇您建立的 API，然後選擇**刪除**。 | 應用程式開發人員 | 
| 刪除 IAM 角色。 | 在 [IAM 主控台](https://console.aws.amazon.com/iam/)**的角色**窗格中，選取 **AWSGatewayRoleForSQS**，然後選擇**刪除**。 | 應用程式開發人員 | 
| 刪除 SQS 佇列。 | 在 [Amazon SQS 主控台](https://console.aws.amazon.com/sqs/)的**佇列**窗格中，選擇您建立的 SQS 佇列，然後選擇**刪除**。 | 應用程式開發人員 | 

## 相關資源
<a name="integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis-resources"></a>
+ [SQS-SendMessage](https://docs.aws.amazon.com/apigateway/latest/developerguide/http-api-develop-integrations-aws-services-reference.html#SQS-SendMessage) (API Gateway 文件）
+ [API Gateway 中的內容類型轉換](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-payload-encodings-workflow.html) (API Gateway 文件）
+ [\$1util 變數](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#util-template-reference) (API Gateway 文件）
+ [如何整合 API Gateway REST API 與 Amazon SQS 並解決常見錯誤？](https://repost.aws/knowledge-center/api-gateway-rest-api-sqs-errors)(AWS re：Post 文章）

# 使用 Amazon API Gateway 和 AWS Lambda 非同步處理事件
<a name="process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda"></a>

*Andrea Meroni、Mariem Kthiri、Nadim Majed 和 Michael Wallner，Amazon Web Services*

## 總結
<a name="process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda-summary"></a>

[Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 是一項全受管服務，開發人員可用來建立、發佈、維護、監控和保護任何規模APIs。它會處理涉及接受和處理多達數十萬個並行 API 呼叫的任務。

API Gateway 的重要服務配額是整合逾時。逾時是後端服務必須在 REST API 傳回錯誤之前傳回回應的最長時間。對於同步工作負載，通常可接受 29 秒的硬性限制。不過，該限制對想要將 API Gateway 與非同步工作負載搭配使用的開發人員來說是一項挑戰。

此模式顯示使用 API Gateway 和 以非同步方式處理事件的範例架構 AWS Lambda。架構支援執行長達 15 分鐘的處理任務，並使用基本 REST API 做為界面。

[Projen](https://pypi.org/project/projen/) 用於設定本機開發環境 AWS 帳戶，以及搭配 [AWS Cloud Development Kit (AWS CDK) Toolkit](https://docs.aws.amazon.com/cdk/v2/guide/cli.html)、[Docker](https://docs.docker.com/get-docker/) 和 [Node.js](https://nodejs.org/en/download/) 將範例架構部署至目標。Projen 會自動使用[預先遞交](https://pre-commit.com/)和用於程式碼品質保證、安全掃描和單元測試的工具來設定 [Python](https://www.python.org/downloads/) 虛擬環境。如需詳細資訊，請參閱[工具](#process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda-tools)一節。

## 先決條件和限制
<a name="process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda-prereqs"></a>

**先決條件 **
+ 作用中 AWS 帳戶
+ 您的工作站上安裝了下列工具：
  + [AWS Cloud Development Kit (AWS CDK) 工具組](https://docs.aws.amazon.com/cdk/v2/guide/cli.html) 2.85.0 版
  + [Docker](https://docs.docker.com/get-docker/) 20.10.21 版
  + [Node.js](https://nodejs.org/en/download/) 18.13.0 版
  + [Projen](https://pypi.org/project/projen/) 0.71.111 版
  + [Python](https://www.python.org/downloads/) 3.9.16 版

**限制 **
+ 任務的最大執行時間受限於 Lambda 函數的最大執行時間 (15 分鐘）。
+ 並行任務請求的數量上限受限於 Lambda 函數的預留並行。

## Architecture
<a name="process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda-architecture"></a>

下圖顯示任務 API 與事件處理和錯誤處理 Lambda 函數的互動，以及存放在 Amazon EventBridge 事件封存中的事件。

![\[AWS 雲端 architecture showing user interaction with jobs API, Lambda functions, and EventBridge.\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e027130c-44c1-41ab-bbe9-f196a49bd9ac/images/3c437b65-48e3-477d-aeea-6ff938cc3285.png)


典型的工作流程包含下列步驟：

1. 您可以驗證 AWS Identity and Access Management (IAM) 並取得安全登入資料。

1. 您可以將 HTTP `POST`請求傳送至`/jobs`任務 API 端點，在請求內文中指定任務參數。

1. 任務 API 是一種 API Gateway REST API，會傳回包含任務識別符的 HTTP 回應給您。

1. 任務 API 會以非同步方式叫用事件處理 Lambda 函數。

1. 事件處理函數會處理事件，然後將任務結果放入任務 Amazon DynamoDB 資料表

1. 您可以將 HTTP `GET`請求傳送至`/jobs/{jobId}`任務 API 端點，並將步驟 3 的任務識別符做為 `{jobId}`。

1. 任務 API 會查詢 `jobs` DynamoDB 資料表來擷取任務結果。

1. 任務 API 會傳回包含任務結果的 HTTP 回應。

1. 如果事件處理失敗，事件處理函數會將事件傳送至錯誤處理函數。

1. 錯誤處理函數會將任務參數放在 `jobs` DynamoDB 資料表中。

1. 您可以透過傳送 HTTP `GET`請求至任務 API 端點來擷取`/jobs/{jobId}`任務參數。

1. 如果錯誤處理失敗，錯誤處理函數會將事件傳送至 EventBridge 事件封存。

   您可以使用 EventBridge 重播封存的事件。

## 工具
<a name="process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda-tools"></a>

**AWS 服務**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端 基礎設施。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您透過命令列 shell 中的命令與 AWS 服務互動。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一項全受管 NoSQL 資料庫服務，可提供快速、可預期且可擴展的效能。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一種無伺服器事件匯流排服務，可協助您將應用程式與來自各種來源的即時資料連線。例如，Lambda 函數、使用 API 目的地的 HTTP 調用端點，或其他事件匯流排 AWS 帳戶。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。

**其他工具**
+ [autopep8](https://github.com/hhatto/autopep8) 會根據 Python Enhancement Proposal (PEP) 8 樣式指南自動格式化 Python 程式碼。
+ [Bandit](https://bandit.readthedocs.io/en/latest/) 會掃描 Python 程式碼以尋找常見的安全問題。
+ [Commitizen](https://commitizen-tools.github.io/commitizen/) 是 Git 遞交檢查程式和`CHANGELOG`產生器。
+ [cfn-lint](https://github.com/aws-cloudformation/cfn-lint) 是 AWS CloudFormation linter
+ [Checkov](https://github.com/bridgecrewio/checkov) 是一種靜態程式碼分析工具，可將基礎設施檢查為程式碼 (IaC) 是否有安全性和合規設定錯誤。
+ [jq](https://stedolan.github.io/jq/download/) 是用於剖析 JSON 的命令列工具。
+ [Postman](https://www.postman.com/) 是 API 平台。
+ [預先遞交](https://pre-commit.com/)是 Git hooks 管理員。
+ [Projen](https://github.com/projen/projen) 是專案產生器。
+ [pytest](https://docs.pytest.org/en/7.2.x/index.html) 是一種 Python 架構，用於撰寫可讀取的小型測試。

**程式碼儲存庫**

您可以在 GitHub [非同步事件處理與 API Gateway 和 Lambda](https://github.com/aws-samples/asynchronous-event-processing-api-gateway-lambda-cdk) 儲存庫中找到此架構程式碼範例。

## 最佳實務
<a name="process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda-best-practices"></a>
+ 此範例架構不包含已部署基礎設施的監控。如果您的使用案例需要監控，請評估新增 [CDK 監控建構](https://constructs.dev/packages/cdk-monitoring-constructs)或其他監控解決方案。
+ 此範例架構使用 [IAM 許可](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html)來控制對任務 API 的存取。有權擔任 的任何人`JobsAPIInvokeRole`都可以叫用任務 API。因此，存取控制機制為二進位。如果您的使用案例需要更複雜的授權模型，請使用不同的[存取控制機制](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html)進行評估。
+ 當使用者傳送 HTTP `POST`請求到`/jobs`任務 API 端點時，輸入資料會在兩個不同的層級進行驗證：
  + Amazon API Gateway 負責第一個[請求驗證](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html)。
  + 事件處理函數會執行第二個請求。

    當使用者對`/jobs/{jobId}`任務 API 端點提出 HTTP `GET`請求時，不會執行驗證。如果您的使用案例需要額外的輸入驗證並提高安全性，[請使用 AWS WAF 評估 來保護您的 API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-aws-waf.html)。

## 史詩
<a name="process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda-epics"></a>

### 設定環境
<a name="set-up-the-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要在本機複製儲存庫，請執行下列命令：<pre>git clone https://github.com/aws-samples/asynchronous-event-processing-api-gateway-lambda-cdk.git</pre> | DevOps 工程師 | 
| 設定專案。 | 使用 [Projen](https://github.com/projen/projen) 將目錄變更為儲存庫根目錄，並設定 Python 虛擬環境和所有工具：<pre>cd asynchronous-event-processing-api-gateway-api-gateway-lambda-cdk<br />npx projen</pre> | DevOps 工程師 | 
| 安裝預先遞交掛鉤。 | 若要安裝預先遞交掛鉤，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda.html) | DevOps 工程師 | 

### 部署範例架構
<a name="deploy-the-example-architecture"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 引導 AWS CDK。 | 若要在 AWS CDK 中引導 AWS 帳戶，請執行下列命令：<pre>AWS_PROFILE=$YOUR_AWS_PROFILE npx projen bootstrap</pre> | AWS DevOps | 
| 部署範例架構。 | 若要在 中部署範例架構 AWS 帳戶，請執行下列命令：<pre>AWS_PROFILE=$YOUR_AWS_PROFILE npx projen deploy</pre> | AWS DevOps | 

### 測試架構
<a name="test-the-architecture"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝測試先決條件。 | 在工作站上安裝 [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)、[Postman](https://www.postman.com/downloads/) 和 [jq](https://jqlang.github.io/jq/)。建議使用 [Postman](https://www.postman.com/downloads/) 測試此範例架構，但不強制。如果您選擇替代 API 測試工具，請確定它支援 [AWS Signature 第 4 版身分驗證](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html)，並參考可透過[匯出 REST API 檢查的公開 API ](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-export-api.html)端點。 | DevOps 工程師 | 
| 擔任 `JobsAPIInvokeRole`。 | [假設](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html)`JobsAPIInvokeRole`從部署命令列印為輸出的 ：<pre>CREDENTIALS=$(AWS_PROFILE=$<YOUR_AWS_PROFILE> aws sts assume-role \<br />--no-cli-pager \<br />--role-arn $<JOBS_API_INVOKE_ROLE_ARN> \<br />--role-session-name JobsAPIInvoke)<br />export AWS_ACCESS_KEY_ID=$(cat $CREDENTIALS | jq ‘.Credentials’’.AccessKeyId’)<br />export AWS_SECRET_ACCESS_KEY=$(cat $CREDENTIALS | jq ‘.Credentials’’.SecretAccessKey’)<br />export AWS_SESSION_TOKEN==$(cat $CREDENTIALS | jq ‘.Credentials’’.SessionToken’)</pre> | AWS DevOps | 
| 設定 Postman。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda.html) | AWS DevOps | 
| 測試範例架構。 | 若要測試範例架構，請將[請求傳送至](https://learning.postman.com/docs/sending-requests/requests/#next-steps)任務 API。如需詳細資訊，請參閱 [Postman 文件](https://learning.postman.com/docs/getting-started/first-steps/sending-the-first-request/#send-an-api-request)。 | DevOps 工程師 | 

## 疑難排解
<a name="process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 範例架構的銷毀和後續重新部署失敗，因為 [Amazon CloudWatch Logs 日誌群組](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)`/aws/apigateway/JobsAPIAccessLogs`已存在。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda.html) | 

## 相關資源
<a name="process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda-resources"></a>
+ [API Gateway 映射範本和存取記錄變數參考](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html)
+ [設定後端 Lambda 函數的非同步調用](https://docs.aws.amazon.com/apigateway/latest/developerguide/set-up-lambda-integration-async.html)

# 使用 Amazon API Gateway 和 Amazon DynamoDB Streams 非同步處理事件
<a name="processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams"></a>

*Andrea Meroni、Mariem Kthiri、Nadim Majed、Alessandro Trisolini 和 Michael Wallner，Amazon Web Services*

## 總結
<a name="processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams-summary"></a>

[Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 是一項全受管服務，開發人員可用來建立、發佈、維護、監控和保護任何規模APIs。它會處理涉及接受和處理多達數十萬個並行 API 呼叫的任務。

API Gateway 的一項重要服務配額是整合逾時。逾時是後端服務必須在 REST API 傳回錯誤之前傳回回應的最長時間。對於同步工作負載，通常可接受 29 秒的硬性限制。不過，該限制對想要將 API Gateway 與非同步工作負載搭配使用的開發人員來說是一項挑戰。

此模式顯示使用 API Gateway、Amazon DynamoDB Streams 和 非同步處理事件的範例架構 AWS Lambda。架構支援使用相同的輸入參數執行平行處理任務，並使用基本 REST API 做為界面。在此範例中，使用 Lambda 做為後端會將任務持續時間限制為 15 分鐘。您可以使用替代服務來處理傳入事件 （例如，)，以避免此限制 AWS Fargate。

[Projen](https://pypi.org/project/projen/) 用於設定本機開發環境 AWS 帳戶，以及搭配 [AWS Cloud Development Kit (AWS CDK) Toolkit](https://docs.aws.amazon.com/cdk/v2/guide/cli.html)、[Docker](https://docs.docker.com/get-docker/) 和 [Node.js](https://nodejs.org/en/download/) 將範例架構部署至目標。Projen 會自動使用[預先遞交](https://pre-commit.com/)和用於程式碼品質保證、安全掃描和單元測試的工具來設定 [Python](https://www.python.org/downloads/) 虛擬環境。如需詳細資訊，請參閱[工具](#processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams-tools)一節。

## 先決條件和限制
<a name="processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams-prereqs"></a>

**先決條件 **
+ 作用中 AWS 帳戶
+ 工作站上安裝了下列工具：
  + [AWS Cloud Development Kit (AWS CDK) 工具組](https://docs.aws.amazon.com/cdk/v2/guide/cli.html) 2.85.0 版或更新版本
  + [Docker](https://docs.docker.com/get-docker/) 20.10.21 版或更新版本
  + [Node.js](https://nodejs.org/en/download/) 第 18 版或更新版本
  + [Projen](https://pypi.org/project/projen/) 0.71.111 版或更新版本
  + [Python](https://www.python.org/downloads/) 3.9.16 版或更新版本

**限制 **
+ DynamoDB Streams 建議的讀取器數目上限為兩個，以避免限流。
+ 任務的最大執行時間受限於 Lambda 函數的最大執行時間 (15 分鐘）。
+ 並行任務請求的數量上限受限於 Lambda 函數的預留並行。

## Architecture
<a name="processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams-architecture"></a>

**架構**

下圖顯示任務 API 與 DynamoDB Streams 的互動，以及事件處理和錯誤處理 Lambda 函數的互動，以及存放在 Amazon EventBridge 事件封存中的事件。

![\[架構和程序的圖表，步驟列在圖表後面。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/68a46501-16e5-48e4-99c6-fc67a8b4133a/images/29fe6982-ad81-4099-9c65-08b17c96e78f.png)


典型的工作流程包括以下步驟：

1. 您可以驗證 AWS Identity and Access Management (IAM) 並取得安全登入資料。

1. 您可以將 HTTP `POST`請求傳送至`/jobs`任務 API 端點，在請求內文中指定任務參數。

1. 任務 API 會傳回包含任務識別符的 HTTP 回應給您。

1. 任務 API 會將任務參數放在 Amazon DynamoDB `jobs_table` 資料表中。

1. `jobs_table` DynamoDB 資料表 DynamoDB 串流會叫用事件處理 Lambda 函數。

1. 事件處理 Lambda 函數會處理事件，然後將任務結果放入 `jobs_table` DynamoDB 資料表。為了協助確保結果一致，事件處理函數實作[樂觀鎖定](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html)機制。

1. 您可以將 HTTP `GET`請求傳送至`/jobs/{jobId}`任務 API 端點，並將步驟 3 的任務識別符做為 `{jobId}`。

1. 任務 API 會查詢 `jobs_table` DynamoDB 資料表來擷取任務結果。

1. 任務 API 會傳回包含任務結果的 HTTP 回應。

1. 如果事件處理失敗，事件處理函數的來源映射會將事件傳送至錯誤處理 Amazon Simple Notification Service (Amazon SNS) 主題。

1. 錯誤處理 SNS 主題會以非同步方式將事件推送至錯誤處理函數。

1. 錯誤處理函數會將任務參數放在 `jobs_table` DynamoDB 資料表中。

   您可以透過傳送 HTTP `GET`請求至任務 API 端點來擷取`/jobs/{jobId}`任務參數。

1. 如果錯誤處理失敗，錯誤處理函數會將事件傳送至 Amazon EventBridge 封存。

   您可以使用 EventBridge 重播封存的事件。

## 工具
<a name="processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams-tools"></a>

**AWS 服務**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端基礎設施。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一項全受管 NoSQL 資料庫服務，可提供快速、可預期且可擴展的效能。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一種無伺服器事件匯流排服務，可協助您將應用程式與來自各種來源的即時資料連線。例如，AWS Lambda 函數、使用 API 目的地的 HTTP 調用端點，或其他 AWS 帳戶中的事件匯流排。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需支付使用的運算時間。
+ [Amazon Simple Notification Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可協助您協調和管理發佈者和用戶端之間的訊息交換，包括 Web 伺服器和電子郵件地址。

**其他工具**
+ [autopep8](https://github.com/hhatto/autopep8) 會根據 Python Enhancement Proposal (PEP) 8 樣式指南自動格式化 Python 程式碼。
+ [Bandit](https://bandit.readthedocs.io/en/latest/) 會掃描 Python 程式碼以尋找常見的安全問題。
+ [Commitizen](https://commitizen-tools.github.io/commitizen/) 是 Git 遞交檢查程式和`CHANGELOG`產生器。
+ [cfn-lint](https://github.com/aws-cloudformation/cfn-lint) 是 AWS CloudFormation linter
+ [Checkov](https://github.com/bridgecrewio/checkov) 是一種靜態程式碼分析工具，可將基礎設施檢查為程式碼 (IaC) 是否有安全性和合規設定錯誤。
+ [jq](https://stedolan.github.io/jq/download/) 是用於剖析 JSON 的命令列工具。
+ [Postman](https://www.postman.com/) 是 API 平台。
+ [預先遞交](https://pre-commit.com/)是 Git hooks 管理員。
+ [Projen](https://github.com/projen/projen) 是專案產生器。
+ [pytest](https://docs.pytest.org/en/7.2.x/index.html) 是一種 Python 架構，用於撰寫小型、可讀取的測試。

**程式碼儲存庫**

您可以在 GitHub [非同步處理搭配 API Gateway 和 DynamoDB Streams ](https://github.com/aws-samples/asynchronous-event-processing-api-gateway-dynamodb-streams-cdk)儲存庫中找到此架構程式碼範例。

## 最佳實務
<a name="processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams-best-practices"></a>
+ 此範例架構不包含對已部署基礎設施的監控。如果您的使用案例需要監控，請評估新增 [CDK 監控建構](https://constructs.dev/packages/cdk-monitoring-constructs)或其他監控解決方案。
+ 此範例架構使用 [IAM 許可](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html)來控制對任務 API 的存取。有權擔任 的任何人`JobsAPIInvokeRole`都可以叫用任務 API。因此，存取控制機制是二進位。如果您的使用案例需要更複雜的授權模型，請使用不同的[存取控制機制](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html)進行評估。
+ 當使用者傳送 HTTP `POST`請求到`/jobs`任務 API 端點時，輸入資料會在兩個不同的層級進行驗證：
  + API Gateway 負責第一個[請求驗證](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html)。
  + 事件處理函數會執行第二個請求。

    當使用者對`/jobs/{jobId}`任務 API 端點提出 HTTP `GET`請求時，不會執行驗證。如果您的使用案例需要額外的輸入驗證和更高的安全性，請使用 評估 [AWS WAF 來保護您的 API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-aws-waf.html)。
+ 為了避免限流，[DynamoDB Streams 文件](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html#Streams.Processing)會阻止使用者從相同串流碎片中讀取兩個以上的取用者。若要擴展消費者數量，建議使用 [Amazon Kinesis Data Streams](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/kds.html)。
+ 此範例中已使用[樂觀鎖定](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html)，以確保 `jobs_table` DynamoDB 資料表中項目的一致更新。根據使用案例需求，您可能需要實作更可靠的鎖定機制，例如漸進式鎖定。

## 史詩
<a name="processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams-epics"></a>

### 設定環境
<a name="set-up-the-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要在本機複製儲存庫，請執行下列命令：<pre>git clone https://github.com/aws-samples/asynchronous-event-processing-api-gateway-dynamodb-streams-cdk.git</pre> | DevOps 工程師 | 
| 設定專案。 | 將目錄變更為儲存庫根目錄，並使用 [Projen](https://github.com/projen/projen) 設定 Python 虛擬環境和所有工具：<pre>cd asynchronous-event-processing-api-gateway-api-gateway-dynamodb-streams-cdk<br />npx projen</pre> | DevOps 工程師 | 
| 安裝預先遞交掛鉤。 | 若要安裝預先遞交掛鉤，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams.html) | DevOps 工程師 | 

### 部署範例架構
<a name="deploy-the-example-architecture"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 引導 AWS CDK。 | 若要在 [AWS CDK](https://aws.amazon.com/cdk/)中引導 AWS 帳戶，請執行下列命令：<pre>AWS_PROFILE=$YOUR_AWS_PROFILE npx projen bootstrap</pre> | AWS DevOps | 
| 部署範例架構。 | 若要在 中部署範例架構 AWS 帳戶，請執行下列命令：<pre>AWS_PROFILE=$YOUR_AWS_PROFILE npx projen deploy</pre> | AWS DevOps | 

### 測試架構
<a name="test-the-architecture"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝測試先決條件。 | 在工作站上安裝 [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)、[Postman](https://www.postman.com/downloads/) 和 [jq](https://jqlang.github.io/jq/)。建議使用 [Postman](https://www.postman.com/downloads/) 測試此範例架構，但並非強制性。如果您選擇替代 API 測試工具，請確定它支援 [AWS Signature 第 4 版身分驗證](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html)，並參考可透過[匯出 REST API 檢查的公開 API ](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-export-api.html)端點。 | DevOps 工程師 | 
| 擔任 `JobsAPIInvokeRole`。 | [假設](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html)`JobsAPIInvokeRole`從 `deploy`命令列印為輸出的 ：<pre>CREDENTIALS=$(AWS_PROFILE=$<YOUR_AWS_PROFILE> aws sts assume-role \<br />--no-cli-pager \<br />--role-arn $<JOBS_API_INVOKE_ROLE_ARN> \<br />--role-session-name JobsAPIInvoke)<br />export AWS_ACCESS_KEY_ID=$(cat $CREDENTIALS | jq ‘.Credentials’’.AccessKeyId’)<br />export AWS_SECRET_ACCESS_KEY=$(cat $CREDENTIALS | jq ‘.Credentials’’.SecretAccessKey’)<br />export AWS_SESSION_TOKEN==$(cat $CREDENTIALS | jq ‘.Credentials’’.SessionToken’)</pre> | AWS DevOps | 
| 設定 Postman。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams.html) | AWS DevOps | 
| 測試範例架構。 | 若要測試範例架構，請將請求傳送至任務 API。如需詳細資訊，請參閱 [Postman 文件](https://learning.postman.com/docs/getting-started/first-steps/sending-the-first-request/#send-an-api-request)。 | DevOps 工程師 | 

## 疑難排解
<a name="processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 範例架構的銷毀和後續重新部署失敗，因為 [Amazon CloudWatch Logs 日誌群組](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)`/aws/apigateway/JobsAPIAccessLogs`已存在。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams.html) | 

## 相關資源
<a name="processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams-resources"></a>
+ [API Gateway 映射範本和存取記錄變數參考](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html)
+ [變更 DynamoDB Streams 的資料擷取](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)
+ [具有版本編號的樂觀鎖定](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html)
+ [使用 Kinesis Data Streams 擷取對 DynamoDB 的變更](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/kds.html)

# 使用 Amazon API Gateway、Amazon SQS 和 AWS Fargate 非同步處理事件
<a name="process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate"></a>

*Andrea Meroni、Mariem Kthiri、Nadim Majed、Alessandro Trisolini 和 Michael Wallner，Amazon Web Services*

## 總結
<a name="process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate-summary"></a>

[Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 是一項全受管服務，開發人員可用來建立、發佈、維護、監控和保護任何規模APIs。它會處理涉及接受和處理多達數十萬個並行 API 呼叫的任務。

API Gateway 的一項重要服務配額是整合逾時。逾時是後端服務必須在 REST API 傳回錯誤之前傳回回應的最長時間。對於同步工作負載，通常可接受 29 秒的硬性限制。不過，該限制對想要將 API Gateway 與非同步工作負載搭配使用的開發人員來說是一項挑戰。

此模式顯示使用 API Gateway、Amazon Simple Queue Service (Amazon SQS) 和 非同步處理事件的範例架構 AWS Fargate。架構支援在沒有持續時間限制的情況下執行處理任務，並使用基本 REST API 做為界面。

[Projen](https://pypi.org/project/projen/) 用於設定本機開發環境 AWS 帳戶，並將範例架構與 [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/cli.html)、[Docker](https://docs.docker.com/get-docker/) 和 [Node.js](https://nodejs.org/en/download/) 結合部署至目標。Projen 會自動使用[預先遞交](https://pre-commit.com/)和用於程式碼品質保證、安全掃描和單元測試的工具來設定 [Python](https://www.python.org/downloads/) 虛擬環境。如需詳細資訊，請參閱[工具](#process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate-tools)一節。

## 先決條件和限制
<a name="process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ 工作站上安裝了下列工具：
  + [AWS Cloud Development Kit (AWS CDK) 工具組](https://docs.aws.amazon.com/cdk/v2/guide/cli.html) 2.85.0 版或更新版本
  + [Docker](https://docs.docker.com/get-docker/) 20.10.21 版或更新版本
  + [Node.js](https://nodejs.org/en/download/) 第 18 版或更新版本
  + [Projen](https://pypi.org/project/projen/) 0.71.111 版或更新版本
  + [Python](https://www.python.org/downloads/) 3.9.16 版或更新版本

**限制**
+ 並行任務限制為每分鐘 500 個任務，這是 Fargate 可以佈建的任務數量上限。

## Architecture
<a name="process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate-architecture"></a>

下圖顯示任務 API 與 `jobs` Amazon DynamoDB 資料表、事件處理 Fargate 服務和錯誤處理 AWS Lambda 函數的互動。事件會存放在 Amazon EventBridge 事件存檔中。

![\[結構圖與圖表後面的描述。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/8a03149c-8f34-4593-84d5-accc1800a0a2/images/5e1071aa-4fbc-495c-bc22-8e62a32a136b.png)


典型的工作流程包括以下步驟：

1. 您可以驗證 AWS Identity and Access Management (IAM) 並取得安全登入資料。

1. 您可以將 HTTP `POST`請求傳送至`/jobs`任務 API 端點，在請求內文中指定任務參數。

1. 任務 API 是一種 API Gateway REST API，會傳回包含任務識別符的 HTTP 回應給您。

1. 任務 API 會傳送訊息至 SQS 佇列。

1. Fargate 從 SQS 佇列提取訊息、處理事件，然後將任務結果放入 `jobs` DynamoDB 資料表。

1. 您可以將 HTTP `GET`請求傳送至`/jobs/{jobId}`任務 API 端點，並將步驟 3 的任務識別符做為 `{jobId}`。

1. 任務 API 會查詢 `jobs` DynamoDB 資料表來擷取任務結果。

1. 任務 API 會傳回包含任務結果的 HTTP 回應。

1. 如果事件處理失敗，SQS 佇列會將事件傳送至無效字母佇列 (DLQ)。

1. EventBridge 事件會啟動錯誤處理函數。

1. 錯誤處理函數會將任務參數放在 `jobs` DynamoDB 資料表中。

1. 您可以透過傳送 HTTP `GET`請求至任務 API 端點來擷取`/jobs/{jobId}`任務參數。

1. 如果錯誤處理失敗，錯誤處理函數會將事件傳送至 EventBridge 封存。

   您可以使用 EventBridge 重播封存的事件。

## 工具
<a name="process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate-tools"></a>

**AWS 服務**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端 基礎設施。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一項全受管 NoSQL 資料庫服務，可提供快速、可預期且可擴展的效能。
+ [AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/userguide/what-is-fargate.html) 可協助您執行容器，而無需管理伺服器或 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體。它與 Amazon Elastic Container Service (Amazon ECS) 搭配使用。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一種無伺服器事件匯流排服務，可協助您將應用程式與來自各種來源的即時資料連線。例如，Lambda 函數、使用 API 目的地的 HTTP 調用端點，或其他事件匯流排 AWS 帳戶。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需支付使用的運算時間。
+ [Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) 提供安全、耐用且可用的託管佇列，可協助您整合和分離分散式軟體系統和元件。

**其他工具**
+ [autopep8](https://github.com/hhatto/autopep8) 會根據 Python Enhancement Proposal (PEP) 8 樣式指南自動格式化 Python 程式碼。
+ [Bandit](https://bandit.readthedocs.io/en/latest/) 會掃描 Python 程式碼來尋找常見的安全問題。
+ [Commitizen](https://commitizen-tools.github.io/commitizen/) 是 Git 遞交檢查程式和`CHANGELOG`產生器。
+ [cfn-lint](https://github.com/aws-cloudformation/cfn-lint) 是 AWS CloudFormation linter
+ [Checkov](https://github.com/bridgecrewio/checkov) 是一種靜態程式碼分析工具，可將基礎設施檢查為程式碼 (IaC) 是否有安全性和合規設定錯誤。
+ [jq](https://stedolan.github.io/jq/download/) 是用於剖析 JSON 的命令列工具。
+ [Postman](https://www.postman.com/) 是 API 平台。
+ [預先遞交](https://pre-commit.com/)是 Git hooks 管理員。
+ [Projen](https://github.com/projen/projen) 是專案產生器。
+ [pytest](https://docs.pytest.org/en/7.2.x/index.html) 是一種 Python 架構，用於撰寫小型且可讀取的測試。

**程式碼儲存庫**

您可以在 GitHub [非同步處理與 API Gateway 和 SQS](https://github.com/aws-samples/asynchronous-event-processing-api-gateway-sqs-cdk) 儲存庫中找到此架構程式碼範例。

## 最佳實務
<a name="process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate-best-practices"></a>
+ 此範例架構不包含對已部署基礎設施的監控。如果您的使用案例需要監控，請評估新增 [CDK 監控建構](https://constructs.dev/packages/cdk-monitoring-constructs)或其他監控解決方案。
+ 此範例架構使用 [IAM 許可](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html)來控制對任務 API 的存取。有權擔任 的任何人`JobsAPIInvokeRole`都可以叫用任務 API。因此，存取控制機制是二進位。如果您的使用案例需要更複雜的授權模型，請使用不同的[存取控制機制](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html)進行評估。
+ 當使用者傳送 HTTP `POST`請求到`/jobs`任務 API 端點時，輸入資料會在兩個不同的層級進行驗證：
  + API Gateway 負責第一個[請求驗證](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-method-request-validation.html)。
  + 事件處理函數會執行第二個請求。

    當使用者對`/jobs/{jobId}`任務 API 端點提出 HTTP `GET`請求時，不會執行驗證。如果您的使用案例需要額外的輸入驗證和更高的安全性，請使用 評估 [AWS WAF 來保護您的 API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-aws-waf.html)。

## 史詩
<a name="process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate-epics"></a>

### 設定環境
<a name="set-up-the-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要在本機複製儲存庫，請執行下列命令：<pre>git clone https://github.com/aws-samples/asynchronous-event-processing-api-gateway-sqs-cdk.git</pre> | DevOps 工程師 | 
| 設定專案。 | 將目錄變更為儲存庫根目錄，並使用 [Projen](https://github.com/projen/projen) 設定 Python 虛擬環境和所有工具：<pre>cd asynchronous-event-processing-api-gateway-api-gateway-sqs-cdk<br />npx projen</pre> | DevOps 工程師 | 
| 安裝預先遞交掛鉤。 | 若要安裝預先遞交掛鉤，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate.html) | DevOps 工程師 | 

### 部署範例架構
<a name="deploy-the-example-architecture"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 引導 AWS CDK。 | 若要在 [AWS CDK](https://aws.amazon.com/cdk/)中引導 AWS 帳戶，請執行下列命令：<pre>AWS_PROFILE=$YOUR_AWS_PROFILE npx projen bootstrap</pre> | AWS DevOps | 
| 部署範例架構。 | 若要在 中部署範例架構 AWS 帳戶，請執行下列命令：<pre>AWS_PROFILE=$YOUR_AWS_PROFILE npx projen deploy</pre> | AWS DevOps | 

### 測試架構
<a name="test-the-architecture"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝測試先決條件。 | 在工作站上安裝 [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)、[Postman](https://www.postman.com/downloads/) 和 [jq](https://jqlang.github.io/jq/)。建議使用 [Postman](https://www.postman.com/downloads/) 測試此範例架構，但不強制。如果您選擇替代 API 測試工具，請確定它支援 [AWS Signature 第 4 版身分驗證](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html)，並參考可透過[匯出 REST API 檢查的公開 API ](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-export-api.html)端點。 | DevOps 工程師 | 
| 擔任 `JobsAPIInvokeRole`。 | [假設](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html)`JobsAPIInvokeRole`從 `deploy`命令列印為輸出的 ：<pre>CREDENTIALS=$(AWS_PROFILE=$<YOUR_AWS_PROFILE> aws sts assume-role \<br />--no-cli-pager \<br />--role-arn $<JOBS_API_INVOKE_ROLE_ARN> \<br />--role-session-name JobsAPIInvoke)<br />export AWS_ACCESS_KEY_ID=$(cat $CREDENTIALS | jq ‘.Credentials’’.AccessKeyId’)<br />export AWS_SECRET_ACCESS_KEY=$(cat $CREDENTIALS | jq ‘.Credentials’’.SecretAccessKey’)<br />export AWS_SESSION_TOKEN==$(cat $CREDENTIALS | jq ‘.Credentials’’.SessionToken’)</pre> | AWS DevOps | 
| 設定 Postman。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate.html) | AWS DevOps | 
| 測試範例架構。 | 若要測試範例架構，請將請求傳送至任務 API。如需詳細資訊，請參閱 [Postman 文件](https://learning.postman.com/docs/getting-started/first-steps/sending-the-first-request/#send-an-api-request)。 | DevOps 工程師 | 

## 疑難排解
<a name="process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 範例架構的銷毀和後續重新部署失敗，因為 [Amazon CloudWatch Logs 日誌群組](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)`/aws/apigateway/JobsAPIAccessLogs`已存在。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate.html) | 
| 範例架構的銷毀和後續重新部署失敗，因為 [CloudWatch Logs 日誌群組](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)`/aws/ecs/EventProcessingServiceLogs`已存在。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate.html) | 

## 相關資源
<a name="process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate-resources"></a>
+ [API Gateway 映射範本和存取記錄變數參考](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html)
+ [如何將 API Gateway REST API 與 Amazon SQS 整合並解決常見錯誤？](https://aws.amazon.com/premiumsupport/knowledge-center/api-gateway-rest-api-sqs-errors/)

# 從 AWS Step Functions 同步執行 AWS Systems Manager 自動化任務 AWS Step Functions
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions"></a>

*Elie El khoury，Amazon Web Services*

## 總結
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-summary"></a>

此模式說明如何 AWS Step Functions 與 整合 AWS Systems Manager。它使用 AWS SDK 服務整合，從狀態機器工作流程使用任務字符呼叫 Systems Manager **startAutomationExecution** API，並暫停直到字符傳回成功或失敗呼叫。為了示範整合，此模式會實作圍繞 `AWS-RunShellScript`或 文件的自動化`AWS-RunPowerShellScript`文件 （執行手冊） 包裝函式，並使用 `.waitForTaskToken` 同步呼叫 `AWS-RunShellScript`或 `AWS-RunPowerShellScript`。如需 Step Functions 中 AWS SDK 服務整合的詳細資訊，請參閱 [AWS Step Functions 開發人員指南](https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html)。

Step Functions ****是一種低程式碼的視覺化工作流程服務，可用來建置分散式應用程式、自動化 IT 和業務流程，以及使用 AWS 服務建置資料和機器學習管道。工作流程會管理故障、重試、平行化、服務整合和可觀測性，讓您可以專注於更高價值的商業邏輯。

自動化是 的功能 AWS Systems Manager，可簡化常見的維護、部署和修復任務， AWS 服務 例如 Amazon Elastic Compute Cloud (Amazon EC2)、Amazon Relational Database Service (Amazon RDS)、Amazon Redshift 和 Amazon Simple Storage Service (Amazon S3)。自動化可讓您精細控制自動化的並行。例如，您可以指定要同時鎖定多少資源，以及在自動化停止之前可以發生的錯誤數量。

如需實作詳細資訊，包括 Runbook 步驟、參數和範例，請參閱[其他資訊](#run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-additional)一節。

## 先決條件和限制
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-prereqs"></a>

**先決條件**
+ 作用中 AWS 的帳戶
+ AWS Identity and Access Management 存取 Step Functions 和 Systems Manager 的 (IAM) 許可
+ [執行個體](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-ssm-agent.html)上安裝 Systems Manager Agent (SSM Agent) 的 EC2 執行個體
+ 連接至您計劃執行 Runbook [之執行個體的 Systems Manager IAM 執行個體描述](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)檔
+ 具有下列 IAM 許可的 Step Functions 角色 （遵循最低權限原則）：

```
{
             "Effect": "Allow",
             "Action": "ssm:StartAutomationExecution",
             "Resource": "*"
 }
```

**產品版本**
+ SSM 文件結構描述 0.3 版或更新版本
+ SSM Agent 2.3.672.0 版或更新版本

## Architecture
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-architecture"></a>

**目標技術堆疊**
+ AWS Step Functions
+ AWS Systems Manager  自動化

**目標架構**

![\[從 Step Functions 同步執行 Systems Manager 自動化任務的架構\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/47c19e4f-d68d-4f91-bb68-202098757529/images/2d248aae-d858-4565-8af2-593cde0da780.png)


**自動化和擴展**
+ 此模式提供 AWS CloudFormation 範本，可用來在多個執行個體上部署 Runbook。（請參閱 GitHub [Step Functions 和 Systems Manager 實作](https://github.com/aws-samples/amazon-stepfunctions-ssm-waitfortasktoken)儲存庫。)

## 工具
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-tools"></a>

**AWS 服務**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 區域的生命週期中管理資源。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 AWS Lambda 函數和其他 AWS 服務 來建置業務關鍵型應用程式。
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 可協助您管理在 中執行的應用程式和基礎設施 AWS 雲端。它可簡化應用程式和資源管理、縮短偵測和解決操作問題的時間，並協助您大規模安全地管理 AWS 資源。

**Code**

此模式的程式碼可在 GitHub [Step Functions 和 Systems Manager 實作](https://github.com/aws-samples/amazon-stepfunctions-ssm-waitfortasktoken)儲存庫中使用。 

## 史詩
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-epics"></a>

### 建立 Runbook
<a name="create-runbooks"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 下載 CloudFormation 範本。 | 從 GitHub 儲存庫的 `cloudformation `資料夾下載`ssm-automation-documents.cfn.json`範本。 | AWS DevOps | 
| 建立 Runbook。 | 登入 AWS 管理主控台，開啟 [CloudFormation 主控台](https://console.aws.amazon.com/cloudformation/)，然後部署 範本。如需部署 CloudFormation 範本的詳細資訊，請參閱 CloudFormation 文件中的[在 CloudFormation 主控台上建立堆疊](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。 CloudFormation 範本會部署三個資源：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions.html) | AWS DevOps | 

### 建立範例狀態機器
<a name="create-a-sample-state-machine"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立測試狀態機器。 | 遵循 [AWS Step Functions 開發人員指南](https://docs.aws.amazon.com/step-functions/latest/dg/getting-started-with-sfn.html)中的指示來建立和執行狀態機器。針對 定義，請使用下列程式碼。請務必使用帳戶中啟用 Systems Manager 之有效執行個體的 ID 來更新`InstanceIds`值。<pre>{<br />  "Comment": "A description of my state machine",<br />  "StartAt": "StartAutomationWaitForCallBack",<br />  "States": {<br />    "StartAutomationWaitForCallBack": {<br />      "Type": "Task",<br />      "Resource": "arn:aws:states:::aws-sdk:ssm:startAutomationExecution.waitForTaskToken",<br />      "Parameters": {<br />        "DocumentName": "SfnRunCommandByInstanceIds",<br />        "Parameters": {<br />          "InstanceIds": [<br />            "i-1234567890abcdef0"<br />          ],<br />          "taskToken.$": "States.Array($$.Task.Token)",<br />          "workingDirectory": [<br />            "/home/ssm-user/"<br />          ],<br />          "Commands": [<br />            "echo \"This is a test running automation waitForTaskToken\" >> automation.log",<br />            "sleep 100"<br />          ],<br />          "executionTimeout": [<br />              "10800"<br />          ],<br />          "deliveryTimeout": [<br />              "30"<br />          ],<br />          "shell": [<br />              "Shell"<br />          ]<br />            }<br />      },<br />      "End": true<br />    }<br />  }<br />}</pre>此程式碼會呼叫 Runbook 來執行兩個命令，以示範對 Systems Manager Automation 的`waitForTaskToken`呼叫。`shell` 參數值 (`Shell` 或 `PowerShell`) 會決定自動化文件是執行 `AWS-RunShellScript`還是 `AWS-RunPowerShellScript`。任務會將「這是執行自動化 waitForTaskToken」的測試寫入 `/home/ssm-user/automation.log` 檔案，然後休眠 100 秒，再以任務字符回應，並釋出工作流程中的下一個任務。如果您想要改為呼叫 `SfnRunCommandByTargets`Runbook，請將上一個程式碼的 `Parameters`區段取代為下列項目：<pre>"Parameters": {<br />          "Targets": [<br />            {<br />              "Key": "InstanceIds",<br />              "Values": [<br />                "i-02573cafcfEXAMPLE",<br />                "i-0471e04240EXAMPLE"<br />              ]<br />            }<br />          ],</pre> | AWS DevOps | 
| 更新狀態機器的 IAM 角色。 | 上一個步驟會自動為狀態機器建立專用 IAM 角色。不過，它不會授予呼叫 Runbook 的許可。透過新增下列許可來更新角色：<pre>{<br />      "Effect": "Allow",<br />      "Action": "ssm:StartAutomationExecution",<br />      "Resource": "*"<br /> }</pre> | AWS DevOps | 
| 驗證同步呼叫。 | 執行狀態機器以驗證 Step Functions 與 Systems Manager Automation 之間的同步呼叫。 如需範例輸出，請參閱[其他資訊](#run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-additional)一節。  | AWS DevOps | 

## 相關資源
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-resources"></a>
+ [入門 AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/getting-started-with-sfn.html)(*AWS Step Functions 開發人員指南*)
+ [使用任務字符等待回呼](https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token) *AWS Step Functions （開發人員指南*，服務整合模式）
+ [send\$1task\$1success](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_success.html) 和 [send\$1task\$1failure](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_failure.html) API 呼叫 (Boto3 文件） 
+ [AWS Systems Manager 自動化](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-automation.html) (*AWS Systems Manager 使用者指南*)

## 其他資訊
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions-additional"></a>

**實作詳細資訊**

此模式提供 CloudFormation 範本，可部署兩個 Systems Manager Runbook：
+ `SfnRunCommandByInstanceIds`會使用執行個體 IDs 執行 `AWS-RunShellScript`或 `AWS-RunPowerShellScript`命令。
+ `SfnRunCommandByTargets`使用目標執行 `AWS-RunShellScript`或 `AWS-RunPowerShellScript`命令。

每個 Runbook 都會實作四個步驟，以在 Step Functions 中使用 `.waitForTaskToken`選項時實現同步呼叫。


| 
| 
| 步驟 | Action | Description | 
| --- |--- |--- |
| **1** | `Branch` | 檢查`shell`參數值 (`Shell` 或 `PowerShell`)，以決定是否要`AWS-RunShellScript`針對 Linux 或 `AWS-RunPowerShellScript` Windows 執行 。 | 
| **2** | `RunCommand_Shell` 或 `RunCommand_PowerShell` | 接受數個輸入並執行 `RunShellScript`或 `RunPowerShellScript`命令。如需詳細資訊，請參閱 Systems Manager 主控台上 `RunCommand_Shell`或`RunCommand_PowerShell`自動化文件**的詳細資訊**索引標籤。 | 
| **3** | `SendTaskFailure` | 步驟 2 中止或取消時執行。它呼叫 Step Functions [send\$1task\$1failure](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_failure.html) API，接受三個參數做為輸入：狀態機器傳遞的字符、失敗錯誤，以及失敗原因的描述。 | 
| **4** | `SendTaskSuccess` | 步驟 2 成功時執行。它呼叫 Step Functions [send\$1task\$1success](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/stepfunctions/client/send_task_success.html) API，該 API 接受狀態機器傳遞的字符作為輸入。 | 

**Runbook 參數**

`SfnRunCommandByInstanceIds` Runbook：


| 
| 
| 參數名稱 | Type | 選用或必要 | Description | 
| --- |--- |--- |--- |
| `shell` | String | 必要 | 執行個體 shell，用於決定是否`AWS-RunShellScript`要針對 Linux 或 Windows `AWS-RunPowerShellScript` 執行。 | 
| `deliveryTimeout` | Integer | 選用 | 等待命令交付至執行個體上 SSM 代理程式的時間，以秒為單位。此參數的最小值為 30 (0.5 分鐘），最大值為 2592000 (720 小時）。 | 
| `executionTimeout` | String | 選用 | 命令在被視為失敗之前完成的時間，以秒為單位。預設值為 3600 (1 小時）。最大值為 172800 (48 小時）。 | 
| `workingDirectory` | String | 選用 | 在您的執行個體上的工作目錄路徑。 | 
| `Commands` | StringList | 必要 | 要執行的 shell 指令碼或命令。 | 
| `InstanceIds` | StringList | 必要 | 您要執行命令之執行個體的 IDs。 | 
| `taskToken` | String | 必要 | 用於回呼回應的任務字符。 | 

`SfnRunCommandByTargets`Runbook：


| 
| 
| Name | 類型 | 選用或必要 | Description | 
| --- |--- |--- |--- |
| `shell` | String | 必要 | 執行個體 shell，以決定是否`AWS-RunShellScript`要針對 Linux 或 Windows `AWS-RunPowerShellScript` 執行。 | 
| `deliveryTimeout` | Integer | 選用 | 等待命令交付至執行個體上 SSM 代理程式的時間，以秒為單位。此參數的最小值為 30 (0.5 分鐘），最大值為 2592000 (720 小時）。 | 
| `executionTimeout` | Integer | 選用 | 命令在被視為失敗之前完成的時間，以秒為單位。預設值為 3600 (1 小時）。最大值為 172800 (48 小時）。 | 
| `workingDirectory` | String | 選用 | 在您的執行個體上的工作目錄路徑。 | 
| `Commands` | StringList | 必要 | 要執行的 shell 指令碼或命令。 | 
| `Targets` | MapList | 必要 | 使用您指定的鍵值對來識別執行個體的搜尋條件陣列。例如：`[{"Key":"InstanceIds","Values":["i-02573cafcfEXAMPLE","i-0471e04240EXAMPLE"]}]` | 
| `taskToken` | String | 必要 | 用於回呼回應的任務字符。 | 

**範例輸出**

下表提供 步驟函數的範例輸出。它顯示步驟 5 (`TaskSubmitted`) 和步驟 6 () 之間的總執行時間超過 100 秒`TaskSucceeded`。這會示範步驟函數等待`sleep 100`命令完成，然後再移至工作流程中的下一個任務。


| 
| 
| ID | Type | 步驟 | 資源 | 經過時間 （毫秒） | 時間戳記 | 
| --- |--- |--- |--- |--- |--- |
| **1** | `ExecutionStarted` |  | - | 0 | 2022 年 3 月 11 日下午 02：50：34.303 | 
| **2** | `TaskStateEntered` | `StartAutomationWaitForCallBack` | - | 40 | 2022 年 3 月 11 日下午 02：50：34.343 | 
| **3** | `TaskScheduled` | `StartAutomationWaitForCallBack` | - | 40 | 2022 年 3 月 11 日下午 02：50：34.343 | 
| **4** | `TaskStarted` | `StartAutomationWaitForCallBack` | - | 154 | 2022 年 3 月 11 日下午 02：50：34.457 | 
| **5** | `TaskSubmitted` | `StartAutomationWaitForCallBack` | - | 657 | 2022 年 3 月 11 日下午 02：50：34.960 | 
| **6** | `TaskSucceeded` | `StartAutomationWaitForCallBack` | - | 103835 | 2022 年 3 月 11 日下午 02：52：18.138 | 
| **7** | `TaskStateExited` | `StartAutomationWaitForCallBack` | - | 103860 | 2022 年 3 月 11 日下午 02：52：18.163 | 
| **8** | `ExecutionSucceeded` |  | - | 103897 | 2022 年 3 月 11 日下午 02：52：18：200 | 

# 在 AWS Lambda 函數中使用 Python 執行 S3 物件的平行讀取
<a name="run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function"></a>

*Eduardo Bortoluzzi，Amazon Web Services*

## 總結
<a name="run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-summary"></a>

您可以使用此模式從 Amazon Simple Storage Service (Amazon S3) 儲存貯體即時擷取和摘要文件清單。模式提供範例程式碼，從 Amazon Web Services () 上的 S3 儲存貯體平行讀取物件AWS。模式示範如何使用 Python 使用 AWS Lambda 函數有效率地執行 I/O 繫結任務。

一家金融公司在互動式解決方案中使用此模式，以即時手動核准或拒絕相互關聯的金融交易。金融交易文件存放在與市場相關的 S3 儲存貯體中。運算子從 S3 儲存貯體中選取文件清單，分析解決方案計算的交易總值，並決定核准或拒絕選取的批次。

I/O 繫結任務支援多個執行緒。在此範例程式碼中，[並行.futures.ThreadPoolExecutor](https://docs.python.org/3.13/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor) 最多可與 30 個同時執行緒搭配使用，即使 Lambda 函數最多支援 1，024 個執行緒 （其中一個執行緒是您的主要程序）。此限制是因為太多執行緒會因為內容切換和運算資源的使用率而產生延遲問題。您也需要在 中增加集區連線上限，`botocore`以便所有執行緒可以同時執行 S3 物件下載。

範例程式碼在 S3 儲存貯體中使用一個 8.3 KB 物件搭配 JSON 資料。物件會多次讀取。Lambda 函數讀取物件後，JSON 資料會解碼為 Python 物件。在 2024 年 12 月，執行此範例後的結果為 2.3 秒內處理的 1，000 次讀取，以及 27 秒內處理的 10，000 次讀取，其使用 Lambda 函數設定為 2，304 MB 記憶體。 AWS Lambda 支援從 128 MB 到 10，240 MB (10 GB) 的記憶體組態，但將 Lambdamemory 增加到超過 2，304 MB 並有助於縮短執行此特定 I/O 繫結任務的時間。

[AWS Lambda Power Tuning](https://github.com/alexcasalboni/aws-lambda-power-tuning) 工具用於測試不同的 Lambda 記憶體組態，並驗證任務的最佳performance-to-cost比。如需測試結果，請參閱[其他資訊](#run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-additional)一節。

## 先決條件和限制
<a name="run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ Python 開發的熟練度

**限制**
+ Lambda 函數最多可以有 [1，024 個執行程序或執行緒](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html#function-configuration-deployment-and-execution)。
+ 新 AWS 帳戶 的 Lambda 記憶體限制為 3，008 MB。相應地調整 AWS Lambda Power Tuning 工具。如需詳細資訊，請參閱[疑難排解](#run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-troubleshooting)一節。
+ Amazon S3 [每個分割字首每秒限制 5，500 個 GET/HEAD 請求](https://docs.aws.amazon.com/AmazonS3/latest/userguide/optimizing-performance.html)。

**產品版本**
+ Python 3.9 或更高版本
+ AWS Cloud Development Kit (AWS CDK) v2
+ AWS Command Line Interface (AWS CLI) 第 2 版
+ AWS Lambda Power Tuning 4.3.6 （選用）

## Architecture
<a name="run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-architecture"></a>

**目標技術堆疊**
+ AWS Lambda
+ Amazon S3
+ AWS Step Functions （如果已部署 AWS Lambda 電源調校）

**目標架構**

下圖顯示從 S3 儲存貯體平行讀取物件的 Lambda 函數。此圖表也有 Step Functions 工作流程，可供 AWS Lambda Power Tuning 工具微調 Lambda 函數記憶體。這種微調有助於在成本和效能之間取得良好的平衡。

![\[顯示 Lambda 函數、S3 儲存貯體和 AWS Step Functions 的圖表。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/b46e9b16-9842-4291-adfa-3ef012b89aec/images/828696e2-6df7-4536-9205-951c99449f4e.png)


**自動化和擴展**

Lambda 函數會在需要時快速擴展。為了避免 Amazon S3 在高需求期間發生 503 緩慢下降錯誤，我們建議對擴展設定一些限制。

## 工具
<a name="run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-tools"></a>

**AWS 服務**
+ [AWS Cloud Development Kit (AWS CDK) v2](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端 基礎設施。已建立要部署的範例基礎設施 AWS CDK。
+ [AWS Command Line InterfaceAWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您 AWS 服務 透過命令列 shell 中的命令與 互動。在此模式中，第 2 AWS CLI 版用於上傳範例 JSON 檔案。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需支付使用的運算時間。
+ [Amazon Simple Storage Service Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您存放、保護和擷取任意數量的資料。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 AWS Lambda 函數和其他 AWS 服務來建置業務關鍵應用程式。

**其他工具**
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。Python 3.8 版中推出了[閒置工作者執行緒的重複使用](https://docs.python.org/3.8/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor)，此模式中的 Lambda 函數程式碼是針對 Python 3.9 版和更新版本建立的。

**程式碼儲存庫**

此模式的程式碼可在 [aws-lambda-parallel-download](https://github.com/aws-samples/aws-lambda-parallel-download) GitHub 儲存庫中使用。

## 最佳實務
<a name="run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-best-practices"></a>
+ 此 AWS CDK 建構倚賴 AWS 帳戶您 的使用者許可來部署基礎設施。如果您打算使用 AWS CDK 管道或跨帳戶部署，請參閱[堆疊合成器](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html#bootstrapping-synthesizers)。
+ 此範例應用程式未在 S3 儲存貯體啟用存取日誌。最佳實務是在生產程式碼中啟用存取日誌。

## 史詩
<a name="run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-epics"></a>

### 準備開發環境
<a name="prepare-the-development-environment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢查 Python 安裝的版本。 | 此程式碼已專門在 Python 3.9 和 Python 3.13 上進行測試，且應適用於這些版本之間的所有版本。若要檢查您的 Python 版本，請在終端機`python3 -V`中執行 ，並視需要安裝較新的版本。若要驗證已安裝必要的模組，請執行 `python3 -c "import pip, venv"`。沒有錯誤訊息表示模組已正確安裝，您已準備好執行此範例。 | 雲端架構師 | 
| 安裝 AWS CDK。 | 若要在尚未安裝 AWS CDK 時安裝 ，請遵循 [入門 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)中的指示。若要確認已安裝的 AWS CDK 版本是 2.0 或更新版本，請執行 `cdk –version`。 | 雲端架構師 | 
| 引導您的環境。 | 若要引導您的環境，如果尚未完成，請依照[引導環境的指示搭配 使用 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping-env.html)。 | 雲端架構師 | 

### 複製範例儲存庫
<a name="clone-the-example-repository"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要複製最新版本的儲存庫，請執行下列命令：<pre>git clone --depth 1 --branch v1.2.0 \<br />git@github.com:aws-samples/aws-lambda-parallel-download.git</pre> | 雲端架構師 | 
| 將工作目錄變更為複製的儲存庫。 | 執行以下命令：<pre>cd aws-lambda-parallel-download</pre> | 雲端架構師 | 
| 建立 Python 虛擬環境。 | 若要建立 Python 虛擬環境，請執行下列命令：<pre>python3 -m venv .venv</pre> | 雲端架構師 | 
| 啟用虛擬環境。 | 若要啟用虛擬環境，請執行下列命令：<pre>source .venv/bin/activate</pre> | 雲端架構師 | 
| 安裝相依性。 | 若要安裝 Python 相依性，請執行 `pip`命令：<pre>pip install -r requirements.txt</pre> | 雲端架構師 | 
| 瀏覽程式碼。 | （選用） 從 S3 儲存貯體下載物件的範例程式碼位於 `resources/parallel.py`。基礎設施程式碼位於 `parallel_download` 資料夾中。 | 雲端架構師 | 

### 部署和測試應用程式
<a name="deploy-and-test-the-app"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署應用程式。 | 執行 `cdk deploy`。寫下 AWS CDK 輸出：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function.html) | 雲端架構師 | 
| 上傳範例 JSON 檔案。 | 儲存庫包含約 9 KB 的範例 JSON 檔案。若要將檔案上傳至已建立堆疊的 S3 儲存貯體，請執行下列命令：<pre>aws s3 cp sample.json s3://<ParallelDownloadStack.SampleS3BucketName></pre>`<ParallelDownloadStack.SampleS3BucketName>` 將 取代為 AWS CDK 輸出中的對應值。 | 雲端架構師 | 
| 執行應用程式。 | 若要執行應用程式，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function.html) | 雲端架構師 | 
| 新增下載次數。 | （選用） 若要執行 1，500 取得物件呼叫，請在 `Test` 參數的事件 JSON 中使用**下列 JSON**：<pre>{"repeat": 1500, "objectKey": "sample.json"}</pre> | 雲端架構師 | 

### 選用：執行 AWS Lambda 電源調校
<a name="optional-run-lamlong-power-tuning"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行 AWS Lambda Power Tuning 工具。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function.html)在執行結束時，結果會在**執行輸入和輸出**索引標籤上。 | 雲端架構師 | 
| 在圖形中檢視 AWS Lambda 電源調校結果。 | 在**執行輸入和輸出**索引標籤上，複製 `visualization` 屬性連結，並將其貼入新的瀏覽器索引標籤。 | 雲端架構師 | 

### 清除
<a name="clean-up"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 從 S3 儲存貯體移除物件。 | 在您銷毀已部署的資源之前，請先從 S3 儲存貯體移除所有物件：<pre>aws s3 rm s3://<ParallelDownloadStack.SampleS3BucketName> \<br />--recursive</pre>請記得將 取代`<ParallelDownloadStack.SampleS3BucketName>`為 AWS CDK 輸出中的 值。 | 雲端架構師 | 
| 銷毀資源。 | 若要銷毀為此試驗建立的所有資源，請執行下列命令：<pre>cdk destroy</pre> | 雲端架構師 | 

## 疑難排解
<a name="run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| `'MemorySize' value failed to satisfy constraint: Member must have value less than or equal to 3008` | 對於新帳戶，您可能無法在 Lambda 函數中設定超過 3，008 MB。若要使用 AWS Lambda Power Tuning 進行測試，請在啟動 Step Functions 執行時，在輸入 JSON 新增下列屬性：<pre>"powerValues": [<br />    512,<br />    1024,<br />    1536,<br />    2048,<br />    2560,<br />    3008<br />  ]</pre> | 

## 相關資源
<a name="run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-resources"></a>
+ [Python – concurrent.futures.ThreadPoolExecutor](https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor)
+ [Lambda 配額 – 函數組態、部署和執行](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html#function-configuration-deployment-and-execution)
+ [在 Python AWS CDK 中使用](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-python.html)
+ [使用 AWS Lambda Power Tuning 分析函數](https://docs.aws.amazon.com/lambda/latest/operatorguide/profile-functions.html)

## 其他資訊
<a name="run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-additional"></a>

**Code**

下列程式碼片段會執行平行 I/O 處理：

```
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
  for result in executor.map(a_function, (the_arguments)):
    ...
```

當執行緒可用時， 會`ThreadPoolExecutor`重複使用執行緒。

**測試和結果**

這些測試是在 2024 年 12 月進行。

第一個測試處理了 2，500 個物件讀取，結果如下。

![\[呼叫時間下降，且呼叫成本隨著記憶體增加而上升。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/b46e9b16-9842-4291-adfa-3ef012b89aec/images/f6743412-1e52-4c4c-a51c-ac0f75b3b998.png)


從 3，009 MB 開始，處理時間層級在任何記憶體增加時幾乎保持不變，但成本會隨著記憶體大小增加而增加。

另一項測試使用 256 MB 的倍數和處理 10，000 個物件讀取的值，調查了介於 1，536 MB 和 3，072 MB 之間的記憶體範圍，結果如下。

![\[減少調用時間下降和調用成本上升之間的差異。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/b46e9b16-9842-4291-adfa-3ef012b89aec/images/c75d4443-74d8-4b93-9b4d-b2640869381e.png)


最佳performance-to-cost比率是使用 2，304 MB 記憶體 Lambda 組態。

為了進行比較，2，500 個物件讀取的循序程序需要 47 秒。使用 2，304 MB Lambda 組態的平行程序需要 7 秒，減少 85%。

![\[圖表顯示從循序處理切換到平行處理的時間減少。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/b46e9b16-9842-4291-adfa-3ef012b89aec/images/f3dcc44d-ac20-4b75-897d-1d71f0d59781.png)


# 將遙測資料從 AWS Lambda 傳送至 OpenSearch，以進行即時分析和視覺化
<a name="send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization"></a>

*Tabby Ward、Guy Bachar 和 David Kilzer，Amazon Web Services*

## 總結
<a name="send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-summary"></a>

現代應用程式越來越分散和事件驅動，這加強了即時監控和可觀測性的需求。 AWS Lambda 是一種無伺服器運算服務，在建置可擴展性和事件驅動型架構方面扮演關鍵角色。不過，如果您只依賴 Amazon CloudWatch Logs，監控和疑難排解 Lambda 函數可能具有挑戰性，這可能會導致延遲和有限的保留期。

為了解決此挑戰， AWS 推出了 Lambda 遙測 API，可讓 Lambda 函數將遙測資料直接傳送到第三方監控和可觀測性工具。此 API 支援日誌、指標和追蹤的即時串流，並提供 Lambda 函數效能和運作狀態的完整及時檢視。

此模式說明如何整合 Lambda 遙測 API 與 [OpenSearch](https://opensearch.org/docs/latest/)，這是一種開放原始碼的分散式搜尋和分析引擎。OpenSearch 提供強大且可擴展的平台，用於擷取、儲存和分析大量資料，這使得它成為 Lambda 遙測資料的理想選擇。具體而言，此模式示範如何使用 提供的 Lambda 擴充功能，將日誌從以 Python 撰寫的 Lambda 函數直接傳送至 OpenSearch 叢集 AWS。此解決方案靈活且可自訂，因此您可以建立自己的 Lambda 延伸模組，或變更範例原始程式碼，視需要變更輸出格式。

模式說明如何設定和設定 Lambda 遙測 API 與 OpenSearch 的整合，並包含安全性、成本最佳化和可擴展性的最佳實務。目標是協助您深入了解 Lambda 函數，並增強無伺服器應用程式的整體可觀測性。


| 
| 
| 注意：此模式著重於整合 Lambda 遙測 API 與受管 OpenSearch。不過，討論的原則和技術也適用於自我管理的 OpenSearch 和 Elasticsearch。 | 
| --- |

## 先決條件和限制
<a name="send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-prereqs"></a>

開始整合程序之前，請確定您已備妥下列先決條件：

**AWS 帳戶**：具備適當許可 AWS 帳戶 的作用中 ，可建立和管理下列 AWS 資源：
+ AWS Lambda
+ AWS Identity and Access Management (IAM)
+ Amazon OpenSearch Service （如果您使用受管 OpenSearch 叢集）

**OpenSearch 叢集**：
+ 您可以使用現有的自我管理 OpenSearch 叢集或受管服務，例如 OpenSearch Service。
+ 如果您使用的是 OpenSearch Service，請依照 OpenSearch Service 文件中的 [Amazon OpenSearch Service 入門](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/gsg.html)中的指示來設定 OpenSearch 叢集。
+ 請確定 OpenSearch 叢集可從 Lambda 函數存取，並使用存取政策、加密和身分驗證等必要的安全設定進行設定。
+ 使用必要的索引映射和設定來設定 OpenSearch 叢集，以擷取 Lambda 遙測資料。如需詳細資訊，請參閱 [ OpenSearch Service 文件中的將串流資料載入 Amazon](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/integrations.html) OpenSearch Service。

**網路連線**：
+ 確保您的 Lambda 函數具有存取 OpenSearch 叢集所需的網路連線能力。如需如何設定虛擬私有雲端 (VPC) 設定的指引，請參閱 [ OpenSearch Service 文件中的在 VPC 內啟動 Amazon OpenSearch Service 網域](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/vpc.html)。 OpenSearch 

**IAM 角色和政策**：
+ 建立具有 Lambda 函數必要許可的 IAM 角色，以存取 OpenSearch 叢集並存取存放在其中的登入資料 AWS Secrets Manager。
+ 將適當的 IAM 政策連接到角色，例如`AWSLambdaBasicExecutionRole`政策以及與 OpenSearch 互動所需的任何其他許可。
+ 確認授予 Lambda 函數的 IAM 許可允許它將資料寫入 OpenSearch 叢集。如需有關管理 IAM 許可的資訊，請參閱 [Lambda 文件中的使用 執行角色定義 Lambda 函數許可](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html)。

**程式設計語言知識**：
+ 您需要 Python （或您選擇的程式設計語言） 的基本知識，才能了解和修改 Lambda 函數和 Lambda 延伸模組的範例程式碼。

**開發環境**：
+ 使用建置和部署 Lambda 函數和延伸所需的工具和相依性來設定本機開發環境。

**AWS CLI 或 AWS 管理主控台**：
+ 安裝並設定 [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)，或使用 AWS 管理主控台 具有適當登入資料的 與所需的 互動 AWS 服務。

**監控和記錄**：
+ 熟悉 的監控和記錄最佳實務 AWS，包括 Amazon CloudWatch 等服務，以及 AWS CloudTrail 用於監控和稽核目的。
+ 檢查您的 Lambda 函數的 CloudWatch Logs，以識別與 Lambda 遙測 API 整合相關的任何錯誤或例外狀況。如需疑難排解指引，請參閱 [Lambda 遙測 API 文件](https://docs.aws.amazon.com/lambda/latest/dg/telemetry-api.html)。

## Architecture
<a name="send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-architecture"></a>

此模式使用 OpenSearch Service 來存放由 Lambda 函數產生的日誌和遙測資料。此方法可讓您將日誌直接快速串流至 OpenSearch 叢集，進而減少使用 CloudWatch Logs 做為中介裝置的延遲和相關成本。


| 
| 
| 您的 Lambda 延伸程式碼可以直接使用 OpenSearch API 或使用 OpenSearch [用戶端程式庫，將遙測推送至 OpenSearch ](https://opensearch.org/docs/latest/clients/index/)Service。Lambda 延伸模組可以使用 OpenSearch API 支援的大量操作，將遙測事件批次在一起，並在單一請求中將其傳送至 OpenSearch Service。 | 
| --- |

下列工作流程圖說明當您使用 OpenSearch 叢集做為端點時，Lambda 函數的日誌工作流程。

![\[將遙測資料傳送至 OpenSearch 叢集的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/57fe8796-9f36-46cf-8304-f506242b9f04/images/283ccdcd-a0e1-40a2-a95a-3bd046bfa8ca.png)


架構包含下列元件：
+ Lambda 函數：在執行期間產生日誌和遙測資料的無伺服器函數。
+ Lambda 延伸模組：Python 型延伸模組，使用 Lambda 遙測 API 直接與 OpenSearch 叢集整合。此延伸項目會在相同的執行環境中與 Lambda 函數一起執行。
+ Lambda 遙測 API：此 API 可讓 Lambda 延伸模組直接將遙測資料傳送至第三方監控和可觀測性工具，包括日誌、指標和追蹤。
+ Amazon OpenSearch Service 叢集：託管於 的受管 OpenSearch 叢集 AWS。此叢集負責透過 Lambda 延伸來擷取、儲存和索引從 Lambda 函數串流的日誌資料。

工作流程包含下列步驟：

1. Lambda 函數稱為 ，並在其執行期間產生日誌和遙測資料。

1. Lambda 延伸項目會與 函數一起執行，以使用 Lambda 遙測 API 擷取日誌和遙測資料。

1. Lambda 擴充功能會與 OpenSearch Service 叢集建立安全連線，並即時串流日誌資料。

1. OpenSearch Service 叢集會擷取、編製索引和存放日誌資料，以便透過使用 Kibana 或其他相容應用程式等工具進行搜尋、分析和視覺化。

透過規避 CloudWatch Logs 並將日誌資料直接傳送到 OpenSearch 叢集，此解決方案提供數種優點：
+ 即時日誌串流和分析，可更快速進行故障診斷並改善可觀測性。
+ 減少與 CloudWatch Logs 相關的延遲和潛在的保留限制。
+ 自訂 Lambda 延伸模組或為特定輸出格式或其他處理建立您自己的延伸模組的彈性。
+ 與 OpenSearch Service 的搜尋、分析和視覺化功能整合，以進行日誌分析和監控。

[Epics](#send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-epics) 區段提供step-by-step說明。 OpenSearch 如需監控和疑難排解解決方案的安全考量、成本最佳化策略和秘訣，請參閱[最佳實務](#send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-best-practices)一節。

## 工具
<a name="send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-tools"></a>

**AWS 服務**
+ [AWS Lambda](https://aws.amazon.com/lambda/) 是一種運算服務，讓您無需設定或管理伺服器即可運行程式碼。Lambda 只有在需要時才會執行程式碼，可自動從每天數項請求擴展成每秒數千項請求。
+ [Amazon OpenSearch Service](https://aws.amazon.com/opensearch-service/) 是 提供的全受管服務 AWS ，可讓您輕鬆地在雲端中部署、操作和擴展 OpenSearch 叢集。
+ [Lambda 延伸](https://docs.aws.amazon.com/lambda/latest/dg/lambda-extensions.html)模組透過執行自訂程式碼來擴展 Lambda 函數的功能。您可以使用 Lambda 擴充功能，將 Lambda 與各種監控、可觀測性、安全性和控管工具整合。
+ [AWS Lambda 遙測 API](https://docs.aws.amazon.com/lambda/latest/dg/telemetry-api.html) 可讓您使用擴充功能直接從 Lambda 擷取增強型監控和可觀測性資料，並將其傳送至您選擇的目的地。
+ [CloudFormation](https://aws.amazon.com/cloudformation/) 可協助您建立和設定 AWS 資源的模型，以減少管理這些資源的時間，並有更多時間專注於您的應用程式。

**程式碼儲存庫**
+ [AWS Lambda 延伸](https://github.com/aws-samples/aws-lambda-extensions)項目包含來自 和 AWS 合作夥伴的示範 AWS 和範例專案，協助您開始建置自己的延伸項目。
+ [適用於 OpenSearch 的 Lambda 遙測整合範例](https://github.com/aws-samples/aws-lambda-extensions/tree/main/python-example-telemetry-opensearch-extension)提供 Lambda 延伸範例，示範如何將日誌從 Lambda 函數傳送至 OpenSearch 叢集。

**其他工具**
+ [OpenSearch](https://opensearch.org/faq/) 是一種開放原始碼分散式搜尋和分析引擎，提供強大的平台，用於擷取、儲存和分析大量資料。
+ Kibana 是一種開放原始碼資料視覺化和探勘工具，可與 OpenSearch 搭配使用。請注意，視覺化和分析的實作超出此模式的範圍。如需詳細資訊，請參閱 [Kibana 文件](https://www.elastic.co/guide/en/kibana/current/index.html)和其他資源。

## 最佳實務
<a name="send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-best-practices"></a>

當您將 Lambda 遙測 API 與 OpenSearch 整合時，請考慮下列最佳實務。

**安全性和存取控制**
+ **安全通訊**：使用 HTTPS 加密 Lambda 函數與 OpenSearch 叢集之間的所有通訊。在 Lambda 延伸模組和 OpenSearch 組態中設定必要的 SSL/TLS 設定。
+ **IAM 許可**：
  + 延伸模組會在與 Lambda 函數相同的執行環境中執行，因此會繼承相同層級的資源存取權，例如檔案系統、聯網和環境變數。
  + 將最低必要 IAM 許可授予 Lambda 函數，以存取 Lambda 遙測 API 並將資料寫入 OpenSearch 叢集。使用[最低權限原則](https://docs.aws.amazon.com/lambda/latest/operatorguide/least-privilege.html)來限制許可範圍。
+ **OpenSearch 存取控制**：在您的 OpenSearch 叢集中實作精細存取控制，以限制對敏感資料的存取。使用 OpenSearch 中的內建安全功能，例如使用者身分驗證、角色型存取控制和索引層級許可。
+ **信任的延伸**模組：一律只從信任的來源安裝延伸模組。使用基礎設施做為程式碼 (IaC) 工具，例如 CloudFormation ，以簡化將相同的延伸組態，包括 IAM 許可連接至多個 Lambda 函數的程序。IaC 工具也提供先前使用的擴充功能和版本的稽核記錄。
+ **敏感資料處理**：建置擴充功能時，請避免記錄敏感資料。在記錄或保留承載和中繼資料以進行稽核之前，請對其進行清理。

**成本最佳化**
+ **監控和提醒**：設定監控和提醒機制，以追蹤從 Lambda 函數傳送至 OpenSearch 的資料量。這將協助您識別和解決任何潛在的成本超支。
+ **資料保留**：仔細考慮 OpenSearch 中 Lambda 遙測資料的適當資料保留期間。較長的保留期可能會增加儲存成本，因此在可觀測性需求與成本最佳化之間取得平衡。
+ **壓縮和索引**：啟用資料壓縮並最佳化 OpenSearch 索引策略，以減少 Lambda 遙測資料的儲存體使用量。
+ **減少對 CloudWatch 的依賴**：透過直接整合 Lambda 遙測 API 與 OpenSearch，您可以減少對 CloudWatch Logs 的依賴，進而節省成本。這是因為 Lambda 遙測 API 可讓您將日誌直接傳送至 OpenSearch，而不需要在 CloudWatch 中存放和處理資料。

**可擴展性和可靠性**
+ **非同步處理**：使用非同步處理模式，例如 Amazon Simple Queue Service (Amazon SQS) 或 Amazon Kinesis，將 Lambda 函數執行與 OpenSearch 資料擷取分離。這有助於維持 Lambda 函數的回應能力，並改善系統的整體可靠性。
+ **OpenSearch 叢集擴展**：監控 OpenSearch 叢集的效能和資源使用率，並視需要進行擴展或縮減，以處理不斷增加的 Lambda 遙測資料量。
+ **容錯移轉和災難復原**：為您的 OpenSearch 叢集實作強大的災難復原策略，包括定期備份，以及在發生故障時快速還原資料的能力。

**可觀測性和監控**
+ **儀表板和視覺化**：使用 Kibana 或其他儀表板工具建立自訂儀表板和視覺化，根據 OpenSearch 中的遙測資料，提供 Lambda 函數效能和運作狀態的洞見。
+ **警示和通知**：設定警示和通知，以主動監控 Lambda 函數中的異常、錯誤或效能問題。將這些提醒和通知與您現有的事件管理程序整合。
+ **追蹤和相互關聯**：確保您的 Lambda 遙測資料包含相關的追蹤資訊，例如請求 IDs 或相互關聯 IDs，以便在分散式無伺服器應用程式中啟用end-to-end可觀測性和故障診斷。

透過遵循這些最佳實務，您可以確保 Lambda 遙測 API 與 OpenSearch 的整合安全、經濟實惠且可擴展，並為無伺服器應用程式提供全方位的可觀測性。

## 史詩
<a name="send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-epics"></a>

### 建置和部署 Lambda 延伸層
<a name="build-and-deploy-the-lam-extension-layer"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 下載原始程式碼。 | 從延伸模組儲存庫下載範例[AWS Lambda 延伸模組](https://github.com/aws-samples/aws-lambda-extensions)。 | 應用程式開發人員、雲端架構師 | 
| 導覽至 `python-example-telemetry-opensearch-extension` 資料夾。 | 您下載[AWS Lambda 的延伸](https://github.com/aws-samples/aws-lambda-extensions)模組儲存庫包含多個使用案例和語言執行時間的許多範例。導覽至 [python-example-telemetry-opensearch-extension](https://github.com/aws-samples/aws-lambda-extensions/tree/main/python-example-telemetry-opensearch-extension) 資料夾，以使用 Python OpenSearch 延伸模組，將日誌傳送至 OpenSearch。 | 應用程式開發人員、雲端架構師 | 
| 新增執行延伸端點的許可。 | 執行下列命令，讓延伸端點可執行：<pre>chmod +x python-example-telemetry-opensearch-extension/extension.py</pre> | 應用程式開發人員、雲端架構師 | 
| 在本機安裝延伸模組相依性。 | 執行下列命令來安裝 Python 程式碼的本機相依性：<pre>pip3 install -r python-example-telemetry-opensearch-extension/requirements.txt -t ./python-example-telemetry-opensearch-extension/</pre>這些相依性將與延伸程式碼一起掛載。 | 應用程式開發人員、雲端架構師 | 
| 為延伸項目建立 .zip 套件，以將其部署為 layer。 | 副檔名 .zip 檔案應該包含一個名為 的根目錄`extensions/`，其中副檔名可執行檔名所在的位置，以及另一個名為 的根目錄`python-example-telemetry-opensearch-extension/`，其中副檔名的核心邏輯及其相依性所在的位置。為擴充功能建立 .zip 套件：<pre>chmod +x extensions/python-example-telemetry-opensearch-extension<br />zip -r extension.zip extensions python-example-telemetry-opensearch-extension</pre> | 應用程式開發人員、雲端架構師 | 
| 將延伸模組部署為 Lambda 層。 | 使用您的副檔名 .zip 檔案和下列命令發佈 layer：<pre>aws lambda publish-layer-version \<br />--layer-name "python-example-telemetry-opensearch-extension" \<br />--zip-file "fileb://extension.zip"</pre> | 應用程式開發人員、雲端架構師 | 

### 將延伸模組整合到您的 函數
<a name="integrate-the-extension-into-your-function"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將圖層新增到您的函式中。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization.html)如需將圖層新增至 Lambda 函數的詳細資訊，請參閱 [Lambda 文件](https://docs.aws.amazon.com/lambda/latest/dg/adding-layers.html)。 | 應用程式開發人員、雲端架構師 | 
| 設定 函數的環境變數。 | 在函數頁面上，選擇**組態**索引標籤，並將下列環境變數新增至函數：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization.html) | 應用程式開發人員、雲端架構師 | 

### 新增記錄陳述式並測試您的函數
<a name="add-logging-statements-and-test-your-function"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將記錄陳述式新增至函數。 | 使用其中一個[內建記錄機制或您選擇的記錄模組，將記錄陳述式](https://docs.aws.amazon.com/lambda/latest/dg/python-logging.html)新增至函數。以下是在 Python 中記錄訊息的範例：<pre>print("Your Log Message Here")<br />logger = logging.getLogger(__name__)<br /><br />logger.info("Test Info Log.")<br />logger.error("Test Error Log.")</pre> | 應用程式開發人員、雲端架構師 | 
| 測試您的函數 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization.html)您應該會看到**執行函數：如果一切正常運作，則表示成功**。 | 應用程式開發人員、雲端架構師 | 

### 在 OpenSearch 中檢視您的日誌
<a name="view-your-logs-in-opensearch"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 查詢您的索引。 | 在 OpenSearch 中，執行下列命令來查詢索引：<pre>SELECT * FROM index-name</pre>您的日誌應該會顯示在查詢結果中。 | 雲端架構師 | 

## 疑難排解
<a name="send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 連線問題 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization.html) | 
| 資料擷取錯誤 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization.html) | 

## 相關資源
<a name="send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-resources"></a>
+ [OpenSearch 的 Lambda 遙測整合範例](https://github.com/aws-samples/aws-lambda-extensions/tree/main/python-example-telemetry-opensearch-extension) (GitHub 儲存庫）
+ [使用 Lambda 延伸模組增強 Lambda 函數 ](https://docs.aws.amazon.com/lambda/latest/dg/lambda-extensions.html)(Lambda 文件）
+ [Lambda 遙測 API](https://docs.aws.amazon.com/lambda/latest/dg/telemetry-api.html) (Lambda 文件）
+ [介紹 AWS Lambda 遙測 API ](https://aws.amazon.com/blogs/compute/introducing-the-aws-lambda-telemetry-api/)(AWS 部落格文章）
+ [將 AWS Lambda 遙測 API 與 Prometheus 和 OpenSearch 整合](https://aws.amazon.com/blogs/opensource/integrating-the-aws-lambda-telemetry-api-with-prometheus-and-opensearch) (AWS 部落格文章）

## 其他資訊
<a name="send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-additional"></a>

**變更日誌結構**

根據預設，延伸模組會將日誌作為巢狀文件傳送至 OpenSearch。這可讓您執行巢狀查詢來擷取個別資料欄值。

如果預設日誌輸出不符合您的特定需求，您可以透過修改由 提供的 Lambda 延伸模組的原始程式碼來自訂它 AWS。 AWS encourages 客戶可根據其業務需求調整輸出。若要變更日誌輸出，請在副檔名的原始程式碼中找到 `telemetry_dispatcher.py` 檔案中的 `dispatch_to_opensearch`函數，並進行必要的變更。

# 為以儲存格為基礎的架構設定無伺服器儲存格路由器
<a name="serverless-cell-router-architecture"></a>

*Mian Tariq 和 Ioannis Lioupras，Amazon Web Services*

## 總結
<a name="serverless-cell-router-architecture-summary"></a>

做為全域儲存格型應用程式系統的進入點，儲存格路由器負責將使用者有效率地指派給適當的儲存格，並將端點提供給使用者。儲存格路由器會處理 函數，例如儲存user-to-cell的映射、監控儲存格容量，以及在需要時請求新的儲存格。在潛在中斷期間維護儲存格路由器功能非常重要。

此模式中的儲存格路由器設計架構著重於彈性、可擴展性和整體效能最佳化。模式使用靜態路由，其中用戶端會在初始登入時快取端點，並直接與儲存格通訊。此解耦透過協助確保在儲存格路由器受損期間，以儲存格為基礎的應用程式不中斷功能，來增強系統彈性。

此模式使用 AWS CloudFormation 範本來部署架構。如需範本部署內容的詳細資訊，或使用 部署相同的組態 AWS 管理主控台，請參閱[其他資訊](#serverless-cell-router-architecture-additional)一節。

**重要**  
此模式中顯示的示範、程式碼和 CloudFormation 範本僅供說明之用。提供的資料僅用於說明設計模式和協助理解。示範和程式碼尚未可供生產使用，不應用於任何即時生產活動。任何在生產環境中使用程式碼或示範的嘗試，都強烈建議您自行承擔風險。我們建議諮詢適當的專業人員，並在生產設定中實作此模式或其任何元件之前執行徹底的測試。

## 先決條件和限制
<a name="serverless-cell-router-architecture-prereqs"></a>

**先決條件**
+ 作用中的 Amazon Web Services (AWS) 帳戶
+ 最新版本的 [AWS Command Line Interface (AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html))
+ 具有建立 CloudFormation 堆疊、 AWS Lambda 函數和相關資源所需許可的 [AWS 登入](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)資料

**產品版本**
+ Python 3.12

## Architecture
<a name="serverless-cell-router-architecture-architecture"></a>

下圖顯示儲存格路由器的高階設計。

![\[儲存格路由器的五個步驟程序。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/fd2fbf9d-9ae4-4c27-bc32-cf117350137a/images/feb90b51-dd91-483b-b5a3-b0a5359686e3.png)


圖表會逐步完成下列工作流程：

1. 使用者聯絡 Amazon API Gateway，做為儲存格路由器 API 端點的前端。

1. Amazon Cognito 會處理身分驗證和授權。

1.  AWS Step Functions 工作流程包含下列元件：
   + **Orchestrator** ‒ `Orchestrator`使用 來 AWS Step Functions 建立工作流程或狀態機器。工作流程是由儲存格路由器 API 觸發。會根據資源路徑`Orchestrator`執行 Lambda 函數。
   + **Dispatcher** `Dispatcher`‒ Lambda 函數會識別並為每個註冊的新使用者指派一個靜態儲存格。函數會搜尋使用者數目最少的儲存格，將其指派給使用者，然後傳回端點。
   + **Mapper** ‒ `Mapper`操作會在 CloudFormation 範本建立的 `RoutingDB` Amazon DynamoDB 資料庫中處理user-to-cell的映射。觸發時， `Mapper`函數會提供已指派的使用者其端點。
   + **Scaler** ‒ `Scaler`函數會追蹤儲存格佔用和可用容量。如有需要，`Scaler`函數可以透過 Amazon Simple Queue Service (Amazon SQS) 將請求傳送至佈建和部署層，以請求新的儲存格。
   + **驗證器** ‒ `Validator`函數會驗證儲存格端點並偵測任何潛在問題。

1. `RoutingDB` 存放儲存格資訊和屬性 (API 端點、 AWS 區域狀態、指標）。

1. 當儲存格的可用容量超過閾值時，儲存格路由器會透過 Amazon SQS 請求佈建和部署服務，以建立新的儲存格。

建立新儲存格時， `RoutingDB`會從佈建和部署層更新。不過，該程序超出此模式的範圍。如需儲存格型架構設計內部部署的概觀，以及此模式中所用儲存格路由器設計的詳細資訊，請參閱[其他資訊](#serverless-cell-router-architecture-additional)一節。

## 工具
<a name="serverless-cell-router-architecture-tools"></a>

**AWS 服務**
+ [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 可協助您建立、發佈、維護、監控和保護任何規模的 REST、HTTP 和 WebSocket APIs。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶 和 生命週期中管理資源 AWS 區域。
+ [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) 為 Web 和行動應用程式提供身分驗證、授權和使用者管理。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一項全受管 NoSQL 資料庫服務，可提供快速、可預期且可擴展的效能。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) 提供安全、耐用且可用的託管佇列，可協助您整合和分離分散式軟體系統和元件。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 Lambda 函數和其他 AWS 服務 來建置業務關鍵應用程式。

**其他工具**
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [Serverless-Cell-Router](https://github.com/aws-samples/Serverless-Cell-Router/) 儲存庫中使用。

## 最佳實務
<a name="serverless-cell-router-architecture-best-practices"></a>

如需建置以儲存格為基礎的架構時的最佳實務，請參閱下列 AWS Well-Architected 指引：
+ [使用以儲存格為基礎的架構減少影響範圍](https://docs.aws.amazon.com/wellarchitected/latest/reducing-scope-of-impact-with-cell-based-architecture/reducing-scope-of-impact-with-cell-based-architecture.html)
+ [AWS Well-Architected Framework 可靠性支柱：REL10-BP04 使用大量架構來限制影響範圍](https://docs.aws.amazon.com/wellarchitected/latest/reliability-pillar/rel_fault_isolation_use_bulkhead.html)

## 史詩
<a name="serverless-cell-router-architecture-epics"></a>

### 準備來源檔案
<a name="prepare-source-files"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製範例程式碼儲存庫。 | 若要將 Serverless-Cell-Router GitHub 儲存庫複製到您的電腦，請使用下列命令：<pre>git clone https://github.com/aws-samples/Serverless-Cell-Router/</pre> | 開發人員 | 
| 設定 AWS CLI 臨時登入資料。 |  AWS CLI 使用 的登入資料來設定 AWS 帳戶。本演練使用 IAM Identity Center Command AWS 行或程式設計存取選項提供的臨時憑證。 ****這會設定具有適當登入資料的 `AWS_SECRET_ACCESS_KEY`、 `AWS_ACCESS_KEY_ID`和 `AWS_SESSION_TOKEN` AWS 環境變數，以便與 搭配使用 AWS CLI。 | 開發人員 | 
| 建立 S3 儲存貯體。 | 建立 S3 儲存貯體，用於存放和存取 Serverless-Cell-Router Lambda 函數，以供 CloudFormation 範本部署。若要建立 S3 儲存貯體，請使用下列命令：<pre>aws s3api create-bucket --bucket <bucket name> --region eu-central-1 --create-bucket-configuration LocationConstraint=eu-central-1</pre> | 開發人員 | 
| 建立 .zip 檔案。 | 為位於 [Functions ](https://github.com/aws-samples/Serverless-Cell-Router/tree/main/Functions)目錄中的每個 Lambda 函數建立一個 .zip 檔案。這些 .zip 檔案將用於部署 Lambda 函數。在 Mac 上，使用下列`zip`命令：<pre>zip -j mapper-scr.zip Functions/Mapper.py<br />zip -j dispatcher-scr.zip Functions/Dispatcher.py<br />zip -j scaler-scr.zip Functions/Scaler.py<br />zip -j cp validator-scr.zip Functions/Validator.py<br />zip -j dynamodbDummyData-scr.zip Functions/DynamodbDummyData.py</pre> | 開發人員 | 
| 將 .zip 檔案複製到 S3 儲存貯體。 | 若要將所有 Lambda 函數 .zip 檔案複製到 S3 儲存貯體，請使用下列命令：<pre>aws s3 cp mapper-scr.zip s3://<bucket name><br />aws s3 cp dispatcher-scr.zip s3://<bucket name><br />aws s3 cp scaler-scr.zip s3://<bucket name><br />aws s3 cp validator-scr.zip s3://<bucket name><br />aws s3 cp dynamodbDummyData-scr.zip s3://<bucket name></pre> | 開發人員 | 

### 建立 CloudFormation 堆疊
<a name="create-the-cfn-stack"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 CloudFormation 範本。 | 若要部署 CloudFormation 範本，請執行下列 AWS CLI 命令：<pre>aws cloudformation create-stack --stack-name serverless.cell-router \<br />--template-body file://Serverless-Cell-Router-Stack-v10.yaml \<br />--capabilities CAPABILITY_IAM \<br />--parameters ParameterKey=LambdaFunctionMapperS3KeyParameterSCR,ParameterValue=mapper-scr.zip \<br />ParameterKey=LambdaFunctionDispatcherS3KeyParameterSCR,ParameterValue=dispatcher-scr.zip \<br />ParameterKey=LambdaFunctionScalerS3KeyParameterSCR,ParameterValue=scaler-scr.zip \<br />ParameterKey=LambdaFunctionAddDynamoDBDummyItemsS3KeyParameterSCR,ParameterValue=dynamodbDummyData-scr.zip \<br />ParameterKey=LambdaFunctionsS3BucketParameterSCR,ParameterValue=<S3 bucket storing lambda zip files> \<br />ParameterKey=CognitoDomain,ParameterValue=<Cognito Domain Name> \<br />--region <enter your aws region id, e.g. "eu-central-1"></pre> | 開發人員 | 
| 檢查進度。 | 登入 AWS 管理主控台，開啟位於 https：//[https://console.aws.amazon.com/cloudformation/]() 的 CloudFormation 主控台，並檢查堆疊開發的進度。當狀態為 時`CREATE_COMPLETE`，堆疊已成功部署。 | 開發人員 | 

### 評估和驗證
<a name="assess-and-verify"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將儲存格指派給使用者。 | 若要啟動 `Orchestrator`，請執行下列 curl 命令：<pre>curl -X POST \<br />-H "Authorization: Bearer {User id_token}" \<br />https://xxxxxx.execute-api.eu-central-1.amazonaws.com/Cell_Router_Development/cells</pre>會`Orchestrator`觸發 `Dispatcher`函數的執行。`Dispatcher`然後， 會驗證使用者的存在。如果找到使用者， 會`Dispatcher`傳回相關聯的儲存格 ID 和端點 URLs。如果找不到使用者， 會將儲存格`Dispatcher`配置給使用者，並將儲存格 ID 傳送至 `Scaler`函數，以評估指派的儲存格剩餘容量。`Scaler` 函數的回應如下：`"cellID : cell-0002 , endPoint_1 : https://xxxxx.execute-api.eu-north-1.amazonaws.com/ , endPoint_2 : https://xxxxxxx.execute-api.eu-central-1.amazonaws.com/"` | 開發人員 | 
| 擷取使用者儲存格。 | 若要使用 `Orchestrator`執行 `Mapper`函數，請執行下列命令：<pre>curl -X POST \<br />-H "Authorization: Bearer {User id_token}" \<br />https://xxxxxxxxx.execute-api.eu-central-1.amazonaws.com/Cell_Router_Development/mapper</pre>`Orchestrator` 會搜尋指派給使用者的儲存格，並在下列回應中傳回儲存格 ID URLs：`"cellID : cell-0002 , endPoint_1 : https://xxxxx.execute-api.eu-north-1.amazonaws.com/ , endPoint_2 : https://xxxxxxx.execute-api.eu-central-1.amazonaws.com/"` | 開發人員 | 

### 清除
<a name="clean-up"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除資源。 | 若要避免在您的帳戶中產生額外費用，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/serverless-cell-router-architecture.html) | 應用程式開發人員 | 

## 相關資源
<a name="serverless-cell-router-architecture-resources"></a>

**參考**
+ [使用可用區域實現靜態穩定性](https://aws.amazon.com/builders-library/static-stability-using-availability-zones/)
+ [AWS 故障隔離界限：靜態穩定性](https://docs.aws.amazon.com/whitepapers/latest/aws-fault-isolation-boundaries/static-stability.html)

**影片**

[Physalia：在 Amazon EBS 上提供更高可用性的儲存格型架構](https://www.youtube.com/watch?v=6IknqRZMFic) 




[https://www.youtube-nocookie.com/embed/6IknqRZMFic?controls=0](https://www.youtube-nocookie.com/embed/6IknqRZMFic?controls=0)

## 其他資訊
<a name="serverless-cell-router-architecture-additional"></a>

**以儲存格為基礎的架構設計內部部署**

雖然此模式著重於儲存格路由器，但請務必了解整個環境。環境分為三個離散圖層：
+ 路由層，或包含儲存格路由器的精簡層
+ 儲存格層，包含各種儲存格
+ 佈建和部署層，可佈建儲存格和部署應用程式

即使影響其他 layer 的受損，每個 layer 也會維持功能。 AWS 帳戶 做為故障隔離界限。

下圖顯示高層級的圖層。儲存格層和佈建和部署層超出此模式的範圍。

![\[路由層、具有多個儲存格帳戶的儲存格層，以及佈建和部署層。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/fd2fbf9d-9ae4-4c27-bc32-cf117350137a/images/137ac34d-43c3-42b6-95de-a365ff611ce8.png)


如需儲存格型架構的詳細資訊，請參閱[使用儲存格型架構降低影響範圍：儲存格路由](https://docs.aws.amazon.com/wellarchitected/latest/reducing-scope-of-impact-with-cell-based-architecture/cell-routing.html)。

**儲存格路由器設計模式**

儲存格路由器是跨儲存格的共用元件。為了減輕潛在的影響，路由層必須使用盡可能精簡且水平可擴展的設計。作為系統的進入點，路由層僅包含有效將使用者指派給適當儲存格所需的元件。此層中的元件不會參與儲存格的管理或建立。

此模式使用靜態路由，這表示用戶端會在初次登入時快取端點，然後與儲存格建立直接通訊。用戶端與儲存格路由器之間的定期互動會啟動，以確認目前狀態或擷取任何更新。此刻意解耦可在儲存格路由器停機時為現有使用者啟用不間斷的操作，並在系統內提供持續的功能和彈性。

在此模式中，儲存格路由器支援下列功能：
+ 從佈建和部署層中的儲存格資料庫擷取儲存格資料，以及儲存或更新本機資料庫。
+ 使用儲存格指派演算法，將儲存格指派給應用程式的每個新註冊使用者。
+ 將user-to-cells映射存放在本機資料庫中。
+ 在使用者指派期間檢查儲存格的容量，並將自動販賣機的事件引發至佈建和部署層以建立儲存格。
+ 使用儲存格建立條件演算法來提供此功能。
+ 透過提供靜態儲存格URLs 來回應新註冊的使用者請求。這些 URLs會以存留時間 (TTL) 快取在用戶端上。
+ 提供新的或更新的 URL，以回應無效 URL 的現有使用者請求。

若要進一步了解 CloudFormation 範本設定的示範儲存格路由器，請檢閱下列元件和步驟：

1. 設定 Amazon Cognito 使用者集區。

1. 設定和設定儲存格路由器的 API Gateway API。

1. 建立 DynamoDB 資料表。

1. 建立和設定 SQS 佇列。

1. 實作 `Orchestrator`。

1. 實作 Lambda 函數：`Dispatcher`、`Scaler`、`Mapper`、`Validator`。

1. 評估和驗證。

預先假設是佈建和部署層已建立。其實作詳細資訊超出此成品的範圍。

由於這些元件是由 CloudFormation 範本設定，因此下列步驟會以描述性和高層級顯示。假設您具備完成設定和組態所需的 AWS 技能。

*1。設定 Amazon Cognito 使用者集區*

登入 AWS 管理主控台，並在 [https://console.aws.amazon.com/cognito/]()：// 開啟 Amazon Cognito 主控台。使用應用程式整合`CellRouterPool`、託管 UI 和必要的許可，設定名為 的 Amazon Cognito 使用者集區。

*2. 設定和設定儲存格路由器的 API Gateway API*

在以下網址開啟 API Gateway 主控台：[https://console.aws.amazon.com/apigateway/]()。使用與 Amazon Cognito 使用者集區 整合的 Amazon Cognito 授權方`CellRouter`，設定名為 的 API`CellRouterPool`。實作下列元素：
+ `CellRouter` API 資源，包括`POST`方法
+ 與步驟 5 中實作的 Step Functions 工作流程整合
+ 透過 Amazon Cognito 授權方的授權
+ 整合請求和回應映射
+ 配置必要的許可

*3. 建立 DynamoDB 資料表*

在 [https://console.aws.amazon.com/dynamodb/]()：// 開啟 DynamoDB 主控台，並使用`tbl_router`下列組態建立名為 的標準 DynamoDB 資料表：
+ **分割區索引鍵** `marketId`‒
+ **排序索引鍵** `cellId`‒
+ **容量模式** ‒ 佈建
+ **Point-in-time(PITR)** ‒ 關閉

在**索引**索引標籤上，建立名為 的全域次要索引`marketId-currentCapacity-index`。`Scaler` Lambda 函數將使用 索引，對指派使用者數目最低的儲存格進行有效的搜尋。

使用下列屬性建立資料表結構：
+ `marketId` ‒ 歐洲
+ `cellId` ‒ cell-0002
+ `currentCapacity` ‒ 2
+ `endPoint_1` ‒ <第一個區域的端點>
+ `endPoint_2` ‒ <第二個區域的端點>
+ `IsHealthy` ‒ True
+ `maxCapacity` ‒ 10
+ `regionCode_1` ‒ `eu-north-1`
+ `regionCode_2` ‒ `eu-central-1`
+ `userIds` ‒ <您的電子郵件地址>

*4. 建立和設定 SQS 佇列*

在 [https://console.aws.amazon.com/sqs/]()：// 開啟 Amazon SQS 主控台，並建立名為 的標準 SQS 佇列，以 **Amazon SQS 金鑰**加密`CellProvisioning`設定。

*5. 實作協調器*

開發 Step Functions 工作流程，做為路由器`Orchestrator`的 。工作流程可透過儲存格路由器 API 呼叫。工作流程會根據資源路徑執行指定的 Lambda 函數。將步驟函數與儲存格路由器 的 API Gateway API 整合`CellRouter`，並設定呼叫 Lambda 函數所需的許可。

下圖顯示工作流程。選擇狀態會叫用其中一個 Lambda 函數。如果 Lambda 函數成功，工作流程會結束。如果 Lambda 函數失敗，則會呼叫失敗狀態。

![\[工作流程圖表，其中包含四個函數，並以失敗狀態結束。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/fd2fbf9d-9ae4-4c27-bc32-cf117350137a/images/cfe8d029-6f30-49a1-aaad-cad503bdcbae.png)


*6. 實作 Lambda 函數*

實作 `Dispatcher`、`Scaler`、 `Mapper`和 `Validator`函數。當您在示範中設定每個函數時，請定義函數的角色，並指派在 DynamoDB 資料表 上執行必要操作的必要許可`tbl_router`。此外，將每個 函數整合到工作流程 `Orchestrator`。

*Dispatcher 函數*

`Dispatcher` 函數負責識別和指派每個新註冊使用者的單一靜態儲存格。當新使用者向 全域應用程式註冊時，請求會移至 `Dispatcher`函數。函數會使用預先定義的評估條件來處理請求，如下所示：

1. **區域** ‒ 選取使用者所在市場中的儲存格。例如，如果使用者從歐洲存取 全域應用程式，請選取 AWS 區域 在歐洲使用 的儲存格。

1. **鄰近性或延遲** ‒ 選取最接近使用者的儲存格 例如，如果使用者從荷蘭存取應用程式，則函數會考慮使用法蘭克福和愛爾蘭的儲存格。有關哪個儲存格最接近的決定是根據指標，例如使用者位置與儲存格區域之間的延遲。在此範例模式中，資訊會從佈建和部署層靜態饋送。

1. **運作**狀態 ‒ `Dispatcher`函數會根據提供的儲存格狀態檢查選取的儲存格是否正常運作 （運作狀態 = true 或 false)。

1. **容量** ‒ 使用者分佈是以*儲存格邏輯中最少的使用者數量*為基礎，因此會將使用者指派給擁有最少使用者數量的儲存格。

**注意**  
這些條件僅用於解釋此範例模式。對於實際的儲存格路由器實作，您可以定義更精簡和使用案例型條件。

會`Orchestrator`叫用 Dispatcher 函數，將使用者指派給儲存格。在此示範函數中，市場值是定義為 的靜態參數`europe`。

`Dispatcher` 函數會評估儲存格是否已指派給使用者。如果已指派儲存格，則`Dispatcher`函數會傳回儲存格的端點。如果未將儲存格指派給使用者，則函數會搜尋使用者數目最少的儲存格，將其指派給使用者，並傳回端點。使用全域次要索引來最佳化儲存格搜尋查詢的效率。

*Mapper 函數*

`Mapper` 函數會監督資料庫中user-to-cell映射的儲存和維護。單一儲存格會配置給每個已註冊的使用者。每個儲存格有兩個不同的 URLs每個 AWS 區域各一個。做為 API Gateway 上託管的 API 端點，這些 URLs 可做為全域應用程式的傳入點。

當`Mapper`函數從用戶端應用程式接收請求時，它會在 DynamoDB 資料表上執行查詢`tbl_router`，以擷取與提供的電子郵件 ID 相關聯的user-to-cell映射。如果找到指派的儲存格，`Mapper`函數會立即提供儲存格的兩個 URLs。該`Mapper`函數也會主動監控儲存格 URLs 的變更，並啟動使用者設定的通知或更新。

*Scaler 函數*

`Scaler` 函數會管理儲存格的剩餘容量。對於每個新的使用者註冊請求，`Scaler`函數會評估`Dispatcher`函數指派給使用者的儲存格的可用容量。如果儲存格已根據指定的評估條件達到其預定限制，則函數會透過 Amazon SQS 佇列向佈建和部署層啟動請求，請求佈建和部署新儲存格。儲存格的擴展可以根據一組評估條件執行，如下所示：

1. **使用者上限** ‒ 每個儲存格最多可有 500 個使用者。

1. **緩衝容量** ‒ 每個儲存格的緩衝容量為 20%，這表示每個儲存格可以隨時指派給 400 個使用者。剩餘的 20% 緩衝區容量會保留給未來的使用案例和非預期案例的處理 （例如，當儲存格建立和佈建服務無法使用時）。

1. **儲存格建立** – 只要現有儲存格達到容量的 70%，就會觸發 請求來建立額外的儲存格。

**注意**  
這些條件僅用於解釋此範例模式。對於實際的儲存格路由器實作，您可以定義更精簡和使用案例型條件。

示範`Scaler`程式碼會在 `Dispatcher`成功將儲存格指派給新註冊的使用者`Orchestrator`後，由 執行。從 收到儲存格 ID 時`Scaler`， 會根據預先定義的評估條件，`Dispatcher`評估指定的儲存格是否有足夠的容量可容納其他使用者。如果儲存格容量不足，`Scaler`函數會將訊息分派給 Amazon SQS 服務。佈建和部署層內的服務會擷取此訊息，以啟動新儲存格的佈建。

**驗證器函數**

此`Validator`函數可識別並解決與儲存格存取相關的問題。當使用者登入全域應用程式時，應用程式會從使用者設定檔設定擷取儲存格的 URLs，並將使用者請求路由到儲存格中兩個指派區域的其中之一。如果無法存取 URLs，應用程式可以將驗證 URL 請求分派至儲存格路由器。cell-router 會`Orchestrator`叫用 `Validator`。會`Validator`啟動驗證程序。除了其他檢查之外，驗證可能包括下列項目：
+ 請求中的交互參考儲存格 URLs 與存放在資料庫中URLs，以識別和處理潛在的更新
+ 執行深層運作狀態檢查 （例如，對儲存格端點的`HTTP GET`請求）

總之， `Validator`函數會回應用戶端應用程式請求，並提供驗證狀態以及任何必要的修補步驟。

`Validator` 旨在增強使用者體驗。假設某些使用者在存取全域應用程式時遇到困難，因為事件導致儲存格暫時無法使用。`Validator` 函數可以提供教學性的修復步驟，而不是呈現一般錯誤。這些步驟可能包括下列動作：
+ 將事件通知使用者。
+ 在服務可用性之前提供大約的等待時間。
+ 提供用於取得其他資訊的支援聯絡電話。

`Validator` 函數的示範程式碼會驗證請求中使用者提供的儲存格 URLs 是否符合`tbl_router`資料表中存放的記錄。`Validator` 函數也會檢查儲存格是否正常運作。

# 透過 VPC 端點設定 Amazon S3 儲存貯體的私有存取權
<a name="set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint"></a>

*Martin Maritsch、Nicoras Jacob Baer、Gabriel Rodriguez Garcia、Shukhrat Khodjaev、Mohan Gowda Purushothama 和 Joaquin Rinaudo、Amazon Web Services*

## 總結
<a name="set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint-summary"></a>

在 Amazon Simple Storage Service (Amazon S3) 中，預先簽章URLs 可讓您與目標使用者共用任意大小的檔案。根據預設，Amazon S3 預先簽章URLs 可在過期時段內從網際網路存取，這使得它們易於使用。不過，企業環境通常需要存取 Amazon S3 預先簽章URLs，才能僅限於私有網路。

此模式提供無伺服器解決方案，可透過使用來自私有網路且沒有網際網路周遊的預先簽章 URLs，安全地與 S3 物件互動。在 架構中，使用者可透過內部網域名稱存取 Application Load Balancer。流量會透過 Amazon API Gateway 和 S3 儲存貯體的虛擬私有雲端 (VPC) 端點在內部路由。 AWS Lambda 函數會透過私有 VPC 端點產生檔案下載的預先簽章 URLs，這有助於增強敏感資料的安全性和隱私權。

## 先決條件和限制
<a name="set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint-prereqs"></a>

**先決條件**
+ 包含部署在 中子網路的 VPC AWS 帳戶 ，該子網路連接到公司網路 （例如，透過 AWS Direct Connect)。

**限制**
+ S3 儲存貯體的名稱必須與網域相同，因此建議您檢查 [Amazon S3 儲存貯體命名規則。](https://docs.aws.amazon.com/AmazonS3/latest/userguide/bucketnamingrules.html)
+ 此範例架構不包含已部署基礎設施的監控功能。如果您的使用案例需要監控，請考慮新增[AWS 監控服務](https://docs.aws.amazon.com/prescriptive-guidance/latest/implementing-logging-monitoring-cloudwatch/welcome.html)。
+ 此範例架構不包含輸入驗證。如果您的使用案例需要輸入驗證並提高安全性，請考慮[使用 AWS WAF 來保護您的 API](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-aws-waf.html)。
+ 此範例架構不包含 Application Load Balancer 的存取記錄。如果您的使用案例需要存取記錄，請考慮啟用[負載平衡器存取日誌](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html)。

**版本**
+ Python 3.11 版或更新版本
+ Terraform 1.6 版或更新版本

## Architecture
<a name="set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint-architecture"></a>

**目標技術堆疊**

目標技術堆疊中會使用下列 AWS 服務：
+ **Amazon S3** 是核心儲存服務，用於安全地上傳、下載和儲存檔案。
+ **Amazon API Gateway** 公開與 S3 儲存貯體互動的資源和端點。此服務在產生預先簽章URLs 以下載或上傳資料時扮演重要角色。
+ **AWS Lambda** 會產生預先簽章URLs，以便從 Amazon S3 下載檔案。API Gateway 呼叫 Lambda 函數。
+ **Amazon VPC** 在 VPC 中部署資源以提供網路隔離。VPC 包含子網路和路由表，以控制流量流程。
+ **Application Load Balancer** 會將傳入流量路由至 API Gateway 或 S3 儲存貯體的 VPC 端點。它允許來自公司網路的使用者在內部存取資源。
+ **Amazon S3 的 VPC 端點**可在 VPC 和 Amazon S3 中的資源之間進行直接的私有通訊，而不會周遊公有網際網路。
+ **AWS Identity and Access Management (IAM)** 控制對 AWS 資源的存取。設定許可以確保與 API 和其他 服務的安全互動。

**目標架構**

![\[透過 VPC 終端設定 S3 儲存貯體的私有存取權\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/683ca6a1-789c-4444-bcbf-e4e80d253df3/images/1ca7ee17-d346-4eb9-bf61-ccf42528a401.png)


此圖展示了以下要點：

1. 企業網路的使用者可以透過內部網域名稱存取 Application Load Balancer。我們假設公司網路與 中的內部網路子網路之間存在連線 AWS 帳戶 （例如，透過 Direct Connect 連線）。

1. Application Load Balancer 會將傳入流量路由至 API Gateway，以產生預先簽章URLs，將資料下載或上傳至 Amazon S3 或 S3 儲存貯體的 VPC 端點。在這兩種情況下，請求都會在內部路由，不需要周遊網際網路。

1. API Gateway 會公開要與 S3 儲存貯體互動的資源和端點。在此範例中，我們提供端點，以從 S3 儲存貯體下載檔案，但也可以進行擴充以提供上傳功能。

1. Lambda 函數會產生預先簽章的 URL，Amazon S3以使用 Application Load Balancer 的網域名稱而非公有 Amazon S3 網域，從 Amazon S3 下載檔案。

1. 使用者會收到預先簽章的 URL，並使用 Application Load Balancer 從 Amazon S3 下載檔案。負載平衡器包含預設路由，可將不適用於 API 的流量傳送至 S3 儲存貯體的 VPC 端點。

1. VPC 端點會將具有自訂網域名稱的預先簽章 URL 路由至 S3 儲存貯體。S3 儲存貯體必須具有與網域相同的名稱。

**自動化和擴展**

此模式使用 Terraform 將基礎設施從程式碼儲存庫部署到 AWS 帳戶。

## 工具
<a name="set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint-tools"></a>

**工具**
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。
+ [Terraform](https://www.terraform.io/) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您透過命令列 shell 中的命令與 AWS 服務互動。

**程式碼儲存庫**

此模式的程式碼可在 GitHub 儲存庫中取得，網址為 https：//[https://github.com/aws-samples/private-s3-vpce](https://github.com/aws-samples/private-s3-vpce)。

## 最佳實務
<a name="set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint-best-practices"></a>

此模式的範例架構使用 [IAM 許可](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html)來控制對 API 的存取。擁有有效 IAM 登入資料的任何人都可以呼叫 API。如果您的使用案例需要更複雜的授權模型，建議您[使用不同的存取控制機制](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-to-api.html)。

## 史詩
<a name="set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint-epics"></a>

### 在 中部署解決方案 AWS 帳戶
<a name="deploy-the-solution-in-an-aws-account"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 取得 AWS 登入資料。 | 檢閱您的 AWS 登入資料和對帳戶的存取。如需說明，請參閱 AWS CLI 文件中的[組態和登入資料檔案設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)。 | AWS DevOps、一般 AWS | 
| 複製儲存庫。 | 複製此模式隨附的 GitHub 儲存庫：<pre>git clone https://github.com/aws-samples/private-s3-vpce</pre> | AWS DevOps、一般 AWS | 
| 設定變數。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint.html) | AWS DevOps、一般 AWS | 
| 部署解決方案。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint.html) | AWS DevOps、一般 AWS | 

### 測試解決方案
<a name="test-the-solution"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立測試檔案。 | 將檔案上傳至 Amazon S3，以建立檔案下載的測試案例。您可以使用 [Amazon S3 主控台](https://console.aws.amazon.com/s3/)或下列 AWS CLI 命令：<pre>aws s3 cp /path/to/testfile s3://your-bucket-name/testfile</pre> | AWS DevOps、一般 AWS | 
| 測試預先簽章的 URL 功能。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint.html) | AWS DevOps、一般 AWS | 
| 清除。 | 請務必在不再需要資源時將其移除：<pre>terraform destroy</pre> | AWS DevOps、一般 AWS | 

## 疑難排解
<a name="set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| S3 物件金鑰名稱具有特殊字元，例如數字符號 (\$1) 會中斷 URL 參數並導致錯誤。 | 正確編碼 URL 參數，並確保 S3 物件金鑰名稱遵循 [Amazon S3 準則](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-keys.html)。 | 

## 相關資源
<a name="set-up-private-access-to-an-amazon-s3-bucket-through-a-vpc-endpoint-resources"></a>

Amazon S3：
+ [使用預先簽章URLs 共用物件](https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html)
+ [使用儲存貯體政策控制 VPC 端點的存取](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies-vpc-endpoint.html)

Amazon API Gateway：
+ [針對 APIs中的私有 API 使用 VPC 端點政策](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-vpc-endpoint-policies.html)

Application Load Balancer：
+ [使用 ALB、S3 和 PrivateLink 託管內部 HTTPS 靜態網站](https://aws.amazon.com/blogs/networking-and-content-delivery/hosting-internal-https-static-websites-with-alb-s3-and-privatelink/) (AWS 部落格文章）

# AWS Step Functions 使用 Amazon Bedrock 對 中的狀態進行故障診斷
<a name="troubleshooting-states-in-aws-step-functions"></a>

*Aniket Kurzadkar 和 Sangam Kushwaha，Amazon Web Services*

## 摘要
<a name="troubleshooting-states-in-aws-step-functions-summary"></a>

AWS Step Functions 錯誤處理功能可協助您看到[工作流程](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-statemachines.html)中狀態期間發生的錯誤，但仍可能難以找出錯誤的根本原因並進行偵錯。此模式可解決挑戰，並顯示 Amazon Bedrock 如何協助您解決 Step Functions 中狀態期間發生的錯誤。

Step Functions 提供工作流程協同運作，讓開發人員更輕鬆地自動化程序。Step Functions 也提供錯誤處理功能，提供下列優點：
+ 開發人員可以建立更具彈性的應用程式，在發生錯誤時不會完全失敗。
+ 工作流程可以包含條件式邏輯，以不同方式處理不同類型的錯誤。
+ 系統可以自動重試失敗的操作，可能具有指數退避。
+ 您可以針對錯誤案例定義替代執行路徑，讓工作流程調整並繼續處理。

當 Step Functions 工作流程發生錯誤時，此模式會顯示錯誤訊息和內容如何傳送至基礎模型 (FM)，例如 Step Functions 支援的 Claude 3。FM 可以分析錯誤、分類錯誤，並建議潛在的修補步驟。

## 先決條件和限制
<a name="troubleshooting-states-in-aws-step-functions-prereqs"></a>

**先決條件**
+ 作用中 AWS 帳戶
+ 對 [AWS Step Functions 和 工作流程](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-statemachines.html)的基本了解
+ Amazon Bedrock [API 連線](https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started-api.html)

**限制**
+ 您可以針對各種 使用此模式的方法 AWS 服務。不過，結果可能會根據後續由 Amazon Bedrock 評估而建立 AWS Lambda 的提示而有所不同。
+ 有些 AWS 服務 無法全部使用 AWS 區域。如需區域可用性，請參閱[依區域的 AWS 服務](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然後選擇服務的連結。

## Architecture
<a name="troubleshooting-states-in-aws-step-functions-architecture"></a>

下圖顯示此模式的工作流程和架構元件。

![\[使用 Step Functions、Amazon Bedrock 和 Amazon SNS 處理錯誤和通知的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/78f86c74-c9de-4562-adcc-105b87a77a54/images/d8eda499-ea1d-45e5-8a36-e04a44ad5c4b.png)


圖表顯示 Step Functions 狀態機器中錯誤處理和通知的自動化工作流程：

1. 開發人員會啟動狀態機器的執行。

1. Step Functions 狀態機器會開始處理其狀態。有兩種可能的結果：
   + (a) 如果所有狀態都成功執行，工作流程會直接前往 Amazon SNS 傳送電子郵件成功通知。
   + (b) 如果任何狀態失敗，工作流程會移至錯誤處理 Lambda 函數。

1. 如果發生錯誤，會發生下列情況：
   + (a) 觸發 Lambda 函數 （錯誤處理常式）。Lambda 函數會從 Step Functions 狀態機器傳遞的事件資料中擷取錯誤訊息。然後，Lambda 函數會根據此錯誤訊息準備提示，並將提示傳送至 Amazon Bedrock。提示請求與遇到的特定錯誤相關的解決方案和建議。
   + (b) 託管生成式 AI 模型的 Amazon Bedrock 會處理輸入提示。（此模式使用 Anthropic Claude 3 基礎模型 (FM)，這是 Amazon Bedrock 支援的許多 FMs之一。) AI 模型會分析錯誤內容。然後，模型會產生回應，其中包含錯誤發生原因的說明、解決錯誤的潛在解決方案，以及避免未來發生相同錯誤的建議。

     Amazon Bedrock 會將其 AI 產生的回應傳回 Lambda 函數。Lambda 函數會處理回應，可能將其格式化或擷取金鑰資訊。然後，Lambda 函數會將回應傳送至狀態機器輸出。

1. 在錯誤處理或成功執行後，工作流程會透過觸發 Amazon SNS 傳送電子郵件通知來結束。

## 工具
<a name="troubleshooting-states-in-aws-step-functions-tools"></a>

**AWS 服務**
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 是一項全受管服務，可讓您透過統一 API 使用來自領導 AI 新創公司的高效能基礎模型 (FMs) 和 Amazon。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一項運算服務，可協助您執行程式碼，無需佈建或管理伺服器。它只會在需要時執行程式碼並自動擴展，因此您只需按使用的運算時間付費。
+ [Amazon Simple Notification Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可協助您協調和管理發佈者和用戶端之間的訊息交換，包括 Web 伺服器和電子郵件地址。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一種無伺服器協同運作服務，可協助您結合 AWS Lambda 函數和其他 AWS 服務 來建置業務關鍵型應用程式。

## 最佳實務
<a name="troubleshooting-states-in-aws-step-functions-best-practices"></a>
+ 由於 Amazon Bedrock 是從訓練資料中學習的生成式 AI 模型，它也會使用該資料來訓練和產生內容。最佳實務是隱藏任何可能導致資料外洩問題的私有資訊。
+ 雖然生成式 AI 可以提供寶貴的洞見，但重要的錯誤處理決策仍應涉及人為監督，尤其是在生產環境中。

## 史詩
<a name="troubleshooting-states-in-aws-step-functions-epics"></a>

### 為您的工作流程建立狀態機器
<a name="create-a-state-machine-for-your-workflow"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立狀態機器。 | 若要建立適合您工作流程的狀態機器，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/troubleshooting-states-in-aws-step-functions.html) | AWS DevOps | 

### 建立 Lambda 函式
<a name="create-a-lam-function"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Lambda 函式。 | 若要建立 Lambda 函數，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/troubleshooting-states-in-aws-step-functions.html) | AWS DevOps | 
| 在 Lambda 程式碼中設定所需的邏輯。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/troubleshooting-states-in-aws-step-functions.html)<pre>client = boto3.client(<br />        service_name="bedrock-runtime", region_name="selected-region"<br />    )<br /><br />    # Invoke Claude 3 with the text prompt<br />    model_id = "your-model-id" # Select your Model ID, Based on the Model Id, Change the body format<br /><br />    try:<br />        response = client.invoke_model(<br />            modelId=model_id,<br />            body=json.dumps(<br />                {<br />                    "anthropic_version": "bedrock-2023-05-31",<br />                    "max_tokens": 1024,<br />                    "messages": [<br />                        {<br />                            "role": "user",<br />                            "content": [{"type": "text", "text": prompt}],<br />                        }<br />                    ],<br />                }<br />            ),<br />        )<br /></pre>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/troubleshooting-states-in-aws-step-functions.html) | AWS DevOps | 

### 將 Step Functions 與 Lambda 整合
<a name="integrate-sfn-with-lam"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 Lambda 來處理 Step Functions 中的錯誤。 | 若要設定 Step Functions 來處理錯誤而不中斷工作流程，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/troubleshooting-states-in-aws-step-functions.html) | AWS DevOps | 

## 疑難排解
<a name="troubleshooting-states-in-aws-step-functions-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| Lambda 無法存取 Amazon Bedrock API （未授權執行） | 當 Lambda 角色沒有存取 Amazon Bedrock API 的許可時，會發生此錯誤。若要解決此問題，請新增 Lambda 角色`AmazonBedrockFullAccess`的政策。如需詳細資訊，請參閱《 *AWS 受管政策參考指南*》中的 [AmazonBedrockFullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonBedrockFullAccess.html)。 | 
| Lambda 逾時錯誤 | 有時可能需要超過 30 秒才能產生回應並將其傳回，視提示而定。若要解決此問題，請增加組態時間。如需詳細資訊，請參閱《 *AWS Lambda 開發人員指南*》中的[設定 Lambda 函數逾時](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonBedrockFullAccess.html)。 | 

## 相關資源
<a name="troubleshooting-states-in-aws-step-functions-resources"></a>
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html)
+ [Amazon Bedrock API 存取](https://docs.aws.amazon.com/bedrock/latest/userguide/getting-started-api.html)
+ [建立您的第一個 Lambda 函數](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html)
+ [使用 Step Functions 開發工作流程](https://docs.aws.amazon.com/step-functions/latest/dg/developing-workflows.html#development-run-debug)
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 

# 更多模式
<a name="serverless-more-patterns-pattern-list"></a>

**Topics**
+ [使用 Athena 存取、查詢和聯結 Amazon DynamoDB 資料表](access-query-and-join-amazon-dynamodb-tables-using-athena.md)
+ [使用 GitHub 動作自動化 AWS CDK Python 應用程式的 Amazon CodeGuru 檢閱](automate-amazon-codeguru-reviews-for-aws-cdk-python-applications.md)
+ [自動化 AWS 資源評估](automate-aws-resource-assessment.md)
+ [使用 AWS SAM 自動化巢狀應用程式的部署](automate-deployment-of-nested-applications-using-aws-sam.md)
+ [使用 GitHub Actions、Artifactory 和 Terraform 在多儲存庫設定中自動化 AWS Supply Chain 資料湖的部署](automate-the-deployment-of-aws-supply-chain-data-lakes.md)
+ [自動化跨 的 Amazon RDS 執行個體複寫 AWS 帳戶](automate-the-replication-of-amazon-rds-instances-across-aws-accounts.md)
+ [使用 DynamoDB TTL 自動將項目封存至 Amazon S3](automatically-archive-items-to-amazon-s3-using-dynamodb-ttl.md)
+ [在 CodeCommit 中自動偵測變更並啟動單一儲存庫的不同 CodePipeline 管道 CodeCommit](automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.md)
+ [在 Amazon OpenSearch Service 中建置多租戶無伺服器架構](build-a-multi-tenant-serverless-architecture-in-amazon-opensearch-service.md)
+ [在 AWS 雲端中建置進階大型主機檔案檢視器](build-an-advanced-mainframe-file-viewer-in-the-aws-cloud.md)
+ [使用 AWS 服務計算風險值 (VaR)](calculate-value-at-risk-var-by-using-aws-services.md)
+ [將 AWS Service Catalog 產品複製到不同的 AWS 帳戶和 AWS 區域](copy-aws-service-catalog-products-across-different-aws-accounts-and-aws-regions.md)
+ [自動為 Java 和 Python 專案建立動態 CI 管道](create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.md)
+ [使用 CQRS 和事件來源將整體分解為微服務](decompose-monoliths-into-microservices-by-using-cqrs-and-event-sourcing.md)
+ [將以 React 為基礎的單一頁面應用程式部署至 Amazon S3 和 CloudFront](deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront.md)
+ [使用私有端點和 Application Load Balancer 在內部網站上部署 Amazon API Gateway API](deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer.md)
+ [使用基礎設施做為程式碼，在 AWS 雲端上部署和管理無伺服器資料湖](deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code.md)
+ [AWS 使用 Terraform 和 Amazon Bedrock 在 上部署 RAG 使用案例](deploy-rag-use-case-on-aws.md)
+ [使用 Amazon Bedrock 代理程式和知識庫開發全自動聊天式助理](develop-a-fully-automated-chat-based-assistant-by-using-amazon-bedrock-agents-and-knowledge-bases.md)
+ [使用 RAG 和 ReAct 提示，開發進階生成式 AI 聊天式助理](develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.md)
+ [使用 Step Functions 透過 IAM Access Analyzer 動態產生 IAM 政策](dynamically-generate-an-iam-policy-with-iam-access-analyzer-by-using-step-functions.md)
+ [使用 Amazon Cognito 和 IaC 自動化將 Amazon Quick Sight 視覺化元件內嵌至 Web 應用程式 IaC](embed-quick-sight-visual-components-into-web-apps-cognito-iac.md)
+ [確保在啟動時啟用對 Amazon S3 的 Amazon EMR 記錄](ensure-amazon-emr-logging-to-amazon-s3-is-enabled-at-launch.md)
+ [預估 DynamoDB 資料表的隨需容量成本](estimate-the-cost-of-a-dynamodb-table-for-on-demand-capacity.md)
+ [使用 Amazon Personalize 產生個人化和重新排名的建議](generate-personalized-and-re-ranked-recommendations-using-amazon-personalize.md)
+ [使用 AWS Glue 任務和 Python 產生測試資料](generate-test-data-using-an-aws-glue-job-and-python.md)
+ [從 SQL Server 遷移至 PostgreSQL 時，實作 PII 資料的 SHA1 雜湊](implement-sha1-hashing-for-pii-data-when-migrating-from-sql-server-to-postgresql.md)
+ [使用 AWS Step Functions 實作無伺服器 saga 模式](implement-the-serverless-saga-pattern-by-using-aws-step-functions.md)
+ [使用 AWS CDK 跨多個 AWS 區域、帳戶和 OUs 啟用 Amazon DevOps Guru，以改善營運效能](improve-operational-performance-by-enabling-amazon-devops-guru-across-multiple-aws-regions-accounts-and-ous-with-the-aws-cdk.md)
+ [使用 Step Functions 和 Lambda 代理函數跨 AWS 帳戶啟動 CodeBuild 專案](launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.md)
+ [使用 AWS Glue 將 Apache Cassandra 工作負載遷移至 Amazon Keyspaces](migrate-apache-cassandra-workloads-to-amazon-keyspaces-by-using-aws-glue.md)
+ [跨多個 監控共用 Amazon Machine Image 的使用 AWS 帳戶](monitor-use-of-a-shared-amazon-machine-image-across-multiple-aws-accounts.md)
+ [使用 AWS CDK 和 GitHub Actions 工作流程最佳化多帳戶無伺服器部署](optimize-multi-account-serverless-deployments.md)
+ [使用 透過驗證、轉換和分割來協調 ETL 管道 AWS Step Functions](orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.md)
+ [使用 Amazon Athena 查詢具有 SQL 的 Amazon DynamoDB 資料表](query-amazon-dynamodb-tables-sql-amazon-athena.md)
+ [使用 AWS Fargate 大規模執行事件驅動和排程工作負載](run-event-driven-and-scheduled-workloads-at-scale-with-aws-fargate.md)
+ [將自訂屬性傳送至 Amazon Cognito，並將其插入字符](send-custom-attributes-cognito.md)
+ [使用 Amazon CloudFront 在 Amazon S3 儲存貯體中透過 VPC 提供靜態內容](serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront.md)
+ [使用自動化工作流程簡化 Amazon Lex 機器人開發和部署](streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.md)
+ [使用 AWS Lambda 在六邊形架構中建構 Python 專案](structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.md)
+ [將自然語言轉換為查詢 DSL for OpenSearch 和 Elasticsearch 查詢](translate-natural-language-query-dsl-opensearch-elasticsearch.md)
+ [將資料從 Amazon Redshift 叢集跨帳戶卸載至 Amazon S3](unload-data-from-amazon-redshift-cross-accounts-to-amazon-s3.md)
+ [使用 AWS Fargate WaitCondition 勾點建構來協調資源相依性和任務執行](use-the-aws-fargate-waitcondition-hook-construct.md)
+ [使用 Amazon Bedrock 代理程式，透過文字型提示在 Amazon EKS 中自動建立存取項目控制項](using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.md)