

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

# Serverless
<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 记录传送到亚马逊 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 库导入到以与你的 PostgreS AWS Lambda QL 数据库进行交互](import-psycopg2-library-lambda.md)
+ [将 Amazon API Gateway 与亚马逊 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 Automation 任务](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)
+ [使用 Amazon Bedroc AWS Step Functions k 对中的状态进行故障排除](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*

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

此示例介绍了如何使用 AWS Amplify 和以下 Amazon Web Services 为 React Native 移动应用程序创建无服务器后端：
+ AWS AppSync
+ Amazon Cognito
+ Amazon DynamoDB

使用 Amplify 配置和部署应用程序的后端后，Amazon Cognito 将对应用程序用户进行身份验证并授权他们访问应用程序。 AppSync 然后，AWS 与前端应用程序和后端 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

## 架构
<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_cn/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>

**Amazon Web Services**
+ [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 接口，可帮助应用程序开发人员合并来自多个来源的数据，包括亚马逊 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 数据库服务，可提供快速、可预测、可扩展的性能。

**代码**

此模式中使用的示例应用程序的代码可在 GitHub [aws-amplify-react-native-ios-todo-app](https://github.com/aws-samples/aws-amplify-react-native-ios-todo-app) 存储库中找到。若要使用示例文件，请按照此模式的**操作说明**部分进行操作。

## 操作说明
<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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建支持 Amplify 中的应用程序所需后端服务。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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 Dev Center 文档中的[创建新的 Amplify 后端](https://docs.amplify.aws/lib/project-setup/create-application/q/platform/js/#create-a-new-amplify-backend)。该`amplify init`命令使用 [AWS](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 预置以下资源 CloudFormation： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon Cognito 身份验证服务。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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` 命令在项目根目录的本地文件夹（**amplify**）中创建必要的文件夹、文件和依赖文件。对于此模式中使用的 ToDoList 应用程序设置，**aws-exports.js** 就是为此目的而创建的。 | 应用程序开发人员 | 
| 将 Amazon Cognito 服务部署到 Amazon Web Services Cloud 端。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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：使用预构建的用户界面组件](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_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 AWS AppSync API 和 DynamoDB 数据库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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_cn/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*

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

此模式展示了如何在 Amazon Web Services Cloud 的单个控制面板上跨多个软件即服务（SaaS）产品管理租户生命周期。提供的参考架构可以帮助组织减少在其单个 SaaS 产品中实施冗余的共享功能，并大规模提高治理效率。

大型企业可以在不同的业务部门拥有多个 SaaS 产品。这些产品通常需要预配，以供不同订阅级别的外部租户使用。如果没有通用的租户解决方案，IT 管理员必须花时间管理多个 SaaS 中的无差异功能 APIs，而不是专注于核心产品功能开发。

此模式中提供的通用租户解决方案可帮助集中管理组织的许多共享 SaaS 产品功能，包括：
+ 安全
+ 租户预配
+ 租户数据存储
+ 租户通信
+ 产品管理
+ 日志记录和监控

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

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 了解 Amazon Cognito 或第三方身份提供者（IdP）
+ 了解 Amazon API Gateway
+ 了解 AWS Lambda
+ 了解 Amazon DynamoDB
+ 了解 AWS Identity and Access Management（AWS IAM）
+ 了解 AWS Step Functions
+ 对 AWS CloudTrail 和亚马逊的了解 CloudWatch
+ 了解 Python 库和代码
+ SaaS 知识 APIs，包括不同类型的用户（组织、租户、管理员和应用程序用户）、订阅模式和租户隔离模型
+ 了解组织的多产品 SaaS 要求和多租户订阅

**限制**
+ 此模式不包括通用租户解决方案与单个 SaaS 产品之间的集成。
+ 此模式仅在单个 AWS 区域中部署 Amazon Cognito 服务。

## 架构
<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 functions

**目标架构**

下图显示了在 Amazon Web Services Cloud 中的单个控制面板上跨多个 SaaS 产品管理租户生命周期的示例工作流程。

![\[在单个控制面板上管理租户生命周期的工作流。\]](http://docs.aws.amazon.com/zh_cn/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. 运行与每个工作流任务关联的 Lambda 函数所需任何基本数据都将从 DynamoDB 或 Amazon S3 中进行检索。其他 AWS 资源可能需要使用 AWS CloudFormation 模板进行配置。

1. 如果需要，工作流会发送请求，为特定 SaaS 产品预置其他 AWS 资源到该产品的 Amazon Web Services account。

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 用户指南中的使用 AWS CloudFormation * 模板](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)。

## 工具
<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) 可帮助您创建、发布、维护、监控和保护任何规模的 RES WebSocket APIs T、HTTP。
+ [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 (AWS IAM) ](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)通过控制验证和授权使用您 AWS 资源的用户，帮助您安全地管理对您 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 Notiﬁcation 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 函数和其他 Amazon Web Services 来构建业务关键型应用程序。

## 最佳实践
<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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确定多租户 SaaS 平台的要求。 | 为以下各项制定详细要求：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html) | 云架构师、AWS 系统管理员 | 
| 设置 Amazon Cognito 服务。 | 按照 *Amazon Cognito 开发人员指南*中 [Amazon Cognito 入门](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-getting-started.html)的说明进行操作。 | 云架构师 | 
| 配置所需 IAM policy。 | 为您的使用案例创建所需 IAM policy。然后，将策略映射到 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_cn/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html) | 云管理员、云架构师 | 

### 配置数据面板
<a name="configure-the-data-plane"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建所需数据目录。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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*。 | 数据库管理员 | 

### 配置控制面板
<a name="configure-the-control-plane"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Lambda 函数和 API Gateway APIs 以运行所需的控制平面任务。 | 创建单独的 Lambda 函数和 API Gateway APIs 来添加、删除和管理以下内容：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html)有关更多信息，请参阅 *AWS Lambda 开发人员指南*中的[将 AWS Lambda 与 Amazon API Gateway 协作使用](https://docs.aws.amazon.com/lambda/latest/dg/services-apigateway.html)。 | 应用程序开发人员 | 

### 配置工作流面板
<a name="configure-the-workflow-plane"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确定 AWS Step Functions 工作流必须运行的任务。 | 确定并记录以下各项的详细 AWS Step Functions 工作流程要求：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html) | 应用程序开发人员、构建主管 | 

### 配置通信面板
<a name="configure-the-communication-plane"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon SNS 主题。 | 创建 Amazon SNS 主题以接收有关以下内容的通知：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-tenants-across-multiple-saas-products-on-a-single-control-plane.html)有关更多信息，请参阅 *Amazon SNS 开发人员指南*中的[创建 Amazon 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)。 | 应用程序开发人员、云架构师 | 

### 配置日志和监控面板
<a name="configure-the-logging-and-monitoring-plane"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为公共租户解决方案的每个组件激活日志记录。 | 在组件级别为创建的公共租户解决方案中的每个资源激活日志记录。有关说明，请参阅：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 CloudFormation 模板。 | 使用 CloudFormation 模板自动部署和维护完整的通用租户解决方案及其所有组件。有关更多信息，请参阅 A [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)（A *mazon 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 和 Jun Soung Lee，Amazon Web Services*

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

此模式通过创建安全的自定义对象下载 URLs 预签名，简化了对亚马逊简单存储服务 (Amazon S3) Simple Service 的访问。该解决方案提高了一个具有唯一域和静态 IP 地址的单个端点。如果客户需要将 API 和 Amazon S3 端点整合到具有静态 IP 地址的统一域，则该解决方案就非常合适。在该使用案例中，用户需要遵守 IP 和域允许列表防火墙策略，即限制 API 访问权限仅限于特定的域和 IP 地址。

该架构采用密钥 AWS 服务，包括 AWS Global Accelerator Amazon API Gateway AWS Lambda、Application Load Balancer 和 Amazon S3。 AWS PrivateLink此设计将用于生成预签名的 API URLs 和 Amazon S3 终端节点集中到一个域下，该域链接到具有两个静态 IP 地址的加速器。因此，用户可以通过具有静态 IP 地址的统一域终端节点毫不费力地请求 URLs 和下载 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)，然后选择相应服务的链接。

## 架构
<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_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e19ebcb5-2138-481e-952e-3cfee9ad9e97/images/effd197c-d4d7-4990-8b66-3eb1c64aab4c.png)


该图阐释了以下概念和工作流：

1. 用户使用提供的自定义终端节点、自定义域名和关联的 IP 地址 AWS Global Accelerator，发起生成预签名 URL 的请求。

1. Lambda 函数生成指向自定义端点的预签名 URL。它使用 301 重定向进行响应，其中包含生成的预签名 URL。通过重定向的预签名 URL，用户可以使用通过 Global Accelerator 提供的自定义端点，进而自动下载对象。

预签名 URL 生成和对象下载工作流的整体架构组件如下所示：
+ 由 Global Accelerator 预调配的静态 IP 地址。
+ 使用自定义域，将加速器以 A 记录为别名注册到 Amazon Route 53 公有托管区中。
+ 创建一个 Amazon S3 存储桶，且该存储桶的名称与注册的自定义域名匹配。
+ 为 API Gateway 和 Amazon S3 服务创建 VPC 端点。
+ 配置面向内部的应用程序负载均衡器，以连接到 Global Accelerator。
+ 为附有 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) 可帮助您创建、发布、维护、监控和保护任何规模的 RES WebSocket APIs T、HTTP。
+ [应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/)将传入的应用程序流量分配到多个可用区域中的多个目标，例如亚马逊弹性计算云 (Amazon EC2) 实例。
+ [AWS Certificate Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) 可帮助您创建、存储和续订 X.509 公有和私有 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 全球网络将流量引导到最佳端点。这可提高全球受众使用的 Internet 应用程序的可用性和性能。
+ [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/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。

**代码存储库**

您可以根据自己的喜好使用 AWS CDK 或 Terraform 来部署此模式。[操作说明](#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](https://github.com/aws-samples/s3-presignedurl-staticips-endpoint-with-terraform)-terraform presignedurl-staticips-endpoint-with

## 最佳实践
<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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 决定域名。 | 决定统一 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 Terraform 开发环境。 | 要设置开发环境，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 AWS CDK 开发环境。 | 要设置开发环境，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证端点的 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，而 URL 应会自动启动测试文件的下载。 | 测试工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 销毁 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署堆栈。 | 要销毁 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/) 
+ [生成模块化 AWS CDK 预签名 URL JavaScript](https://aws.amazon.com/blogs/developer/generate-presigned-url-modular-aws-sdk-javascript/) 
+ [使用 ALB、S3 和 PrivateLink](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 和 Robert Stone，Amazon Web Services*

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

大型分布式系统使用亚马逊 EventBridge 在 AWS Organizations 组织中的各个 Amazon Web Services (AWS) 账户之间传达状态变化。但是， EventBridge 通常只能定位同一个端点或消费者 AWS 账户。不同账户中的事件总线除外。该事件总线是一个有效目标。要在另一个账户中使用来自事件总线的事件，必须将事件从源账户的事件总线推送到目标账户的事件总线。为避免在管理不同应用程序中的关键事件时遇到困难 AWS 账户，请使用此模式中推荐的方法。

这种模式说明了如何实现一个事件驱动的架构 EventBridge ，该架构涉及组织 AWS 账户 中的多个事件 AWS Organizations 。该模式使用 AWS Cloud Development Kit (AWS CDK) 工具包和 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
+ Git [已在本地安装](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
+ AWS Command Line Interface (AWS CLI) [已在本地安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ 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 Toolkit 2.126.0
+ Node.js 18.19.0
+ npm 10.2.3
+ Python 3.12

这种模式应该适用于任何版本的 AWS CDK v2 或 npm。13.0.0 至 13.6.0 版本的 Node.js 与 AWS CDK不兼容。

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

**目标架构**

下图显示了从一个账户推送事件并在另一个账户中使用该事件的架构工作流。

![\[连接源创建者账户和目标使用者账户的三步流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/34a5f3ae-511d-4636-999f-c73396770117/images/ccc4878a-6281-4a77-a483-4e6f299d7807.png)


工作流包含以下步骤：

1. Source 账户中的 Producer AWS Lambda 函数在账户的事件总线上放置一个 EventBridge 事件。

1. 跨账户 EventBridge 规则将事件路由到目标账户中的 EventBridge 事件总线。

1. 目标账户中的 EventBridge 事件总线具有调用使用者 Lambda 函数的目标 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-](https://github.com/aws-samples/aws-cdk-examples/tree/main/python/cross-account-eventbridge-in-organization) 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为源账户和目标账户配置本地凭证。 | 查看[设置新配置和凭证](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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| `cdk.json`使用您的 AWS Organizations 和账户详细信息进行修改。 | 在项目的根文件夹中，对 `cdk.json` 进行以下更改：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-cross-account-amazon-eventbridge-connection-organization.html) | 应用程序开发人员 | 
| 部署 ProducerStack 资源。 | 从项目的根目录运行以下命令：<pre>cdk deploy ProducerStack --profile sourceAccount</pre>出现提示时，接受通过 AWS CloudFormation创建的新 IAM 角色和其他与安全相关的权限。 | 应用程序开发人员 | 
| 验证 ProducerStack 资源是否已部署。 | 要验证资源，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-cross-account-amazon-eventbridge-connection-organization.html) | 应用程序开发人员 | 

### 部署 ConsumerStack 到目标账户
<a name="deploy-consumerstack-to-the-destination-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 ConsumerStack 资源。 | 从项目的根目录运行以下命令：<pre>cdk deploy ConsumerStack --profile destinationAccount</pre>出现提示时，接受通过 CloudFormation创建的新 IAM 角色和其他与安全相关的权限。 | 应用程序开发人员 | 
| 验证 ConsumerStack 资源是否已部署 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-cross-account-amazon-eventbridge-connection-organization.html) | 应用程序开发人员 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 调用创建者 Lambda 函数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/prescriptive-guidance/latest/patterns/create-cross-account-amazon-eventbridge-connection-organization.html) | 应用程序开发人员 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 摧毁 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_cn/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)
+ [亚马逊 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-亚马逊的高级事件驱动模式 (01-R) EventBridge COM3](https://www.youtube.com/watch?v=6X4lSPkn4ps)

## 附加信息
<a name="create-cross-account-amazon-eventbridge-connection-organization-additional"></a>

**创建者规则**

在 Source 账户中，创建了一个 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 资源名称）来唯一标识目标事件总线，并且 `id` 是 AWS CloudFormation使用的[逻辑 ID](https://docs.aws.amazon.com/cdk/v2/guide/identifiers.html#identifiers_logical_ids)。在创建目标规则时，不必实际存在目标事件总线。

**目标账户特定的注意事项**

在目标账户中，创建了一个 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 记录传送到亚马逊 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*

## Summary
<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 Data Stream。您的应用程序可以访问 Kinesis 数据流，近实时查看项目级别的更改。Kinesis Data Streams 还提供了对其他 Amazon Kinesis 服务的访问权限，例如 Firehose 和适用于 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-s计算机上克隆和配置的 3 次摄取](https://github.com/aws-samples/aws-dynamodb-kinesisfirehose-s3-ingestion/)存储库。
+ DynamoDB 表现有示例数据。数据必须采用以下格式：`{"SourceDataId": {"S": "123"},"MessageData":{"S": "Hello World"}}`

## 架构
<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_cn/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 服务 通过命令行外壳中的命令进行交互。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在和的整个 AWS 账户 生命周期中对其进行管理 AWS 区域。

*代码存储库*

此模式的代码可在 GitHub [aws-dynamodb-kinesisfirehose-s3 摄取](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>

### 设置和配置 Sample 代码
<a name="set-up-and-configure-the-sample-code"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装依赖项。 | 在本地计算机上，通过运行以下命令，为 `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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 检查和部署资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将您的示例数据摄取至 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 存储桶，以验证是否使用您发送的数据创建了新对象。 有关更多信息，请参阅 [GetObject](https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html)Amazon S3 文档中的。 | 应用程序开发人员，常规 AWS | 

### 清理 资源
<a name="clean-up-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理资源。 | 运行 `cdk destroy` 命令以删除此模式使用的所有资源。 | 应用程序开发人员，常规 AWS | 

## 相关资源
<a name="deliver-dynamodb-records-to-amazon-s3-using-kinesis-data-streams-and-amazon-data-firehose-with-aws-cdk-resources"></a>
+ s@@ [3-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、Marcelo Barbosa、Mario Lopez Martinez、Anbazhagan Ponnuswamy、 Gaurav Samudra 和 Abhilash Vinod，Amazon Web Services*

## Summary
<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 映射 APIs 通过您的自定义域名向您发送流量。

在 API 公开可用后，使用者便会使用它。随着公有 API 的发展，为反映新的特征和功能，其服务合同也在不断演变。但是，更改或移除现有功能并非明智之举。任何重大更改都可能影响消费者的应用程序，并导致其在运行时崩溃故障。API 版本控制对于避免破坏向后兼容性和破坏合约至关重要。

您需要制定明确的 API 版本控制策略，以帮助使用者采用这些策略。使用基于路径 APIs 的版本控制 URLs 是最直接和最常用的方法。在这种版本控制中，版本被明确定义为 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 设置自定义域名之前，您必须先在 AWS Certificate Manager中准备好 [SSL/TLS 证书](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-specify-certificate-for-custom-domain-name.html)。
+ 您必须创建或更新 DNS 提供程序的资源记录以映射到您的 API 端点。如果没有此类映射，针对自定义域名的 API 请求无法到达 API Gateway。

**限制**
+ 自定义域名在所有域名中必须是 AWS 区域 唯一的 AWS 账户。
+ 要配置具有多个级别的 API 映射，您必须使用区域自定义域名并使用 TLS 1.2 安全策略。
+ 在 API 映射中，自定义域名和映射的域名 APIs 必须相同 AWS 账户。
+ API 映射必须仅包含字母、数字和以下字符：`$-_.+!*'()/`
+ API 映射中路径的最大长度为 300 个字符。
+ 每个域名可以有 200 个具有多个级别的 API 映射。
+ 您只能使用 TLS 1.2 安全策略 APIs 将 HTTP 映射到区域自定义域名。
+ 你不能映射 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)，然后选择相应服务的链接。

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

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

下图显示了架构工作流。

![\[使用 API 映射和自定义域实施基于路径的 API 版本控制解决方案的工作流。\]](http://docs.aws.amazon.com/zh_cn/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_cn/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) 可帮助您创建、发布、维护、监控和保护任何规模的 RES WebSocket APIs T、HTTP。
+ [AWS Certificate Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) 可帮助您创建、存储和续订 X.509 公有和私有 SSL/TLS X.509 证书和密钥，以保护您的 AWS 网站和应用程序。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)是一个开源软件开发框架，用于在代码中定义您的云基础架构并通过它进行配置 CloudFormation。此模式的示例实现使用 [AWS CDK in TypeScript](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-typescript.html)。在 in AWS CDK 中 TypeScript 使用熟悉的工具，包括 Microsoft TypeScript 编译器 (`tsc`)、[Node.js](https://nodejs.org/) 和节点包管理器 (`npm`)。如果您愿意，则可以使用 [Yarn](https://yarnpkg.com/)，尽管此模式中的示例使用的是 `npm`。通过 `npm ` 存储库 [npmjs.org](https://docs.npmjs.com/) 来分发构成 [AWS 构造库](https://docs.aws.amazon.com/cdk/v2/guide/libraries.html#libraries-construct)的模块。
+ [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-](https://github.com/aws-samples/path-based-versioning-with-api-gateway) gateway 存储库中找到。

## 最佳实践
<a name="implement-path-based-api-versioning-by-using-custom-domains-best-practices"></a>
+ 使用强大的持续集成和持续交付 (CI/CD) 管道，自动测试和部署使用构建的 CloudFormation 堆栈。 AWS CDK有关此建议的更多信息，请参阅 Well-Architect [AWS ed 指南 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 资源管理的访问权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)。 AWS 账户 
+ 要对使用构建的应用程序强制执行最佳实践和安全建议 AWS CDK，我们建议您使用 [cdk-na](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) g 实用程序。

## 操作说明
<a name="implement-path-based-api-versioning-by-using-custom-domains-epics"></a>

### 准备本地环境
<a name="prepare-your-local-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要克隆示例应用程序存储库，请运行以下命令：<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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动路由堆栈的部署。 | 要启动 CloudFormation 路由堆栈的部署`CustomDomainRouterStack`，请运行以下命令，`example.com`替换为您拥有的域名：<pre>npx cdk deploy CustomDomainRouterStack --parameters PrerequisiteDomainName=example.com</pre>只有成功执行以下域 DNS 验证任务，才能成功完成堆栈部署。 | 应用程序开发人员 | 

### 验证域所有权
<a name="verify-domain-ownership"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证域的所有权。 | 在您证明关联域的所有权之前，证书将一直处于**等待验证**状态。要证明所有权，请将 CNAME 记录添加到与该域关联的托管区。有关更多信息，请参阅 AWS Certificate Manager 文档中的 [DNS 验证](https://docs.aws.amazon.com/acm/latest/userguide/dns-validation.html)。添加适当的记录可以使 `CustomDomainRouterStack` 部署成功。 | 应用程序开发人员、AWS 系统管理员、网络管理员 | 
| 创建别名记录，以指向您的 API Gateway 自定义域。 | 成功颁发并验证证书后，[创建一条 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。自定义域 URL 由配置自定义域名时唯一生成，并指定为 CloudFormation 输出参数。下文是[记录示例](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-values-basic.html)：**路由策略**：简单路由**记录名称**：`demo.api-gateway-custom-domain-versioning.example.com`**别名**：是**记录类型**：指向 AWS 资源的 “A” 类型的 DNS 记录**值**：`d-xxxxxxxxxx.execute-api.xx-xxxx-x.amazonaws.com`**TTL（秒）**：300 | 应用程序开发人员、AWS 系统管理员、网络管理员 | 

### 部署 CloudFormation 堆栈并调用 API
<a name="deploy-cfnshort-stacks-and-invoke-the-api"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 `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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理资源。 | 要销毁与此示例应用程序关联的资源，请使用以下命令：<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 实现基于标头的 API Gateway 版本控制 CloudFront](https://aws.amazon.com/blogs/compute/implementing-header-based-api-gateway-versioning-with-amazon-cloudfront/) — 这篇 AWS Compute 博客文章提供了一种基于标头的版本控制策略，作为该模式中概述的基于路径的版本控制策略的替代方案。
+ [AWS CDK 研讨会](https://cdkworkshop.com/20-typescript.html) — 此入门研讨会重点介绍如何使用构建和部署应用程序 AWS Cloud Development Kit (AWS CDK)。 AWS 本研讨会支持 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 库导入到以与你的 PostgreS AWS Lambda QL 数据库进行交互
<a name="import-psycopg2-library-lambda"></a>

*Louis Hourcade，Amazon Web Services*

## Summary
<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 运行时环境就是根据 AWS提供的 [Lambda 基础映像](https://github.com/aws/aws-lambda-base-images)创建的。基础映像中不包含库，例如 `pandas` 或 `psycopg2`。要使用库，您需要将其捆绑到自定义包中并将其附加到 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

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

**解决方案概述**

为了说明在 Lambda 中使用 `psycopg2` 库时可能面临的挑战，该模式部署了两个 Lambda 函数：
+ 一个由 .zip 文件创建的、使用 Python 运行时的 Lambda 函数。`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/) 是通用的计算机编程语言。

**代码存储库**

此模式的代码可在上的 [import-psycopg2--存储库](https://github.com/aws-samples/import-psycopg2-in-lambda-to-interact-with-postgres-database)中找到。in-lambda-to-interact with-postgres-database GitHub

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

此模式为您提供了一个使用 AWS CDK 从 Dockerfile 创建 Lambda 函数的工作示例。如果您在应用程序中重复使用此代码，请确认部署的资源满足所有安全要求。使用诸如 [Checkov](https://www.checkov.io/) 之类的工具，以在部署基础设施之前扫描云基础设施配置，进而发现配置错误。

## 操作说明
<a name="import-psycopg2-library-lambda-epics"></a>

### 克隆存储库并配置部署
<a name="clone-the-repository-and-configure-the-deployment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要在本地计算机上克隆 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 | 
| 配置部署。 | 使用有关您的 AWS 账户以下信息的`app.py`文件进行编辑：<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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 引导你的 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 测试从 .zip 文件创建的 Lambda 函数。 | 要测试从 .zip 文件创建的 Lambda 函数，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/import-psycopg2-library-lambda.html)由于 Lambda 在默认映像中找不到所需的 PostgreSQL 库，因此它无法使用 `psycopg2` 库。 | 常规 AWS | 
| 测试从 Dockerfile 文件创建的 Lambda 函数。 | 要在 Lambda 函数中使用 `psycopg2` 库，您必须编辑 Lambda 亚马逊机器映像（AMI）。要测试从 Dockerfile 文件创建的 Lambda 函数，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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 运行时的 Lamb AWS da 镜像并安装 p [ostgresql-devel，其中包含编译直接与 PostgreSQL](https://yum-info.contradodigital.com/view-package/updates/postgresql-devel/) 管理服务器交互的应用程序所需的库。Dockerfile 还会按照 `requirements.txt` 文件的说明安装 `pandas` 和 `psycopg2` 库。 | 常规 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 与亚马逊 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*

## Summary
<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）](https://aws.amazon.com/sqs/)发送消息，进而创建 REST API 端点。它在两个服务之间创建了 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)

## 架构
<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_cn/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) 可帮助您创建、发布、维护、监控和保护任何规模的 RES WebSocket APIs T、HTTP。
+ [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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建队列。 | 要创建接收来自 REST API 的消息的 SQS 队列，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 IAM 角色。 | 此 IAM 角色授予 API Gateway 对 Amazon SQS 的完全访问权限。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | AWS 开发人员、AWS 管理人 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 REST API。 | 这是 HTTP 请求发送到的 REST API。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 测试 REST API。 | 运行测试以检查是否缺少配置：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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_cn/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_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 API。 |  要部署 REST API：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/prescriptive-guidance/latest/patterns/integrate-amazon-api-gateway-with-amazon-sqs-to-handle-asynchronous-rest-apis.html) | 应用程序开发人员 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除 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 与亚马逊 SQS 集成，并解决常见错误？](https://repost.aws/knowledge-center/api-gateway-rest-api-sqs-errors) （re AWS : 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*

## Summary
<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/) [与 T [AWS Cloud Development Kit (AWS CDK) oo](https://docs.aws.amazon.com/cdk/v2/guide/cli.html) lkit、[Docker](https://docs.docker.com/get-docker/) 和 Node.js 结合使用 AWS 账户，用于设置本地开发环境并将示例架构部署到目标。](https://nodejs.org/en/download/)Projen 会自动创建一个 [Python](https://www.python.org/downloads/) 虚拟环境，其中包含[预提交](https://pre-commit.com/)工具以及用于代码质量保证、安全扫描和单元测试的工具。有关更多信息，请参阅[工具](#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 函数预留并发数的限制。

## 架构
<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_cn/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. 您通过第 3 步中的作业标识符 `{jobId}`，向 `/jobs/{jobId}` 作业 API 端点发送 HTTP `GET` 请求。

1. 作业 API 查询 `jobs` DynamoDB 表以检索作业结果。

1. 作业 API 返回包含作业结果的 HTTP 响应。

1. 事件处理函数将事件发送到错误处理函数（若事件处理失败）。

1. 错误处理函数将作业参数放入 `jobs` DynamoDB 表中。

1. 您可以向 `/jobs/{jobId}` 作业 API 端点发送 HTTP `GET` 请求，检索作业参数。

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) 是一个开源工具，可帮助您通过命令行外壳中的命令与 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 增强提案（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 
+ [Checkov](https://github.com/bridgecrewio/checkov) 是一款静态代码分析工具，用于检查基础设施即代码（IaC）是否存在安全性和合规性配置错误。
+ [jq](https://stedolan.github.io/jq/download/) 是一个用于解析 JSON 的命令行工具。
+ [Postman](https://www.postman.com/) 是 API 平台。
+ [pre-commit](https://pre-commit.com/) 是 Git 挂钩管理器。
+ [Projen](https://github.com/projen/projen) 是项目生成器。
+ [pytest](https://docs.pytest.org/en/7.2.x/index.html) 是一个 Python 框架，用于编写可读的小型测试。

**代码存储库**

此示例架构代码可以在使用 [API Gateway 和 Lambda 进行 GitHub 异步事件处理](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)进行评估。
+ 当用户向 `/jobs` 作业 API 端点发送 HTTP `POST` 请求时，系统将在两个不同的层级验证输入数据：
  + 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要在本地克隆存储库，请运行以下命令：<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_cn/prescriptive-guidance/latest/patterns/process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda.html) | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| Bootstrap 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装测试先决条件。 | 在您的工作站上安装（[AWS Command Line InterfaceAWS 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 签名版本 4 身份验证](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html)，并参考可通过[导出 REST API](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-export-api.html) 检查的公开 API 端点。 | 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_cn/prescriptive-guidance/latest/patterns/process-events-asynchronously-with-amazon-api-gateway-and-aws-lambda.html) | AWS DevOps | 
| 测试示例架构。 | 要测试示例架构，请向作业 API [发送请求](https://learning.postman.com/docs/sending-requests/requests/#next-steps)。有关更多信息，请参阅 [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 Lo CloudWatch gs 日志组](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_cn/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*

## Summary
<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/) [与 T [AWS Cloud Development Kit (AWS CDK) oo](https://docs.aws.amazon.com/cdk/v2/guide/cli.html) lkit、[Docker](https://docs.docker.com/get-docker/) 和 Node.js 结合使用 AWS 账户，用于设置本地开发环境并将示例架构部署到目标。](https://nodejs.org/en/download/)Projen 会自动创建一个 [Python](https://www.python.org/downloads/) 虚拟环境，其中包含[预提交](https://pre-commit.com/)工具以及用于代码质量保证、安全扫描和单元测试的工具。有关更多信息，请参阅[工具](#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 函数预留并发数的限制。

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

**架构**

下图显示了任务 API 与 DynamoDB Streams 以及事件处理和错误处理 Lambda 函数的交互，事件存储在亚马逊事件档案中。 EventBridge 

![\[架构和流程图，步骤列于图后。\]](http://docs.aws.amazon.com/zh_cn/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 将任务参数放在 `jobs_table` Amazon DynamoDB 表中。

1. `jobs_table` DynamoDB 表 DynamoDB 流调用事件处理 Lambda 函数。

1. 事件处理 Lambda 函数处理事件，然后将作业结果放入 `jobs_table` DynamoDB 表中。为了帮助确保结果一致，事件处理函数实施[乐观锁](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBMapper.OptimisticLocking.html)机制。

1. 您通过第 3 步中的作业标识符 `{jobId}`，向 `/jobs/{jobId}` 作业 API 端点发送 HTTP `GET` 请求。

1. 作业 API 查询 `jobs_table` DynamoDB 表以检索作业结果。

1. 作业 API 返回包含作业结果的 HTTP 响应。

1. 如果事件处理失败，事件处理函数的源映射将此事件发送到事件处理 Amazon Simple Notification Service（Amazon SNS）主题。

1. 错误处理 SNS 主题异步将事件推送到错误处理函数。

1. 错误处理函数将作业参数放入 `jobs_table` DynamoDB 表中。

   您可以向 `/jobs/{jobId}` 作业 API 端点发送 HTTP `GET` 请求，检索作业参数。

1. 如果错误处理失败，错误处理功能会将事件发送到 Ama EventBridge zon 档案。

   您可以使用重播存档的事件 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 调用端点或其他 Amazon Web Services account 中的事件总线。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [Amazon Simple Notiﬁcation Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可帮助您协调和管理发布者与客户端（包括 Web 服务器和电子邮件地址）之间的消息交换。

**其他工具**
+ [autopep8](https://github.com/hhatto/autopep8) 会根据 Python 增强提案（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 
+ [Checkov](https://github.com/bridgecrewio/checkov) 是一款静态代码分析工具，用于检查基础设施即代码（IaC）是否存在安全性和合规性配置错误。
+ [jq](https://stedolan.github.io/jq/download/) 是一个用于解析 JSON 的命令行工具。
+ [Postman](https://www.postman.com/) 是 API 平台。
+ [pre-commit](https://pre-commit.com/) 是 Git 挂钩管理器。
+ [Projen](https://github.com/projen/projen) 是项目生成器。
+ [pytest](https://docs.pytest.org/en/7.2.x/index.html) 是一个 Python 框架，用于编写可读的小型测试。

**代码存储库**

此示例架构代码可以在使用 [API Gateway 和 DynamoDB Streams 进行 GitHub 异步处理](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)进行评估。
+ 当用户向 `/jobs` 作业 API 端点发送 HTTP `POST` 请求时，系统将在两个不同的层级验证输入数据：
  + 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要在本地克隆存储库，请运行以下命令：<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_cn/prescriptive-guidance/latest/patterns/processing-events-asynchronously-with-amazon-api-gateway-and-amazon-dynamodb-streams.html) | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| Bootstrap 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装测试先决条件。 | 在您的工作站上安装（[AWS Command Line InterfaceAWS 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 签名版本 4 身份验证](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html)，并参考可通过[导出 REST API](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-export-api.html) 检查的公开 API 端点。 | DevOps 工程师 | 
| 承担 `JobsAPIInvokeRole`。 | [承担](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html) `deploy` 命令输出中打印的 `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_cn/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 Lo CloudWatch gs 日志组](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_cn/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*

## Summary
<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 和（亚马逊 SQS）异步处理事件的架构示例。 AWS Fargate这个架构支持运行无持续时间限制的处理作业，并使用基本的 REST API 作为接口。

[Projen](https://pypi.org/project/projen/) [与、[Docker](https://docs.docker.com/get-docker/) 和 Node.js 结合使用 AWS 账户，用于设置本地开发环境并将示例架构部署到目标。[AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/cli.html)](https://nodejs.org/en/download/)Projen 会自动创建一个 [Python](https://www.python.org/downloads/) 虚拟环境，其中包含[预提交](https://pre-commit.com/)工具以及用于代码质量保证、安全扫描和单元测试的工具。有关更多信息，请参阅[工具](#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 能够预调配的任务最大数。

## 架构
<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_cn/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 队列发送到 SQS 队列的消息。

1. Fargate 从 SQS 队列提取消息、处理事件，然后将作业结果放入 `jobs` DynamoDB 表中。

1. 您通过第 3 步中的作业标识符 `{jobId}`，向 `/jobs/{jobId}` 作业 API 端点发送 HTTP `GET` 请求。

1. 作业 API 查询 `jobs` DynamoDB 表以检索作业结果。

1. 作业 API 返回包含作业结果的 HTTP 响应。

1. 如果事件处理失败，SQS 队列将事件发送到死信队列（DLQ）。

1.  EventBridge 事件启动错误处理函数。

1. 错误处理函数将作业参数放入 `jobs` DynamoDB 表中。

1. 您可以向 `/jobs/{jobId}` 作业 API 端点发送 HTTP `GET` 请求，检索作业参数。

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 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 增强提案（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 
+ [Checkov](https://github.com/bridgecrewio/checkov) 是一款静态代码分析工具，用于检查基础设施即代码（IaC）是否存在安全性和合规性配置错误。
+ [jq](https://stedolan.github.io/jq/download/) 是一个用于解析 JSON 的命令行工具。
+ [Postman](https://www.postman.com/) 是 API 平台。
+ [pre-commit](https://pre-commit.com/) 是 Git 挂钩管理器。
+ [Projen](https://github.com/projen/projen) 是项目生成器。
+ [pytest](https://docs.pytest.org/en/7.2.x/index.html) 是一个 Python 框架，用于编写可读的小型测试。

**代码存储库**

此示例架构代码可以在使用 [API Gateway 和 SQS 进行 GitHub 异步处理](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)进行评估。
+ 当用户向 `/jobs` 作业 API 端点发送 HTTP `POST` 请求时，系统将在两个不同的层级验证输入数据：
  + 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要在本地克隆存储库，请运行以下命令：<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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| Bootstrap 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装测试先决条件。 | 在您的工作站上安装（[AWS Command Line InterfaceAWS 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 签名版本 4 身份验证](https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html)，并参考可通过[导出 REST API](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-export-api.html) 检查的公开 API 端点。 | DevOps 工程师 | 
| 承担 `JobsAPIInvokeRole`。 | [承担](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sts/assume-role.html) `deploy` 命令输出中打印的 `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_cn/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 Lo CloudWatch gs 日志组](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_cn/prescriptive-guidance/latest/patterns/process-events-asynchronously-with-amazon-api-gateway-amazon-sqs-and-aws-fargate.html) | 
| 由于[CloudWatch 日志日志组](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_cn/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 Automation 任务
<a name="run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions"></a>

*Elie El khoury，Amazon Web Services*

## Summary
<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 工具包服务集成的更多信息，请参阅[AWS Step Functions 开发者指南](https://docs.aws.amazon.com/step-functions/latest/dg/supported-services-awssdk.html)。

Step Function**** s 是一项低代码的可视化工作流服务，您可以使用它来构建分布式应用程序、自动执行 IT 和业务流程，以及使用 AWS 服务构建数据和机器学习管道。工作流程可以管理故障、重试、并行化、服务集成和可观测性，因此您可以专注于更高价值的业务逻辑。

自动化是一项功能，可简化亚马逊弹性计算云（亚马逊）、亚马逊关系数据库服务（Amazon RDS EC2）、Amazon Redshift和亚马逊简单存储服务（Amazon S3） AWS 服务 等的常见维护、部署和补救任务。 AWS Systems Manager自动化使您可以精确控制自动化的并发性。例如，您可以指定同时定位多少资源，以及在停止自动化之前可能发生的错误数。

有关实施的详细信息，包括运行手册步骤、参数和示例，请参阅[其他信息](#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 (IAM) 访问 Step Functions 和 Systems Manager 的权限
+  EC2 实例上[安装](https://docs.aws.amazon.com/systems-manager/latest/userguide/sysman-install-ssm-agent.html)了 Systems Manager 代理（SSM 代理）
+ [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 或更高版本

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

**目标技术堆栈**
+ AWS Step Functions
+ AWS Systems Manager  自动化

**目标架构**

![\[从 AWS Step Functions 同步运行 Systems Manager Automation 任务的架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/47c19e4f-d68d-4f91-bb68-202098757529/images/2d248aae-d858-4565-8af2-593cde0da780.png)


**自动化和扩展**
+ 此模式提供了一个 AWS CloudFormation 模板，您可以使用该模板在多个实例上部署运行手册。（请参阅 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 资源。

**代码**

此模式的代码可在 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>

### 创建运行手册
<a name="create-runbooks"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 下载 CloudFormation 模板。 | 从 GitHub 存储库的`cloudformation `文件夹下载`ssm-automation-documents.cfn.json`模板。 | AWS DevOps | 
| 创建运行手册。 | 登录 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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建测试状态机。 | 按照 [AWS Step Functions 开发人员指南](https://docs.aws.amazon.com/step-functions/latest/dg/getting-started-with-sfn.html)中的说明创建和运行状态机。对于定义，请使用以下代码。请务必使用您账户中启用系统管理器的有效实例的 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>此代码调用运行手册来运行两个命令来演示对 Systems Manager Automation 的 `waitForTaskToken` 调用。`shell` 参数值（`Shell` 或 `PowerShell`）决定了该自动化文档是运行 `AWS-RunShellScript` 还是 `AWS-RunPowerShellScript`。该任务将 “这是测试运行自动化 waitForTask令牌” 写入`/home/ssm-user/automation.log`文件，然后休眠 100 秒，然后使用任务令牌进行响应并释放工作流程中的下一个任务。如果要改为调用 `SfnRunCommandByTargets` 运行手册，请将前述代码的 `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 角色。但是，它不授予调用运行手册的权限。通过添加以下权限来更新角色：<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>

**实施详情**

此模式提供了一个部署两个 Systems Manager 运行手册的 CloudFormation 模板：
+ `SfnRunCommandByInstanceIds`使用实例运行`AWS-RunShellScript`或`AWS-RunPowerShellScript`命令 IDs。
+ `SfnRunCommandByTargets` 使用目标运行 `AWS-RunShellScript` 或 `AWS-RunPowerShellScript` 命令。

使用 Step Functions 中的 `.waitForTaskToken` 选项时，每个运行手册都实施四个步骤来实施同步调用。


| 
| 
| 步骤 | Action | 说明 | 
| --- |--- |--- |
| **1** | `Branch` | 检查 `shell` 参数值（`Shell` 或 `PowerShell`），以决定是运行适用于 Linux 的 `AWS-RunShellScript` 还是运行适用于 Windows 的 `AWS-RunPowerShellScript`。 | 
| **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，该 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 接受状态机传递的令牌作为输入。 | 

**运行手册参数**

`SfnRunCommandByInstanceIds` 运行手册：


| 
| 
| 参数名称 | Type | 必需或可选 | 说明 | 
| --- |--- |--- |--- |
| `shell` | 字符串 | 必需 | 实例 Shell，决定是运行适用于 Linux 的 `AWS-RunShellScript` 还是运行适用于 Windows 的 `AWS-RunPowerShellScript`。 | 
| `deliveryTimeout` | 整数 | 可选 | 等待命令传递到实例上的 SSM Agent 的时间（单位：秒）。此参数的最小值为 30（0.5 分钟），最大值为 2592000（720 小时）。 | 
| `executionTimeout` | 字符串 | 可选 | 在被视为已失败前命令将运行的时间（单位：秒）。默认值为 3600（1 小时）。最长值为 172800（48 小时）。 | 
| `workingDirectory` | 字符串 | 可选 | 实例上工作目录的路径。 | 
| `Commands` | StringList | 必需 | 要运行的 Shell 脚本或命令。 | 
| `InstanceIds` | StringList | 必需 | 您要在其中运行命令的实例。 IDs  | 
| `taskToken` | 字符串 | 必需 | 用于回调响应的任务令牌。 | 

`SfnRunCommandByTargets` 运行手册：


| 
| 
| Name | Type | 必需或可选 | 说明 | 
| --- |--- |--- |--- |
| `shell` | 字符串 | 必需 | 实例 Shell，决定是运行适用于 Linux 的 `AWS-RunShellScript` 还是运行适用于 Windows 的 `AWS-RunPowerShellScript`。 | 
| `deliveryTimeout` | 整数 | 可选 | 等待命令传递到实例上的 SSM Agent 的时间（单位：秒）。此参数的最小值为 30（0.5 分钟），最大值为 2592000（720 小时）。 | 
| `executionTimeout` | 整数 | 可选 | 在被视为已失败前命令将运行的时间（单位：秒）。默认值为 3600（1 小时）。最长值为 172800（48 小时）。 | 
| `workingDirectory` | 字符串 | 可选 | 实例上工作目录的路径。 | 
| `Commands` | StringList | 必需 | 要运行的 Shell 脚本或命令。 | 
| `Targets` | MapList | 必需 | 一组搜索条件，使用您指定的键值对来识别实例。例如：`[{"Key":"InstanceIds","Values":["i-02573cafcfEXAMPLE","i-0471e04240EXAMPLE"]}]` | 
| `taskToken` | 字符串 | 必需 | 用于回调响应的任务令牌。 | 

**示例输出**

下表提供了 Step 函数的示例输出。它显示步骤 5（`TaskSubmitted`）和步骤 6（`TaskSucceeded`）之间的总运行时间超过 100 秒。这表明 Step 函数在等待 `sleep 100` 命令完成后才进入工作流程中的下一个任务。


| 
| 
| ID | Type | 步骤 | 资源 | 运行时间 (ms) | Timestamp | 
| --- |--- |--- |--- |--- |--- |
| **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*

## Summary
<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（AWS）上并行读取 S3 存储桶中的对象的示例代码。该模式展示了如何使用 Python 通过 AWS Lambda 函数高效运行 I/O 绑定任务。

某金融公司在交互式解决方案中使用此模式，以实时通过手动方式批准或拒绝相关的金融交易。金融交易相关文档存储在与该市场相关的 S3 存储桶中。操作人员从 S3 存储桶中选择文档列表，分析解决方案计算出的交易总价值，并决定是批准还是拒绝所选批次。

I/O 绑定任务支持多个线程。在此示例代码中，并行.futu [res。 ThreadPoolExecutor](https://docs.python.org/3.13/library/concurrent.futures.html#concurrent.futures.ThreadPoolExecutor)可与 30 个并发线程一起使用，尽管 Lambda 函数最多支持 1,024 个线程（其中一个线程是您的主进程）。之所以设置这一限制，是因为线程过多会导致频繁的上下文切换和计算资源利用率率过高，从而造成延迟问题。此外，您还需要增加 `botocore` 中的最大池连接数，确保所有线程都能同时执行 S3 对象下载操作。

该示例代码使用的是 S3 存储桶中一个包含 JSON 数据的 8.3 KB 对象，并对该对象进行了多次读取。Lambda 函数读取该对象后，会将 JSON 数据解码为 Python 对象。2024 年 12 月，运行此示例后的结果是，使用配置了 2,304 MB 内存的 Lambda 函数在 2.3 秒内处理了 1,000 次读取，在 27 秒内处理了 10,000 次读取。 AWS Lambda 支持从 128 MB 到 10,240 MB (10 GB) 的内存配置，但将 Lambdamemory 增加到 2,304 MB 以上无助于缩短运行此特定 I/O 绑定任务的时间。

[AWS Lambda 电源调整](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 电源调整工具。有关更多信息，请参阅[问题排查](#run-parallel-reads-of-s3-objects-by-using-python-in-an-aws-lambda-function-troubleshooting)部分。
+ Amazon S3 对每个[分区前缀的 GET/HEAD 请求限制为每秒 5,500](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 功率调整 4.3.6（可选）

## 架构
<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 函数。该图还具有用于 AWS Lambda 功率调整工具的 Step Functions 工作流程，用于微调 Lambda 函数内存。这种微调有助于在成本与性能之间实现良好平衡。

![\[显示 Lambda 函数、S3 存储桶和 AWS Step Functions 的图表。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/b46e9b16-9842-4291-adfa-3ef012b89aec/images/828696e2-6df7-4536-9205-951c99449f4e.png)


**自动化和扩展**

Lambda 函数可根据需要快速扩展。为了避免在需求量较高的场景下 Amazon S3 出现 503 Slow Down 错误，建议对扩展设置一些限制。

## 工具
<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 中的命令进行交互。在此模式中， AWS CLI 版本 2 用于上传示例 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 账户用户权限来部署基础架构。如果您计划使用 Pipelin AWS CDK es 或跨账户部署，请参阅[堆栈合成器](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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 检查已安装的 Python 版本。 | 此代码已在 Python 3.9 和 Python 3.13 版本上专门测试过，且应能在这两个版本之间的所有版本上正常运行。要检查您的 Python 版本，请在终端中运行 `python3 -V`；如有需要，请安装更新版本的 Python。要验证所需模块是否已安装，请运行 `python3 -c "import pip, venv"`。若未显示错误消息，则表示这些模块已正确安装，您可以开始运行此示例代码了。 | 云架构师 | 
| 安装 AWS CDK。 | 要安装（ AWS CDK 如果尚未安装），请按照[入门中的说明进行](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)操作 AWS CDK。要确认安装的 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要克隆最新版本的存储库，请运行以下命令：<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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署应用程序。 | 运行 `cdk deploy`。写下 AWS CDK 输出：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 运行 AWS Lambda 电源调整工具。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 从 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 — 并行.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)
+ [AWS CDK 在 Python 中使用](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-python.html)
+ [使用 AWS Lambda 功率调整功能进行性能分析](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>

**代码**

以下代码片段执行并行 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_cn/prescriptive-guidance/latest/patterns/images/pattern-img/b46e9b16-9842-4291-adfa-3ef012b89aec/images/f6743412-1e52-4c4c-a51c-ac0f75b3b998.png)


从 3,009 MB 开始，无论内存如何增加，处理时间基本保持不变，但成本会随着内存大小的增加而上升。

另一项测试调查 1,536 MB 至 3,072 MB 的内存范围，使用 256 MB 的倍数作为测试内存值，处理了 10,000 次对象读取操作，结果如下。

![\[减少了调用时间缩短和调用成本上升之间的差异。\]](http://docs.aws.amazon.com/zh_cn/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_cn/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*

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

现代应用程序变得越来越分散和事件驱动，这增强了对实时监控和可观测性的需求。 AWS Lambda 是一种无服务器计算服务，在构建可扩展和事件驱动的架构方面起着至关重要的作用。但是，如果您仅依赖 Amazon Lo CloudWatch gs，Lambda 功能的监控和故障排除可能会很困难，这可能会带来延迟和有限的保留期。

为了应对这一挑战， AWS 推出了 Lambda Telemetry API，它使 Lambda 函数能够将遥测数据直接发送到第三方监控和可观察性工具。此 API 支持实时流式传输日志、指标和跟踪数据，让您能全面、及时地了解 Lambda 函数的性能和运行状况。

此模式解释了如何将 Lambda Telemetry API 与[OpenSearch](https://opensearch.org/docs/latest/)开源分布式搜索和分析引擎集成。 OpenSearch 为摄取、存储和分析大量数据提供了一个强大且可扩展的平台，这使其成为 Lambda 遥测数据的理想选择。具体而言，此模式演示了如何使用提供的 Lambda 扩展将用 Python 编写的 Lambda 函数中的日志直接发送到 OpenSearch 集群。 AWS该解决方案灵活且可自定义，因此您可以创建自己的 Lambda 扩展，或修改示例源代码以按需调整输出格式。

该模式说明了如何设置和配置 Lambda Telemetry 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 服务（如果您使用的是托管 OpenSearch 集群）

**OpenSearch 集群**：
+ 您可以使用现有的自管理 OpenSearch 集群或托管服务，例如 OpenSearch 服务。
+ 如果您使用的是 OpenSearch 服务，请按照服务文档中 [Amazon OpenSearch 服务入门](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/gsg.html)中的 OpenSearch 说明设置 OpenSearch 集群。
+ 确保可通过您的 Lambda 函数访问 OpenSearch 集群，并配置了必要的安全设置，例如访问策略、加密和身份验证。
+ 为 OpenSearch 集群配置必要的索引映射和设置，以提取 Lambda 遥测数据。有关更多信息，请参阅服务文档中的将[流数据加载到 Amazon OpenSearch OpenSearch 服务](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/integrations.html)。

**网络连接**：
+ 确保您的 Lambda 函数具有访问集群所需的网络连接。 OpenSearch 有关如何配置虚拟私有云 (VPC) 设置的指导，请参阅[ OpenSearch 服务文档中的在 VPC 内启动您的 Amazon OpenSearch 服务域](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/vpc.html)。

**IAM 角色和策略**：
+ 创建一个具有 Lambda 函数访问 OpenSearch 集群和访问存储在中的证书所需权限的 IAM 角色。 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 日志，找出与 Lambda 遥测 API 集成相关的任何错误或异常。有关问题排查指南，请参阅 [Lambda 遥测 API 文档](https://docs.aws.amazon.com/lambda/latest/dg/telemetry-api.html)。

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

此模式使用 OpenSearch 服务来存储 Lambda 函数生成的日志和遥测数据。这种方法使您能够快速将日志直接流式传输到 OpenSearch 集群，从而减少与使用 CloudWatch 日志作为中介相关的延迟和成本。


| 
| 
| [您的 Lambda 扩展代码可以通过直接使用 OpenSearch API 或使用客户端库将遥测推送到 OpenSearch 服务。OpenSearch ](https://opensearch.org/docs/latest/clients/index/)Lambda 扩展可以使用 OpenSearch API 支持的批量操作将遥测事件批量处理在一起，并在单个请求中将其发送到 OpenSearch 服务。 | 
| --- |

以下工作流程图说明了使用 OpenSearch 集群作为终端节点时 Lambda 函数的日志工作流程。

![\[向 OpenSearch 集群发送遥测数据的工作流程。\]](http://docs.aws.amazon.com/zh_cn/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：支持 Lambda 扩展将遥测数据（包括日志、指标和跟踪数据）直接发送到第三方监控和可观测性工具的 API。
+ Amazon S OpenSearch ervice OpenSearch 集群：托管在上的托管集群 AWS。该集群负责摄取、存储通过 Lambda 扩展从 Lambda 函数流式传输过来的日志数据并为其编制索引。

该工作流由以下步骤组成：

1. 调用 Lambda 函数，并在其执行过程中生成日志和遥测数据。

1. Lambda 扩展与该函数一起运行，通过 Lambda 遥测 API 捕获日志和遥测数据。

1. Lambda 扩展与 OpenSearch 服务集群建立安全连接并实时流式传输日志数据。

1.  OpenSearch 服务集群采集、索引和存储日志数据，以便通过使用 Kibana 或其他兼容应用程序等工具进行搜索、分析和可视化。

通过绕过 CloudWatch 日志并将日志数据直接发送到 OpenSearch 集群，此解决方案提供了以下好处：
+ 实现日志的实时流式传输与分析，更快地进行问题排查并提升可观测性。
+ 减少了延迟，并限制了与 CloudWatch 日志相关的潜在保留期限。
+ 具备灵活性，可针对特定输出格式或额外处理需求自定义 Lambda 扩展，或创建专属扩展。
+ 与 S OpenSearch ervice 的搜索、分析和可视化功能集成，用于日志分析和监控。

[Epics](#send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization-epics) 部分提供了 step-by-step有关设置 Lambda 扩展、配置 Lambda 函数以及与服务集群集成的说明。 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 S OpenSearch er](https://aws.amazon.com/opensearch-service/) vice 是一 AWS 项由提供的完全托管的服务，可以轻松地在云中部署、操作和扩展 OpenSearch 集群。
+ [Lambda 扩展](https://docs.aws.amazon.com/lambda/latest/dg/lambda-extensions.html)通过在函数旁边运行自定义代码来扩展 Lambda 函数的功能。您可以使用 Lambda 扩展将 Lambda 与各种监控、可观测性、安全性和治理工具集成。
+ [AWS Lambda Telemetry 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 和示例项目，可帮助您开始构建自己的扩展。
+ [Lambda 遥测集成示例提供了 OpenSearch一个示](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 函数在同一执行环境中运行，因此会继承对文件系统、网络和环境变量等资源的相同访问级别。
  + 向您的 Lambda 函数授予访问 Lambda 遥测 API 和向集群写入数据所需的最低限度 IAM 权限。 OpenSearch 使用[最低权限原则](https://docs.aws.amazon.com/lambda/latest/operatorguide/least-privilege.html)来限制权限范围。
+ **OpenSearch 访问控制**：在 OpenSearch 集群中实施精细的访问控制，以限制对敏感数据的访问。使用中的内置安全功能，例如用户身份验证、基于角色的访问控制和索引级权限。 OpenSearch
+ **可信扩展**：始终仅从可信来源安装扩展。使用基础设施即代码 (IaC) 工具，例如简化 CloudFormation 将相同扩展配置（包括 IAM 权限）附加到多个 Lambda 函数的过程。IaC 工具还能提供之前使用的扩展及版本的审计记录。
+ **敏感数据处理**：构建扩展时，避免记录敏感数据。在出于审计目的记录或保留有效载荷和元数据之前，需先对其进行清理。

**成本优化**
+ **监控和警报**：设置监控和警报机制，以跟踪 OpenSearch 从 Lambda 函数发送到的数据量。这有助于识别并解决潜在的成本超支问题。
+ **数据保留**：请仔细考虑中您的 Lambda 遥测数据的适当数据保留期。 OpenSearch留存期越长，存储成本就越高，因此需在可观测性需求与成本优化之间取得平衡。
+ **压缩和索引**：启用数据压缩并优化 OpenSearch 索引策略，以减少 Lambda 遥测数据的存储占用空间。
+ **减少对日志的依赖 CloudWatch**：通过将 Lambda Telemetry API 直接与集成 OpenSearch，您有可能减少对 CloudWatch 日志的依赖，从而节省成本。这是因为 Lambda Telemetry API 允许您直接向发送日志 OpenSearch，从而无需在中存储和处理数据。 CloudWatch

**可扩展性与可靠性**
+ **异步处理**：使用异步处理模式，例如亚马逊简单队列服务 (Amazon SQS) Simple Queue Service 或 Amazon Kinesis，将 Lambda 函数的执行与数据摄取分开。 OpenSearch 这有助于保持 Lambda 函数的响应性，并提升系统的整体可靠性。
+ **OpenSearch 集群扩展**：监控集 OpenSearch 群的性能和资源利用率，并根据需要向上或向下扩展以处理不断增加的 Lambda 遥测数据量。
+ **故障转移和灾难恢**复：为您的 OpenSearch 集群实施强大的灾难恢复策略，包括定期备份以及在出现故障时能够快速恢复数据。

**可观测性和监控**
+ **仪表板和可视化效果**：使用 Kibana 或其他仪表板工具创建自定义仪表板和可视化效果，根据中的遥测数据深入了解 Lambda 函数的性能和运行状况。 OpenSearch
+ **警报和通知**：设置提醒和通知，以主动监控 Lambda 函数中的异常、错误或性能问题。将这些提醒和通知与现有事件管理流程集成。
+ **跟踪和关联**：确保您的 Lambda 遥测数据包含相关的跟踪信息，例如请求 IDs 或关联 IDs，以实现分布式无服务器 end-to-end应用程序的可观察性和故障排除。

通过遵循这些最佳实践，您可以确保将 Lambda Telemet OpenSearch ry API 与 Lambda Telemetry API 的集成安全、经济实惠且可扩展，并为您的无服务器应用程序提供全面的可观察性。

## 操作说明
<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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 下载源代码。 | 从[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-e](https://github.com/aws-samples/aws-lambda-extensions/tree/main/python-example-telemetry-opensearch-extension) xtension文件夹，使用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 压缩包，以层形式部署。 | 扩展的 .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 文件和以下命令发布层：<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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将层添加到函数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 向函数添加日志记录语句。 | 使用[内置日志记录机制](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_cn/prescriptive-guidance/latest/patterns/send-telemetry-data-from-lambda-to-opensearch-for-analytics-visualization.html)如果一切正常，您将看到**执行函数：成功**。 | 应用程序开发人员、云架构师 | 

### 查看您的登录信息 OpenSearch
<a name="view-your-logs-in-opensearch"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查询索引。 | 在中 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_cn/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_cn/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>
+ （存储库）的 [Lambda 遥测集成示例 OpenSearch](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 鼓励客户调整输出以适应其业务需求。要更改日志输出，请在扩展源代码的 `telemetry_dispatcher.py` 文件中找到 `dispatch_to_opensearch` 函数，然后进行必要的修改。

# 为基于单元的架构设置无服务器单元路由器
<a name="serverless-cell-router-architecture"></a>

*Mian Tariq 和 Ioannis Lioupras，Amazon Web Services*

## Summary
<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

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

下图展示了单元路由器的高层级设计。

![\[单元路由器的五步流程。\]](http://docs.aws.amazon.com/zh_cn/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** AWS Step Functions − `Orchestrator` 用于创建工作流程或状态机。该工作流由单元路由器 API 触发。`Orchestrator` 根据资源路径执行 Lambda 函数。
   + **Dispatcher** ‒ `Dispatcher` Lambda 函数为每个新注册用户识别并分配一个静态单元。该函数会搜索用户数量最少的单元，将其分配给用户并返回端点。
   + **映射器**-该`Mapper`操作处理由模板创建的 Amazon `RoutingDB` DynamoDB 数据库中的 user-to-cell映射。 CloudFormation 触发后，`Mapper` 函数会为已分配的用户提供其端点。
   + **Scaler** ‒ `Scaler` 函数跟踪单元的占用情况和可用容量。需要时，`Scaler` 函数可通过 Amazon Simple Queue Service（Amazon SQS）向预调配和部署层发送请求，以请求创建新单元。
   + **Validator** ‒ `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) 可帮助您创建、发布、维护、监控和保护任何规模的 RES WebSocket APIs T、HTTP。
+ [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-](https://github.com/aws-samples/Serverless-Cell-Router/) Router 存储库中找到。

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

有关构建基于单元的架构的最佳实践，请参阅以下 Well-Architected 指南 AWS ：
+ [使用基于单元的架构缩小影响范围](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 可靠性支柱 REL1：0-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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆示例代码存储库。 | 要将 Serverless-Cell-Router GitHub 存储库克隆到您的计算机，请使用以下命令：<pre>git clone https://github.com/aws-samples/Serverless-Cell-Router/</pre> | 开发者版 | 
| 设置 AWS CLI 临时证书。 | 使用您的 AWS CLI 凭据进行配置 AWS 账户。本演练使用 AWS IAM Identity Cen **ter 命令行或编程访问**选项提供的临时证书。这会将`AWS_ACCESS_KEY_ID``AWS_SECRET_ACCESS_KEY`、和`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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 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 管理控制台，打开 CloudFormation 控制台 [https://console.aws.amazon.com/cloudformation/]()，然后查看堆栈开发进度。当状态为时 `CREATE_COMPLETE`，表示堆栈已成功部署。 | 开发者版 | 

### 评估和验证
<a name="assess-and-verify"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为用户分配单元。 | 要启动 `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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清除资源。 | 为避免您的账户产生额外费用，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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/6Iknq？RZMFic 控件=0](https://www.youtube-nocookie.com/embed/6IknqRZMFic?controls=0)

## 附加信息
<a name="serverless-cell-router-architecture-additional"></a>

**基于单元的架构设计前提**

尽管此模式聚焦于单元路由器，但了解整个环境非常重要。该环境被构建为三个独立的层：
+ 路由层，也称为薄层，包含单元路由器
+ 单元层，由多个不同的单元组成
+ 配置和部署层，负责单元的预调配及应用程序的部署

即使存在影响其他层的损伤，每层也能维持其功能。 AWS 账户 用作故障隔离边界。

下图从高层级视角展示了这些层。单元层以及预调配和部署层不在此模式的范围之内。

![\[路由层、包含多个单元账户的单元层，以及预调配和部署层。\]](http://docs.aws.amazon.com/zh_cn/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 用户池*

登录并打开 Amazon Cognito 控制台，网址为。 AWS 管理控制台[https://console.aws.amazon.com/cognito/]()设置并配置名为 `CellRouterPool` 的 Amazon Cognito 用户池，配置内容需包含应用程序集成、托管 UI 以及所需权限。

*2。为单元路由器设置和配置 API Gateway API*

打开 API Gateway 控制台，网址为[https://console.aws.amazon.com/apigateway/]()。设置并配置名为 `CellRouter` 的 API，该 API 需使用与 Amazon Cognito 用户池 `CellRouterPool` 集成的 Amazon Cognito 授权方。需实现以下元素：
+ `CellRouter` API 资源，包括 `POST` 方法
+ 与步骤 5 中实现的 Step Functions 工作流集成
+ 通过 Amazon Cognito 授权方进行授权
+ 集成请求和响应映射
+ 分配所需权限

*3。创建 DynamoDB 表*

在上打开 DynamoDB 控制台，然后使用[https://console.aws.amazon.com/dynamodb/]()以下配置创建名为的标准 DynamoDB 表：`tbl_router`
+ **分区键** ‒ `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 队列*

在上打开 Amazon SQS 控制台 [https://console.aws.amazon.com/sqs/]()，然后创建一个名为 “`CellProvisioning`配置了亚马**逊** SQS 密钥加密” 的标准 SQS 队列。

*5。实现 Orchestrator*

开发 Step Functions 工作流，作为路由器的 `Orchestrator`。该工作流可通过单元路由器 API 调用，并根据资源路径执行指定的 Lambda 函数。将该 Step 函数与单元路由器 `CellRouter` 的 API Gateway API 集成，并配置调用 Lambda 函数所需的权限。

图表显示了以下工作流。选择状态会调用某个 Lambda 函数。如果 Lambda 函数执行成功，则工作流结束。如果 Lambda 函数执行失败，则调用失败状态。

![\[包含这四个函数且以失败状态结束的工作流示意图。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/fd2fbf9d-9ae4-4c27-bc32-cf117350137a/images/cfe8d029-6f30-49a1-aaad-cad503bdcbae.png)


*6。实现 Lambda 函数*

实现 `Dispatcher`、`Mapper`、`Scaler` 和 `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` 表运行查询，以检索 user-to-cell与提供的电子邮件 ID 关联的映射。如果它找到了分配的单元格，则该`Mapper`函数会立即提供该单元格的两个单元格 URLs。该`Mapper`功能还会主动监控单元的更改 URLs，并启动通知或更新用户设置。

*Scaler 函数*

`Scaler` 函数管理单元的剩余容量。对于每个新用户注册请求，`Scaler` 函数会评估 `Dispatcher` 函数为该用户分配的单元的可用容量：如果根据指定的评估标准判断该单元已达到预先确定的容量上限，则该函数会通过 Amazon SQS 队列向预调配和部署层发起请求，请求预调配并部署新的单元。例如，可根据以下一组评估标准来执行单元的扩展：

1. **最大用户数** − 每个单元最多可承载 500 名用户。

1. **缓冲容量** − 每个单元的缓冲容量为 20%，这意味着每个单元可随时分配给 400 名用户。剩余 20% 的缓冲容量预留用于未来使用案例以及应对意外情况（例如，单元创建与预调配服务不可用时）。

1. **单元创建** ‒ 当现有单元的容量利用率达到 70% 时，会立即触发创建额外单元的请求。

**注意**  
上述标准仅用于解释此示例模式。在实际的单元路由器实现中，您可以根据具体使用案例定义更精细、更贴合业务场景的评估标准。

在 `Dispatcher` 成功为新注册的用户分配单元后，`Orchestrator` 会执行演示版 `Scaler` 代码。`Scaler` 从 `Dispatcher` 收到单元 ID 后，会根据预定义的评估标准判断该指定单元是否有足够的容量容纳更多用户。如果单元的容量不足，`Scaler` 函数会向 Amazon SQS 服务发送一条消息。预调配和部署层中的服务会获取该消息，并启动新单元的预调配流程。

**Validator 函数**

`Validator` 函数可识别并解决与单元访问相关的问题。当用户登录全局应用程序时，该应用程序会 URLs 从用户配置文件设置中检索单元格，并将用户请求路由到单元内两个分配的区域之一。如果无法访问， URLs 则应用程序可以向蜂窝路由器发送验证 URL 请求。此时，单元路由器 `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、Nicolas Jacob Baer、Gabriel Rodriguez Garcia、Shukhrat Khodjaev、Mohan Gowda Purushothama 和 Joaquin Rinaudo，Amazon Web Services*

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

在 Amazon Simple Storage Service (Amazon S3) 中， URLs 预签名允许您与目标用户共享任意大小的文件。默认情况下，预签名 URLs 的 Amazon S3 可以在到期时间窗口内从互联网访问，这使得它们使用起来很方便。但是，企业环境通常要求对预先签名 URLs 的 Amazon S3 的访问权限仅限于私有网络。

这种模式提供了一种无服务器解决方案，通过使用 URLs 来自私有网络的预签名与 S3 对象进行安全交互，无需遍历互联网。在该架构中，用户通过内部域名访问应用程序负载均衡器。流量通过 Amazon API Gateway 和 S3 存储桶的虚拟私有云（VPC）端点在内部路由。该 AWS Lambda 函数生成预签名， URLs 以便通过私有 VPC 端点下载文件，这有助于增强敏感数据的安全和隐私。

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

**先决条件**
+ 一个 VPC，包括部署在与公司网络相连的子网（例如，通过 AWS Direct Connect）。 AWS 账户 

**限制**
+ 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)。
+ 此示例架构不包括应用程序负载均衡器的访问日志记录功能。如果您的使用案例需要访问日志记录，请考虑启用[负载均衡器访问日志](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-access-logs.html)。

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

## 架构
<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 包括用于控制流量的子网和路由表。
+ **应用程序负载均衡器**将传入流量路由到 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_cn/prescriptive-guidance/latest/patterns/images/pattern-img/683ca6a1-789c-4444-bcbf-e4e80d253df3/images/1ca7ee17-d346-4eb9-bf61-ccf42528a401.png)


下图说明了以下内容：

1. 企业网络中的用户可通过内部域名访问应用程序负载均衡器。我们假设公司网络和中的内部网子网之间存在连接 AWS 账户 （例如，通过 Direct Connect 连接）。

1. Application Load Balancer 将传入流量路由到 API Gateway URLs 以生成预签名以下载或上传到 Amazon S3 的数据，或者路由到 S3 存储桶的 VPC 终端节点。在这两种情况下，请求均在内部进行路由，无需遍历互联网。

1. API Gateway 公开用于与 S3 存储桶交互的资源和端点。在此示例中，我们提供了一个用于从 S3 存储桶下载文件的端点，但也可以对其进行扩展以提供上传功能。

1. Lambda 函数生成用于从 Amazon S3 下载文件的预签名 URL 时，使用的是应用程序负载均衡器的域名，而非 Amazon S3 的公有域名。

1. 用户收到预签名 URL 后，使用该 URL 通过应用程序负载均衡器从 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/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您通过命令行 shell 中的命令与 AWS 服务进行交互。

**代码存储库**

此模式的代码可在 private [https://github.com/aws-samples/-s](https://github.com/aws-samples/private-s3-vpce) 3-vpce 的 GitHub 存储库中找到。

## 最佳实践
<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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 获取 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_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建测试文件。 | 向 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_cn/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>


| 问题 | 解决方案 | 
| --- | --- | 
| 包含井号（\$1）等特殊字符的 S3 对象键名会破坏 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：
+ [在 API Gateway APIs 中使用私有的 VPC 终端节点策略](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-vpc-endpoint-policies.html)

应用程序负载均衡器：
+ 使用 [ALB、S3 和 PrivateLink（AWS 博客文章）托管内部 HTTPS 静态网站](https://aws.amazon.com/blogs/networking-and-content-delivery/hosting-internal-https-static-websites-with-alb-s3-and-privatelink/)

# 使用 Amazon Bedroc AWS Step Functions k 对中的状态进行故障排除
<a name="troubleshooting-states-in-aws-step-functions"></a>

*Aniket Kurzadkar 和 Sangam Kushwaha，Amazon Web Services*

## Summary
<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 工作流中出现错误时，此模式将显示如何将错误消息和上下文发送到 Step Functions 支持的基础模型（FM），例如 Claude 3。基础模型可以分析错误，对其进行分类，并提出可以采取的补救措施。

## 先决条件和限制
<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)，然后选择相应服务的链接。

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

下图显示了此模式的工作流和架构组件。

![\[用于使用 Step Functions、Amazon Bedrock 和 Amazon SNS 来处理错误和发送通知的工作流。\]](http://docs.aws.amazon.com/zh_cn/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）托管着生成式人工智能模型的 Amazon Bedrock 将处理输入的提示。（此模式使用 Anthropic Claude 3 基础模型 (FM)，这是 FMs 亚马逊 Bedrock 支持的众多模型之一。） 人工智能模型将分析错误上下文。随后，此模型会生成一个响应，其中可能包含对错误发生原因的解释、错误的潜在解决方案以及有关如何避免将来再犯同样错误的建议。

     Amazon Bedrock 将向 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 提供来自领先的人工智能初创公司和亚马逊的高性能基础模型 (FMs) 供您使用。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [Amazon Simple Notiﬁcation 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 是一款从经过训练的数据中学习的生成式人工智能模型，因此它还会使用这些数据来训练和生成上下文。作为一项最佳实践，隐藏任何可能导致数据泄露问题的私有信息。
+ 尽管生成式人工智能可以提供宝贵的洞察，但关键的错误处理决策仍然涉及人工监督，尤其是在生产环境中。

## 操作说明
<a name="troubleshooting-states-in-aws-step-functions-epics"></a>

### 为工作流创建状态机
<a name="create-a-state-machine-for-your-workflow"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个状态机。 | 要创建一个适合工作流的状态机，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/troubleshooting-states-in-aws-step-functions.html) | AWS DevOps | 

### 创建 Lambda 函数
<a name="create-a-lam-function"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个 Lambda 函数。 | 要创建一个 Lambda 函数，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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_cn/prescriptive-guidance/latest/patterns/troubleshooting-states-in-aws-step-functions.html) | AWS DevOps | 

### 将 Step Functions 与 Lambda 集成
<a name="integrate-sfn-with-lam"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 Lambda，以便处理 Step Functions 中的错误。 | 要设置 Step Functions 以便在不中断工作流的情况下处理错误，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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` 策略。有关更多信息，请参阅[AmazonBedrockFullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonBedrockFullAccess.html)《*AWS 托管策略参考指南》*。 | 
| 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 操作在亚马逊自动 CodeGuru 审查 AWS CDK Python 应用程序](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)
+ [自动检测变化并为 monorepo 启动不同的 CodePipeline 管道 CodeCommit](automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.md)
+ [在 Amazon 服务中构建多租户无服务器架构 OpenSearch](build-a-multi-tenant-serverless-architecture-in-amazon-opensearch-service.md)
+ [在 Amazon Web Services Cloud 中构建高级大型机文件查看器](build-an-advanced-mainframe-file-viewer-in-the-aws-cloud.md)
+ [通过 Amazon Web Services 计算风险价值 (VaR)](calculate-value-at-risk-var-by-using-aws-services.md)
+ [跨不同 Amazon Web Services account 和 AWS 区域 复制 AWS Service Catalog 产品](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)
+ [使用私有端点和应用程序负载均衡器在内部网站上部署 Amazon API Gateway API](deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer.md)
+ [使用基础设施即代码，在 Amazon Web Services Cloud 上部署和管理无服务器数据湖](deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code.md)
+ [使用 Terraform 和 Amazon AWS 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 和提示开发基于人工智能聊天的高级生成式 AI 助手 ReAct](develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.md)
+ [使用 Step Functions 通过 IAM Access Analyzer 动态生成 IAM policy](dynamically-generate-an-iam-policy-with-iam-access-analyzer-by-using-step-functions.md)
+ [使用 Amazon Cognito 和 iaC 自动化将 Amazon Quick Sight 视觉组件嵌入到网络应用程序中](embed-quick-sight-visual-components-into-web-apps-cognito-iac.md)
+ [确保在启动时启用 Amazon EMR 日志记录到 Amazon S3](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 区域、账户中启用 Amazon DevOps Guru 并 OUs 使用 AWS CDK 来提高运营绩效](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 系统映像的使用情况 AWS 账户](monitor-use-of-a-shared-amazon-machine-image-across-multiple-aws-accounts.md)
+ [使用 AWS CDK 和 GitHub 操作工作流程优化多账户无服务器部署](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)
+ [使用亚马逊通过 VPC 在 Amazon S3 存储桶中提供静态内容 CloudFront](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 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)