

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

# 计算
<a name="compute-pattern-list"></a>

**Topics**
+ [容器和微服务](containersandmicroservices-pattern-list.md)
+ [Serverless](serverless-pattern-list.md)
+ [Networking](networking-pattern-list.md)
+ [内容分发](contentdelivery-pattern-list.md)

# 容器和微服务
<a name="containersandmicroservices-pattern-list"></a>

**Topics**
+ [从 Amazon EKS 容器访问 Amazon Neptune 数据库](access-amazon-neptune-database-from-amazon-eks-container.md)
+ [使用 AWS PrivateLink 和 Network Load Balancer 在 Amazon ECS 上私密访问容器应用程序](access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.md)
+ [使用 AWS Fargate PrivateLink、AWS 和网络负载均衡器在 Amazon ECS 上私下访问容器应用程序](access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.md)
+ [使用 AWS PrivateLink 和 Network Load Balancer 在 Amazon EKS 上私密访问容器应用程序](access-container-applications-privately-on-amazon-eks-using-aws-privatelink-and-a-network-load-balancer.md)
+ [使用 AWS Batch 自动备份 Amazon RDS for PostgreSQL 数据库实例](automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch.md)
+ [使用 CI/CD 管道在 Amazon EKS 中自动部署节点终止处理程序](automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline.md)
+ [使用 CI/CD 管道自动构建 Java 应用程序并将其部署到 Amazon EKS](automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.md)
+ [将 Amazon ECR 容器镜像复制到各处 AWS 账户 AWS 区域](copy-ecr-container-images-across-accounts-regions.md)
+ [使用 Amazon EFS 创建 Amazon ECS 任务定义并在 EC2 实例上挂载文件系统](create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs.md)
+ [使用容器映像部署 Lambda 函数](deploy-lambda-functions-with-container-images.md)
+ [使用 AWS Fargate 在 Amazon ECS 上部署 Java 微服务](deploy-java-microservices-on-amazon-ecs-using-aws-fargate.md)
+ [使用 Amazon EKS 和 Amazon S3 中的 Helm 图表存储库部署 Kubernetes 资源和软件包](deploy-kubernetes-resources-and-packages-using-amazon-eks-and-a-helm-chart-repository-in-amazon-s3.md)
+ [使用 Terraform 在亚马逊 EKS 中部署 CockroachDB 集群](deploy-cockroachdb-on-eks-using-terraform.md)
+ [在 Amazon EKS 上部署示例 Java 微服务并使用应用程序负载均衡器公开该微服务](deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer.md)
+ [在 Amazon EKS 集群上部署基于 gRPC 的应用程序并使用应用程序负载均衡器访问它](deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer.md)
+ [在作为 Docker 容器 AWS IoT Greengrass V2 运行时部署容器化应用程序](deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.md)
+ [使用 Elastic Beanstalk 部署容器](deploy-containers-by-using-elastic-beanstalk.md)
+ [使用 Lambda 函数、Amazon VPC 和无服务器架构生成静态出站 IP 地址](generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.md)
+ [迁移到 Amazon ECR 存储库时自动识别重复的容器映像](identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.md)
+ [使用 Kubernetes 在亚马逊 EKS 工作节点上安装 SSM 代理 DaemonSet](install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset.md)
+ [使用在 Amazon EKS 工作节点上安装 SSM CloudWatch 代理和代理 preBootstrapCommands](install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands.md)
+ [启用 Amazon EKS 自动模式时迁移 NGINX 入口控制器](migrate-nginx-ingress-controller-eks-auto-mode.md)
+ [将你的容器工作负载从 Azure 红帽 OpenShift (ARO) 迁移到 AWS 云端 Red Hat OpenShift 服务 (ROSA)](migrate-container-workloads-from-aro-to-rosa.md)
+ [使用 Amazon ECS Anywhere 在亚马逊 WorkSpaces 上运行亚马逊 ECS 任务](run-amazon-ecs-tasks-on-amazon-workspaces-with-amazon-ecs-anywhere.md)
+ [在亚马 EC2 逊 Linux 实例上运行 ASP.NET Core Web API Docker 容器](run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance.md)
+ [使用带 AWS Fargate 的 Amazon EFS on Amazon EKS，运行带持久数据存储的有状态工作负载](run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate.md)
+ [使用 Amazon EKS 容器组身份和 KEDA 在 Amazon EKS 中设置事件驱动的自动扩缩](event-driven-auto-scaling-with-eks-pod-identity-and-keda.md)
+ [使用 PGO 简化 Amazon EKS 上的 PostgreSQL 部署](streamline-postgresql-deployments-amazon-eks-pgo.md)
+ [使用应用程序负载均衡器简化 Amazon ECS 中双向 TLS 的应用程序身份验证](simplify-application-authentication-with-mutual-tls-in-amazon-ecs.md)
+ [更多模式](containersandmicroservices-more-patterns-pattern-list.md)

# 从 Amazon EKS 容器访问 Amazon Neptune 数据库
<a name="access-amazon-neptune-database-from-amazon-eks-container"></a>

*Ramakrishnan Palaninathan，Amazon Web Services*

## Summary
<a name="access-amazon-neptune-database-from-amazon-eks-container-summary"></a>

这种模式在完全托管的图形数据库 Amazon Neptune 与容器编排服务 Amazon Elastic Kubernetes Service（Amazon EKS）之间建立连接，用于访问 Neptune 数据库。Neptune 数据库集群被限制在 AWS上的虚拟私有云（VPC）中。因此，访问 Neptune 需要仔细配置 VPC 以启用连接。

与 Amazon Relational Database Service（Amazon RDS）for PostgreSQL 不同，Neptune 不依赖典型的数据库访问凭证。相反，它使用 AWS Identity and Access Management (IAM) 角色进行身份验证。因此，从 Amazon EKS 连接到 Neptune 需要设置一个拥有访问 Neptune 所需权限的 IAM 角色。

此外，Neptune 端点仅在集群所在的 VPC 内可访问。这意味着您必须配置网络设置以促进 Amazon EKS 与 Neptune 之间的通信。根据您的具体要求和联网偏好，可以采用[多种方法配置 VPC](https://docs.aws.amazon.com/neptune/latest/userguide/get-started-vpc.html)，以在 Neptune 与 Amazon EKS 之间实现无缝连接。每种方法都有不同的优势和注意事项，这让用户能够灵活地设计数据库架构以满足应用程序的需求。

## 先决条件和限制
<a name="access-amazon-neptune-database-from-amazon-eks-container-prereqs"></a>

**先决条件**
+ 安装最新版本的 **kubectl**（请参阅[说明](https://kubernetes.io/docs/tasks/tools/#kubectl)）。要检查版本，请运行：

  ```
  kubectl version --short
  ```
+ 安装最新版本的 **eksctl**（请参阅[说明](https://eksctl.io/installation/)）。要检查版本，请运行：

  ```
  eksctl info
  ```
+ 安装最新版本的 AWS Command Line Interface (AWS CLI) 版本 2（参见[说明](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)）。要检查版本，请运行：

  ```
  aws --version
  ```
+ 创建 Neptune 数据库集群（请参阅[说明](https://docs.aws.amazon.com/neptune/latest/userguide/get-started-cfn-create.html)）。确保通过 [VPC 对等](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html)、[AWS Transit Gateway](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-getting-started.html) 或其他方法在集群的 VPC 和 Amazon EKS 之间建立通信。此外，请确保集群的状态为“可用”，并且在端口 8182 上有针对安全组的入站规则。
+ 在现有 Amazon EKS 集群上配置 IAM OpenID Connect（OIDC）提供商（请参阅[说明](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html)）。

**产品版本**
+ [Amazon EKS 1.27](https://docs.aws.amazon.com/eks/latest/userguide/kubernetes-versions.html)
+ [Amazon Neptune 引擎版本 1.3.0.0（2023 年 11 月 15 日）](https://docs.aws.amazon.com/neptune/latest/userguide/engine-releases-1.3.0.0.html)

## 架构
<a name="access-amazon-neptune-database-from-amazon-eks-container-architecture"></a>

下图显示了 Amazon EKS 集群中的 Kubernetes 容器组（pod）与 Neptune 之间的连接，通过该连接可访问 Neptune 数据库。

![\[连接 Kubernetes 节点中的容器组（pod）与 Amazon Neptune。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/2fcf9e00-1664-462a-825e-b0fdd962f478/images/86da67e5-340e-4b29-acc6-2da416ce57eb.png)


**自动化和扩展**

您可以使用 Amazon EKS [Horizontal Pod Autoscaler](https://docs.aws.amazon.com/eks/latest/userguide/horizontal-pod-autoscaler.html) 来扩展此解决方案。

## 工具
<a name="access-amazon-neptune-database-from-amazon-eks-container-tools"></a>

**服务**
+ [亚马逊 Elastic Kubernetes Service（亚马逊](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [Amazon Neptune](https://docs.aws.amazon.com/neptune/latest/userguide/intro.html) 是一种图形数据库服务，有助于构建并运行使用高度互连数据集的应用程序。

## 最佳实践
<a name="access-amazon-neptune-database-from-amazon-eks-container-best-practices"></a>

有关最佳实践，请参阅 *Amazon EKS 最佳实践指南*中的[身份和访问权限管理](https://aws.github.io/aws-eks-best-practices/security/docs/iam/)。

## 操作说明
<a name="access-amazon-neptune-database-from-amazon-eks-container-epics"></a>

### 设置环境变量
<a name="set-environment-variables"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证集群上下文。 | 在使用 Helm 或其他命令行工具与 Amazon EKS 集群进行交互之前，必须定义用于封装集群详细信息的环境变量。这些变量将在后续命令中使用，以确保它们针对正确的集群和资源。首先，确认您在正确的集群环境中运行。这样可以确保将任何后续命令发送到预期的 Kubernetes 集群。要验证当前上下文，请运行以下命令。<pre>kubectl config current-context</pre> | AWS 管理员、云管理员 | 
| 定义 `CLUSTER_NAME` 变量。 | 定义 Amazon EKS 集群的 `CLUSTER_NAME` 环境变量。在以下命令中，将示例值`us-west-2`替换 AWS 区域 为适用于您的集群的正确值。将示例值 `eks-workshop` 替换为您的现有集群名称。<pre>export CLUSTER_NAME=$(aws eks describe-cluster --region us-west-2 --name eks-workshop --query "cluster.name" --output text)</pre> | AWS 管理员、云管理员 | 
| 验证输出。 | 要验证变量已正确设置，请运行以下命令。<pre>echo $CLUSTER_NAME</pre>验证此命令的输出与您在上一步中指定的输入相匹配。 | AWS 管理员、云管理员 | 

### 创建 IAM 角色并将其与 Kubernetes 关联
<a name="create-iam-role-and-associate-it-with-kubernetes"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建服务账户。 | 您可使用[服务账户的 IAM 角色](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html?sc_channel=el&sc_campaign=appswave&sc_content=eks-integrate-secrets-manager&sc_geo=mult&sc_country=mult&sc_outcome=acq)将您的 Kubernetes 服务账户映射到 IAM 角色，从而对 Amazon EKS 上运行的应用程序启用精细的权限管理。您可以使用 [eksctl](https://eksctl.io/) 创建 IAM 角色并将其与您的 Amazon EKS 集群中的特定 Kubernetes 服务账户相关联。 AWS 托管策略`NeptuneFullAccess`允许对您指定的 Neptune 集群进行写入和读取访问。在运行这些命令之前，您必须拥有与集群关联的 [OIDC 端点](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html?sc_channel=el&sc_campaign=appswave&sc_content=eks-integrate-secrets-manager&sc_geo=mult&sc_country=mult&sc_outcome=acq)。创建要与名为的 AWS 托管策略关联的服务帐号`NeptuneFullAccess`。<pre>eksctl create iamserviceaccount --name eks-neptune-sa --namespace default --cluster $CLUSTER_NAME --attach-policy-arn arn:aws:iam::aws:policy/NeptuneFullAccess --approve --override-existing-serviceaccounts</pre>其中，`eks-neptune-sa `是您希望创建的服务账户的名称。此命令执行完成后，将显示以下响应信息：<pre>2024-02-07 01:12:39 [ℹ] created serviceaccount "default/eks-neptune-sa"</pre> | AWS 管理员、云管理员 | 
| 验证账户设置正确。 | 确保在集群的默认命名空间中正确设置了 `eks-neptune-sa` 服务账户。<pre>kubectl get sa eks-neptune-sa -o yaml</pre>输出应该如下所示：<pre>apiVersion: v1<br />kind: ServiceAccount<br />metadata:<br />  annotations:<br />    eks.amazonaws.com/role-arn: arn:aws:iam::123456789123:role/eksctl-eks-workshop-addon-iamserviceaccount-d-Role1-Q35yKgdQOlmM<br />  creationTimestamp: "2024-02-07T01:12:39Z"<br />  labels:<br />    app.kubernetes.io/managed-by: eksctl<br />  name: eks-neptune-sa<br />  namespace: default<br />  resourceVersion: "5174750"<br />  uid: cd6ba2f7-a0f5-40e1-a6f4-4081e0042316</pre> | AWS 管理员、云管理员 | 
| 检查连接。 | 部署一个名为 `pod-util` 的示例容器组（pod）并检查与 Neptune 的连接。<pre>apiVersion: v1<br />kind: Pod<br />metadata:<br />  name: pod-util<br />  namespace: default<br />spec:<br />  serviceAccountName: eks-neptune-sa<br />  containers:<br />  - name: pod-util<br />    image: public.ecr.aws/patrickc/troubleshoot-util<br />    command:<br />      - sleep<br />      - "3600"<br />    imagePullPolicy: IfNotPresent</pre><pre>kubectl apply -f pod-util.yaml</pre><pre>kubectl exec --stdin --tty pod-util -- /bin/bash<br />bash-5.1# curl -X POST -d '{"gremlin":"g.V().limit(1)"}' https://db-neptune-1.cluster-xxxxxxxxxxxx.us-west-2.neptune.amazonaws.com:8182/gremlin<br />{"requestId":"a4964f2d-12b1-4ed3-8a14-eff511431a0e","status":{"message":"","code":200,"attributes":{"@type":"g:Map","@value":[]}},"result":{"data":{"@type":"g:List","@value":[]},"meta":{"@type":"g:Map","@value":[]}}}<br />bash-5.1# exit<br />exit</pre> | AWS 管理员、云管理员 | 

### 验证连接活动
<a name="validate-connection-activity"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启用 IAM 数据库身份验证。 | 默认情况下，创建 Neptune 数据库集群时禁用 IAM 数据库身份验证。您可以使用 AWS 管理控制台启用或禁用 IAM 数据库身份验证。按照 AWS 文档中的步骤在 Nept [une 中启用 IAM 数据库身份验证](https://docs.aws.amazon.com/neptune/latest/userguide/iam-auth-enable.html)。 | AWS 管理员、云管理员 | 
| 验证连接。 | 在此步骤中，您将与已处于运行状态的 `pod-util` 容器进行交互，以安装 **awscurl** 并验证连接。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-amazon-neptune-database-from-amazon-eks-container.html) | AWS 管理员、云管理员 | 

## 问题排查
<a name="access-amazon-neptune-database-from-amazon-eks-container-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 无法访问 Neptune 数据库。 | 查看附加到服务账号的 IAM 策略。确保它允许对您要运行的操作执行必要的操作（例如 `neptune:Connec,neptune:DescribeDBInstances`）。 | 

## 相关资源
<a name="access-amazon-neptune-database-from-amazon-eks-container-resources"></a>
+ [AWS 使用 Kubernetes 服务账户授予 Kubernetes 工作负载访问权限（亚马逊 EK](https://docs.aws.amazon.com/eks/latest/userguide/service-accounts.html) S 文档）
+ [服务账户的 IAM 角色](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html)（Amazon EKS 文档）
+ [创建新 Neptune DB 集群](https://docs.aws.amazon.com/neptune/latest/userguide/get-started-create-cluster.html)（Amazon Neptune 文档）

# 使用 AWS PrivateLink 和 Network Load Balancer 在 Amazon ECS 上私密访问容器应用程序
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer"></a>

*Kirankumar Chandrashekar，Amazon Web Services*

## Summary
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer-summary"></a>

此模式描述了如何在网络负载均衡器后面的亚马逊弹性容器服务 (Amazon ECS) 上私下托管 Docker 容器应用程序，以及如何使用 AWS 访问该应用程序。 PrivateLink然后，您便可以使用专用网络安全地访问 Amazon Web Services (AWS) Cloud 上的服务。Amazon Relational Database Service (Amazon RDS) 为在具有高可用性 (HA) 的 Amazon ECS 上运行的应用程序关系数据库提供托管。如果应用程序需要持久性存储，请使用 Amazon Elastic File System (Amazon EFS)。

运行 Docker 应用程序的 Amazon ECS 服务在前端装有 Network Load Balancer，可以与虚拟私有云 (VPC) 终端节点相关联，以便通过 AWS PrivateLink 进行访问。然后，可以使用 VPC 终端节点与其他 VPCs 人共享此 VPC 终端节点服务。

你也可以使用 [AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html) 代替 Amazon A EC2 uto Scaling 群组。有关更多信息，请参阅[使用 AWS Fargate、AWS 和网络负载均衡器在 Amazon ECS PrivateLink 上私下访问容器应用程序](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html?did=pg_card)。

## 先决条件和限制
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户
+ 已在 Linux、macOS 或 Windows 上安装并配置 [AWS 命令行界面（AWS CLI）版本 2](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ [Docker](https://www.docker.com/)，已在 Linux、macOS 或 Windows 上安装并配置
+ 在 Docker 上运行的应用程序

## 架构
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer-architecture"></a>

![\[使用 AWS PrivateLink 在网络负载均衡器后面访问 Amazon ECS 上的容器应用程序。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a316bf46-24db-4514-957d-abc60f8f6962/images/573951ed-74bb-4023-9d9c-43e77e4f8eda.png)


 

**技术堆栈**
+ Amazon CloudWatch
+ 亚马逊弹性计算云（亚马逊 EC2）
+ Amazon A EC2 uto Scaling
+ Amazon Elastic Container Registry(Amazon ECR)
+ Amazon ECS
+ Amazon RDS
+ Amazon Simple Storage Service（Amazon S3）
+ AWS Lambda
+ AWS PrivateLink
+ AWS Secrets Manager
+ 应用程序负载均衡器
+ Network Load Balancer
+ VPC

*自动化和扩展*
+ 您可以使用 [AWS](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 通过使用[基础设施即代码 CloudFormation](https://docs.aws.amazon.com/whitepapers/latest/introduction-devops-aws/infrastructure-as-code.html)来创建此模式。

## 工具
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer-tools"></a>
+ [亚马逊 EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) — 亚马逊弹性计算云 (Amazon EC2) 在 AWS 云中提供可扩展的计算容量。
+ [Amazon A EC2 ut](https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html) EC2 o Scaling — Amazon Auto Scaling 可帮助您确保有正确数量的亚马逊 EC2 实例可用来处理应用程序的负载。
+ [Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) - Amazon Elastic Container Service (Amazon ECS)是一项高度可扩展的快速容器管理服务，可帮助轻松运行、停止和管理集群上的容器。
+ [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) - Amazon Elastic Container Registry (Amazon ECR) 是一项安全、可靠且可扩展的 AWS 托管容器映像注册表服务。
+ [Amazon EFS](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html) - Amazon Elastic File System (Amazon EFS)可提供简单、可扩展、完全托管的弹性 NFS 文件系统，以便与 Amazon Web Services Cloud 服务和本地资源配合使用。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) - Lambda 是一项计算服务，使您无需预调配或管理服务器即可运行代码。
+ [Amazon RDS](https://docs.aws.amazon.com/rds/) – Amazon Relational Database Service (Amazon RDS) 是一项 Web 服务，使用户能够在 Amazon Web Services Cloud 中轻松设置、操作和扩展关系数据库。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一项面向互联网的存储服务。该服务旨在降低开发人员进行网络规模级计算的难度。
+ [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) - Secrets Manager 允许您将代码中的硬编码凭证(包括密码)替换为对 Secrets Manager 的 API 调用，并以编程方式检索密钥。
+ [Amazon VPC](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) - Amazon Virtual Private Cloud (Amazon VPC)可助您将 AWS 资源启动到您已定义的虚拟网络中。
+ [Elastic L](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) oad Balancing — Elastic Load Balancing 将传入的应用程序或网络流量分配到多个可用区的多个目标，例如亚马逊 EC2 实例、容器和 IP 地址。
+ [Docker](https://www.docker.com/) - Docker 允许开发人员打包、交付和运行任何应用程序，并将其作为轻量、便携且自给自足的容器。

## 操作说明
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer-epics"></a>

### 创建联网组件
<a name="create-networking-components"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 VPC。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 

### 创建负载均衡器
<a name="create-the-load-balancers"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建网络负载均衡器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 创建应用程序负载均衡器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 

### 创建 Amazon EFS 文件系统
<a name="create-an-amazon-efs-file-system"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon EFS 文件系统。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 子网的挂载目标。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 验证子网是否已挂载为目标。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 

### 创建 S3 存储桶
<a name="create-an-s3-bucket"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 S3 存储桶。 | 打开 Amazon S3 控制台并创建一个 S3 存储桶，以在需要时存储应用程序的静态资产。 | 云管理员 | 

### 创建 Secrets Manager 密钥
<a name="create-a-secrets-manager-secret"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 AWS KMS 密钥以加密 Secrets Manager 密钥。 | 打开 AWS Key Management Service (AWS KMS)控制台并创建 KMS 密钥。 | 云管理员 | 
|  创建 Secrets Manager 密钥以存储 Amazon RDS 密码。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员  | 

### 创建 Amazon RDS 实例
<a name="create-an-amazon-rds-instance"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建数据库子网组。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 创建 Amazon RDS 实例。 | 在私有子网中创建和配置 Amazon RDS 实例。确保已启用**多可用区**以实现高可用性(HA)。 | 云管理员 | 
| 将数据载入 Amazon RDS 实例。 | 将应用程序所需关系数据加载到 Amazon RDS 实例中。此流程将根据应用程序的需求以及数据库架构的定义和设计方式而有所不同。 | 云管理员、数据库管理员 | 

### 创建 Amazon ECS 组件
<a name="create-the-amazon-ecs-components"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 ECS 集群。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 创建 Docker 映像  | 按照*相关资源*部分中的说明创建 Docker 映像。 | 云管理员 | 
| 创建 Amazon ECR 存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员、 DevOps 工程师 | 
| 对您的 Amazon ECR 注册表进行 Docker CLI 身份验证。 | 要对 Amazon ECR 存储库的 Docker 客户端进行身份验证，请在 AWS CLI 中运行 "`aws ecr get-login-password` 命令。 | 云管理员 | 
| 推送 Docker 映像至 Amazon ECR 存储库  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 创建 Amazon ECS 任务定义。 | 需要任务定义才能在 Amazon ECS 中运行 Docker 容器。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html)有关设置任务定义的帮助，请参阅*相关资源*部分中的“创建任务定义”。请务必提供您推送至 Amazon ECR 的 Docker 映像。 | 云管理员 | 
| 创建 Amazon ECS 服务  | 使用您之前创建的 ECS 集群创建 Amazon ECS 服务。确保选择 Amazon EC2 作为启动类型，然后选择在上一步中创建的任务定义以及 Application Load Balancer 的目标组。 | 云管理员 | 

### 创建 Amazon A EC2 uto Scaling 群组
<a name="create-an-amazon-ec2-auto-scaling-group"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建启动配置。 | 打开 Amazon EC2 控制台，然后创建启动配置。确保用户数据包含允许 EC2 实例加入所需的 ECS 集群的代码。有关所需代码的示例，请参阅*相关资源*部分。 | 云管理员 | 
| 创建 Amazon A EC2 uto Scaling 群组。 | 返回亚马逊 EC2 控制台，在 A **uto S** caling 下，选择 A **uto Scaling 群组**。设置一个 Amazon A EC2 uto Scaling 群组。请确保您选择了之前创建的私有子网和启动配置。 | 云管理员 | 

### 设置 AWS PrivateLink
<a name="set-up-aws-privatelink"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 AWS 终 PrivateLink 端节点。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html)有关更多信息，请参阅*相关资源*部分。 | 云管理员 | 

### 创建 VPC 端点
<a name="create-a-vpc-endpoint"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 VPC 端点。 | 为您之前创建的 AWS 终端 PrivateLink 节点创建 VPC 终端节点。VPC 终端节点完全限定域名 (FQDN) 将指向 AWS PrivateLink 终端节点 FQDN。这将创建一个 DNS 端点可以访问的 VPC 端点服务的弹性网络接口。 | 云管理员 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Lambda 函数。 | 在 AWS Lambda 控制台上，创建 Lambda 函数以将应用程序负载均衡器 IP 地址更新为网络负载均衡器的目标。有关这方面的更多信息，请参阅[使用 AWS Lambda 为应用程序负载均衡器启用静态 IP 地址](https://aws.amazon.com/blogs/networking-and-content-delivery/using-aws-lambda-to-enable-static-ip-addresses-for-application-load-balancers/)博客文章。 | 应用程序开发人员 | 

## 相关资源
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer-resources"></a>

**创建负载均衡器：**
+ [为 Amazon ECS 使用网络负载均衡器](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/nlb.html)
+ [创建网络负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/create-network-load-balancer.html)
+ [为 Amazon ECS 使用应用程序负载均衡器](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/alb.html)
+ [创建应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-application-load-balancer.html)

**创建 Amazon EFS 文件系统：**
+ [创建 Amazon EFS 文件系统](https://docs.aws.amazon.com/efs/latest/ug/creating-using-create-fs.html)
+ [在 Amazon EFS 中创建挂载目标](https://docs.aws.amazon.com/efs/latest/ug/accessing-fs.html)

**创建 S3 存储桶：**
+ [创建 S3 存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/GetStartedWithS3.html#creating-bucket)

**创建 Secrets Manager 密钥：**
+ [在 AWS KMS 中创建密钥](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html)
+ [在 AWS Secrets Manager 中创建密钥](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)

**创建 Amazon RDS 实例：**
+ [创建 Amazon RDS 数据库实例](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateDBInstance.html)

**创建 Amazon ECS 组件：**
+ [创建 Amazon ECS 集群 ](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-ec2-cluster-console-v2.html)
+ [创建 Docker 映像 ](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-container-image.html)
+ [创建 Amazon ECR 存储库 ](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)
+ [使用 Amazon ECR 存储库对 Docker 进行身份验证](https://docs.aws.amazon.com/AmazonECR/latest/userguide/Registries.html#registry_auth)
+ [将映像推送至 Amazon ECR 存储库](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)
+ [创建 Amazon ECS 任务定义](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)
+ [创建 Amazon ECS 服务](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-service-console-v2.html)

**创建 Amazon A EC2 uto Scaling 群组：**
+ [创建启动配置](https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-launch-config.html)
+ [使用启动配置创建自动扩缩组](https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-asg.html)
+ [使用亚马逊 EC2 用户数据引导容器实例](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/bootstrap_container_instance.html)

**设置 AWS PrivateLink：**
+ [VPC 终端节点服务 (AWS PrivateLink)](https://docs.aws.amazon.com/vpc/latest/privatelink/privatelink-share-your-services.html)

**创建 VPC 端点：**
+ [接口 VPC 终端节点 (AWS PrivateLink)](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html)

**创建 Lambda 函数：**
+ [创建 Lambda 函数](https://docs.aws.amazon.com/lambda/latest/dg/getting-started.html)

**其他资源：**
+ [为应用程序负载均衡器使用静态 IP 地址](https://aws.amazon.com/blogs/networking-and-content-delivery/using-static-ip-addresses-for-application-load-balancers/)
+ [通过 AWS 安全访问服务 PrivateLink](https://d1.awsstatic.com/whitepapers/aws-privatelink.pdf)

# 使用 AWS Fargate PrivateLink、AWS 和网络负载均衡器在 Amazon ECS 上私下访问容器应用程序
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer"></a>

*Kirankumar Chandrashekar，Amazon Web Services*

## Summary
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer-summary"></a>

此模式描述了如何使用带有 AWS Fargate 启动类型的亚马逊弹性容器服务 (Amazon ECS)，在网络负载均衡器后面，在亚马逊网络服务 (AWS) 云上私下托管 Docker 容器应用程序，并使用 AWS 访问该应用程序。 PrivateLinkAmazon Relational Database Service (Amazon RDS) 为在具有高可用性 (HA) 的 Amazon ECS 上运行的应用程序关系数据库提供托管。如果应用程序需要持久性存储，则您可以使用 Amazon Elastic File System (Amazon EFS)。

此模式对运行 Docker 应用程序的 Amazon ECS 服务使用 [Fargate 启动类型](https://docs.aws.amazon.com/AmazonECS/latest/userguide/launch_types.html)，并在前端使用网络负载均衡器。然后可以将其与虚拟私有云 (VPC) 终端节点关联，以便通过 AWS 进行访问 PrivateLink。然后，可以使用 VPC 终端节点与其他 VPCs 人共享此 VPC 终端节点服务。

您可以将 Fargate 与 Amazon ECS 配合使用来运行容器，而无需管理服务器或亚马逊弹性计算云 (Amazon EC2) 实例的集群。你也可以使用 Amazon A EC2 uto Scaling 群组来代替 Fargate。有关更多信息，请参阅[使用 AWS PrivateLink 和 Network Load Balancer 在 Amazon ECS 上私下访问容器应用程序](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.html?did=pg_card&trk=pg_card)。

## 先决条件和限制
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户
+ 已在 Linux、macOS 或 Windows 上安装并配置 [AWS 命令行界面（AWS CLI）版本 2](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ [Docker](https://www.docker.com/)，已在 Linux、macOS 或 Windows 上安装并配置
+ 在 Docker 上运行的应用程序

## 架构
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer-architecture"></a>

![\[PrivateLink 用于访问带有 AWS Fargate 启动类型的亚马逊 ECS 上的容器应用程序。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/31cca5e2-8d8b-45ec-b872-a06b0dd97007/images/57cc9995-45f4-4039-a0bf-2d2b3d6a05de.png)


**技术堆栈**
+ Amazon CloudWatch
+ Amazon Elastic Container Registry(Amazon ECR)
+ Amazon ECS
+ Amazon EFS
+ Amazon RDS
+ Amazon Simple Storage Service (Amazon S3)
+ AWS Fargate
+ AWS PrivateLink
+ AWS Secrets Manager
+ 应用程序负载均衡器
+ Network Load Balancer
+ VPC

**自动化和扩展**
+ 您可以使用 [AWS](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 通过使用[基础设施即代码 CloudFormation](https://docs.aws.amazon.com/whitepapers/latest/introduction-devops-aws/infrastructure-as-code.html)来创建此模式。

## 工具
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer-tools"></a>

**AWS 服务**
+ [Amazon Elastic Container Registry（Amazon ECR）](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)是一项安全、可靠且可扩展的 AWS 托管容器映像注册表服务。
+ [Amazon Elastic Container Service（Amazon ECS）](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html)是一项高度可扩展的快速容器管理服务，可帮助轻松运行、停止和管理集群上的容器。
+ [Amazon Elastic File System（Amazon EFS）](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html)可提供简单、可扩展、完全托管的弹性 NFS 文件系统，以便与 AWS 云服务和本地资源配合使用。
+ [AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html)是一种可以与 Amazon ECS 配合使用的技术，无需管理服务器或亚马逊 EC2 实例集群即可运行容器。
+ [Amazon Relational Database Service（Amazon RDS）](https://docs.aws.amazon.com/rds/index.html)是一项 Web 服务，让用户能够在 AWS 云云中更轻松地设置、操作和扩展关系数据库。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一种面向互联网的存储服务。该服务旨在降低开发人员进行网络规模级计算的难度。
+ [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/) 可帮助您将代码中的硬编码凭证（包括密码）替换为对 Secrets Manager 进行的 API 调用，以便以编程方式检索此密钥。
+ [Amazon Virtual Private Cloud（Amazon VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。
+ El@@ [astic Load Balancing (ELB)](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) 将传入的应用程序或网络流量分发到多个可用区域中的多个目标，例如 EC2 实例、容器和 IP 地址。

**其他工具**
+ [Docker](https://www.docker.com/) 帮助开发人员轻松地将任何应用程序作为轻量级、便携且自给自足的容器打包、运输和运行。

## 操作说明
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer-epics"></a>

### 创建联网组件
<a name="create-networking-components"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 VPC。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 

### 创建负载均衡器
<a name="create-the-load-balancers"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建网络负载均衡器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html)要获取有关此操作和其他操作的帮助，请参阅*相关资源*部分。 | 云管理员 | 
| 创建应用程序负载均衡器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 

### 创建 Amazon EFS 文件系统
<a name="create-an-amazon-efs-file-system"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon EFS 文件系统。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 子网的挂载目标。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 验证子网是否已挂载为目标。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 

### 创建 S3 存储桶
<a name="create-an-s3-bucket"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 S3 存储桶。 | 打开 Amazon S3 控制台并[创建一个 S3 存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/GetStartedWithS3.html#creating-bucket)，以在需要时存储应用程序的静态资产。 | 云管理员 | 

### 创建 Secrets Manager 密钥
<a name="create-a-secrets-manager-secret"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  创建 AWS KMS 密钥以加密 Secrets Manager 密钥。 | 打开 AWS Key Management Service (AWS KMS)控制台并创建 KMS 密钥。 | 云管理员 | 
|  创建 Secrets Manager 密钥以存储 Amazon RDS 密码。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 

### 创建 Amazon RDS 实例
<a name="create-an-amazon-rds-instance"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建数据库子网组。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 创建 Amazon RDS 实例。 | 在私有子网中创建和配置 Amazon RDS 实例。确保已启用**多可用区**以实现高可用性 (HA)。 | 云管理员 | 
| 将数据载入 Amazon RDS 实例。 | 将应用程序所需关系数据加载到 Amazon RDS 实例中。此流程将根据应用程序的需求以及数据库架构的定义和设计方式而有所不同。 | 数据库管理员 | 

### 创建 Amazon ECS 组件
<a name="create-the-amazon-ecs-components"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 ECS 集群。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 创建 Docker 映像 | 按照 [AWS 文档](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-container-image.html)中的说明创建 Docker 映像。 | 云管理员 | 
| 创建 Amazon ECR 存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员、 DevOps 工程师 | 
| 推送 Docker 映像至 Amazon ECR 存储库  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 
| 创建 Amazon ECS 任务定义。 | 需要任务定义才能在 Amazon ECS 中运行 Docker 容器。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html)有关设置任务定义的帮助，请参阅*相关资源*部分中的“创建任务定义”。请务必提供您推送至 Amazon ECR 的 Docker 映像。 | 云管理员 | 
| 创建 ECS 服务，然后选择 Fargate 作为启动类型。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 

### 设置 AWS PrivateLink
<a name="set-up-aws-privatelink"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 AWS 终 PrivateLink 端节点。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.html) | 云管理员 | 

### 创建 VPC 端点
<a name="create-a-vpc-endpoint"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 VPC 端点。 | 为您之前@@ [创建的 AWS 终端 PrivateLink 节点创建 VPC](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html) 终端节点。VPC 终端节点完全限定域名 (FQDN) 将指向 AWS PrivateLink 终端节点 FQDN。这会为 VPC 端点服务创建一个可供域名服务端点访问的弹性网络接口。 | 云管理员 | 

### 设置目标
<a name="set-the-target"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 添加应用程序负载均衡器作为目标。 | 要添加应用程序负载均衡器作为网络负载均衡器的目标，请遵循 [AWS 文档](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/application-load-balancer-target.html)中的说明进行操作。 | 应用程序开发人员 | 

## 相关资源
<a name="access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer-resources"></a>

**创建负载均衡器：**
+ [为 Amazon ECS 使用网络负载均衡器](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/nlb.html)
+ [创建网络负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/create-network-load-balancer.html)
+ [为 Amazon ECS 使用应用程序负载均衡器](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/alb.html)
+ [创建应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-application-load-balancer.html)

**创建 Amazon EFS 文件系统：**
+ [创建 Amazon EFS 文件系统](https://docs.aws.amazon.com/efs/latest/ug/creating-using-create-fs.html)
+ [在 Amazon EFS 中创建挂载目标](https://docs.aws.amazon.com/efs/latest/ug/accessing-fs.html)

**创建 Secrets Manager 密钥：**
+ [在 AWS KMS 中创建密钥](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html)
+ [在 AWS Secrets Manager 中创建密钥](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html)

**创建 Amazon RDS 实例：**
+ [创建 Amazon RDS 数据库实例](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateDBInstance.html)

**创建 Amazon ECS 组件**
+ [创建 Amazon ECR 存储库 ](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)
+ [使用 Amazon ECR 存储库对 Docker 进行身份验证](https://docs.aws.amazon.com/AmazonECR/latest/userguide/Registries.html#registry_auth)
+ [将映像推送至 Amazon ECR 存储库](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)
+ [创建 Amazon ECS 任务定义](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)
+ [创建 Amazon ECS 服务](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-service-console-v2.html)

**其他资源：**
+ [通过 AWS 安全访问服务 PrivateLink](https://d1.awsstatic.com/whitepapers/aws-privatelink.pdf)

# 使用 AWS PrivateLink 和 Network Load Balancer 在 Amazon EKS 上私密访问容器应用程序
<a name="access-container-applications-privately-on-amazon-eks-using-aws-privatelink-and-a-network-load-balancer"></a>

*Kirankumar Chandrashekar，Amazon Web Services*

## Summary
<a name="access-container-applications-privately-on-amazon-eks-using-aws-privatelink-and-a-network-load-balancer-summary"></a>

此模式描述了如何在网络负载均衡器后面的亚马逊 Elastic Kubernetes Service（Amazon EKS）上私下托管 Docker 容器应用程序，以及如何使用 AWS 访问该应用程序。 PrivateLink然后，您便可以使用专用网络安全地访问 Amazon Web Services (AWS) Cloud 上的服务。 

运行 Docker 应用程序的 Amazon EKS 集群在前端装有 Network Load Balancer，可以与虚拟私有云 (VPC) 终端节点关联，以便通过 AWS PrivateLink 进行访问。然后，可以使用 VPC 终端节点与其他 VPCs 人共享此 VPC 终端节点服务。

此模式描述的设置是在 VPCs 和 AWS 账户之间共享应用程序访问权限的安全方式。它不需要特殊的连接或路由配置，因为使用者和提供商账户之间的连接位于全球 AWS 主干网上，不会遍历公共互联网。

## 先决条件和限制
<a name="access-container-applications-privately-on-amazon-eks-using-aws-privatelink-and-a-network-load-balancer-prereqs"></a>

**先决条件**
+ [Docker](https://www.docker.com/)，已在 Linux、macOS 或 Windows 上安装并配置。
+ 在 Docker 上运行的应用程序。
+ 一个活跃的 AWS 账户。
+ [AWS 命令行界面（AWS CLI）版本 2](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)，已在 Linux、macOS 或 Windows 上安装并配置。
+ 具有标记的私有子网并配置为托管应用程序的现有 Amazon EKS 集群。有关更多信息，请参阅 Amazon EKS 文档中的[子网标记](https://docs.aws.amazon.com/eks/latest/userguide/network_reqs.html#vpc-subnet-tagging)。 
+ Kubectl，已安装并配置为访问 Amazon EKS 集群上的资源。有关更多信息，请参阅 Amazon EKS 文档中的[安装 kubectl ](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)。 

## 架构
<a name="access-container-applications-privately-on-amazon-eks-using-aws-privatelink-and-a-network-load-balancer-architecture"></a>

![\[使用 PrivateLink 和 Network Load Balancer 访问 Amazon EKS 容器中的应用程序。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/ce977924-012c-4fb6-8e51-94d6e5c829a6/images/378456a3-f4d1-4a57-bb36-879c240cabfb.png)


**技术堆栈**
+ Amazon EKS
+ AWS PrivateLink
+ Network Load Balancer

**自动化和扩展**
+ Kubernetes 清单可以在基于 Git 的存储库上进行跟踪和管理，也可以使用 AWS 中的持续集成和持续交付 (CI/CD) 进行部署。 CodePipeline 
+ 您可以使用 AWS CloudFormation 通过使用基础设施即代码 (IaC) 来创建此模式。

## 工具
<a name="access-container-applications-privately-on-amazon-eks-using-aws-privatelink-and-a-network-load-balancer-tools"></a>
+ [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) - AWS 命令行界面（AWS CLI）是一种开源工具，它使您能够使用命令行 Shell 中的命令与 Amazon Web Services 交互。
+ [Elastic L](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) oad Balancing — Elastic Load Balancing 将传入的应用程序或网络流量分配到一个或多个可用区的多个目标，例如亚马逊弹性计算云 (Amazon EC2) 实例、容器和 IP 地址。
+ [Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) – Amazon Elastic Kubernetes Service (Amazon EKS) 是一项托管服务，可让您在 AWS 上轻松运行 Kubernetes，而无需安装、操作和维护您自己的 Kubernetes 控制面板或节点。
+ [Amazon VPC](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) - Amazon Virtual Private Cloud (Amazon VPC)可助您将 AWS 资源启动到您已定义的虚拟网络中。
+ [Kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) - Kubectl 是一个命令行实用程序，用于对 Kubernetes 集群运行命令。

## 操作说明
<a name="access-container-applications-privately-on-amazon-eks-using-aws-privatelink-and-a-network-load-balancer-epics"></a>

### 部署 Kubernetes 部署和服务清单文件
<a name="deploy-the-kubernetes-deployment-and-service-manifest-files"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  创建 Kubernetes 部署清单文件。 | 根据您的要求修改以下示例文件，以创建部署清单文件。<pre>apiVersion: apps/v1<br />kind: Deployment<br />metadata:<br />  name: sample-app<br />spec:<br />  replicas: 3<br />  selector:<br />    matchLabels:<br />      app: nginx<br />  template:<br />    metadata:<br />      labels:<br />        app: nginx<br />    spec:<br />      containers:<br />        - name: nginx<br />          image: public.ecr.aws/z9d2n7e1/nginx:1.19.5<br />          ports:<br />            - name: http<br />              containerPort: 80</pre>这是使用 NGINX Docker 映像部署的 NGINX 示例配置文件。有关更多信息，请参阅 Docker 文档中的[如何使用官方 NGINX Docker 映像](https://www.docker.com/blog/how-to-use-the-official-nginx-docker-image/)。 | DevOps 工程师 | 
| 部署 Kubernetes 部署清单文件。 | 运行以下命令，将部署清单文件应用于 Amazon EKS 集群：`kubectl apply –f <your_deployment_file_name> ` | DevOps 工程师 | 
|  创建 Kubernetes 服务清单文件。 | 根据您的要求修改以下示例文件，创建服务清单文件。<pre>apiVersion: v1<br />kind: Service<br />metadata:<br />  name: sample-service<br />  annotations:<br />    service.beta.kubernetes.io/aws-load-balancer-type: nlb<br />    service.beta.kubernetes.io/aws-load-balancer-internal: "true"<br />spec:<br />  ports:<br />    - port: 80<br />      targetPort: 80<br />      protocol: TCP<br />  type: LoadBalancer<br />  selector:<br />    app: nginx</pre>请确保包含以下 `annotations` 以定义内部网络负载均衡器：<pre>service.beta.kubernetes.io/aws-load-balancer-type: nlb<br />service.beta.kubernetes.io/aws-load-balancer-internal: "true"</pre> | DevOps 工程师 | 
| 部署 Kubernetes 服务清单文件。 | 运行以下命令以将服务清单文件应用于 Amazon EKS 集群：`kubectl apply -f <your_service_file_name>` | DevOps 工程师 | 

### 创建端点
<a name="create-the-endpoints"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 记录网络负载均衡器的名称。 | 运行以下命令来检索网络负载均衡器的名称：`kubectl get svc sample-service -o wide`记录网络负载均衡器的名称，这是创建 AWS PrivateLink 终端节点所必需的。 | DevOps 工程师 | 
| 创建 AWS PrivateLink 终端节点。 | 登录 AWS 管理控制台，打开 Amazon VPC 控制台，然后创建 AWS PrivateLink 终端节点。将此端点与网络负载均衡器相关联，这使得应用程序可供客户私下使用。有关更多信息，请参阅 Amazon [VPC 文档中的 VPC 终端节点服务 (AWS PrivateLink)](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-service.html)。如果使用者账户需要访问应用程序，则必须将使用者账户的 [AWS 账户 ID](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html) 添加到 AWS PrivateLink 终端节点配置的允许委托人列表中。有关更多信息，请参阅 Amazon VPC 文档中的[添加和删除端点服务的权限](https://docs.aws.amazon.com/vpc/latest/userguide/add-endpoint-service-permissions.html)。 | 云管理员  | 
| 创建 VPC 端点。 | 在 **Amazon VPC 控制台**中，选择**端点服务**，然后选择您的端点服务。为 AWS 终端节点创建 VPC PrivateLink 终端节点。VPC 终端节点的完全限定域名 (FQDN) 指向 AWS PrivateLink 终端节点的 FQDN。这将创建一个 DNS 端点可以访问的 VPC 端点服务的弹性网络接口。  | 云管理员 | 

## 相关资源
<a name="access-container-applications-privately-on-amazon-eks-using-aws-privatelink-and-a-network-load-balancer-resources"></a>
+ [使用官方 NGINX Docker 映像](https://www.docker.com/blog/how-to-use-the-official-nginx-docker-image/)
+ [Amazon EKS 上的网络负载均衡](https://docs.aws.amazon.com/eks/latest/userguide/load-balancing.html) 
+ [创建 VPC 终端节点服务 (AWS PrivateLink)](https://docs.aws.amazon.com/vpc/latest/userguide/endpoint-service.html) 
+ [为您的端点服务添加和删除权限](https://docs.aws.amazon.com/vpc/latest/userguide/add-endpoint-service-permissions.html)

# 使用 AWS Batch 自动备份 Amazon RDS for PostgreSQL 数据库实例
<a name="automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch"></a>

*Kirankumar Chandrashekar，Amazon Web Services*

## Summary
<a name="automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch-summary"></a>

备份 PostgreSQL 数据库是一项重要的任务，通常可以使用 [pg\$1dump utility](https://www.postgresql.org/docs/current/app-pgdump.html) 完成，该实用程序默认使用 COPY 命令创建 PostgreSQL 数据库的架构和数据转储。但是，如果您需要定期备份多个 PostgreSQL 数据库，则此进程可能会变得重复。如果您的 PostgreSQL 数据库托管在云端，您也可以利用Amazon Relational Database Service (Amazon RDS) 为 PostgreSQL 提供的[自动备份](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_WorkingWithAutomatedBackups.html)功能。此示例介绍了如何使用 pg\$1dump 实用程序自动执行适用于 Amazon RDS for PostgreSQL 数据库实例的定期备份。

注意：这些说明假定您使用的是 Amazon RDS。但是，您也可以对托管在 Amazon RDS 外部的 PostgreSQL 数据库采用这种方法。若要进行备份，AWS Lambda 函数必须能访问您的数据库。

基于时间的亚马逊 CloudWatch 事件会启动 Lambda 函数，该函数搜索[应用于 Amazon RDS 上 PostgreSQL 数据库实例元数据的特定备份标签](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Tagging.html)。如果 **DBDump PostgreSQL 数据库实例具有 bkp: Automated =** Active 标签和其他必需的备份标签，则 Lambda 函数将每个数据库备份的单个任务提交到 AWS Batch。 

AWS Batch 会处理这些任务，并将备份数据上至到 Amazon Simple Storage Service（Amazon S3）存储桶。此模式使用 Dockerfile 和 entrypoint.sh 文件构建 Docker 容器映像，该映像用于在 AWS Batch 作业中进行备份。备份过程完成后，AWS Batch 会将备份详细信息记录至 Amazon DynamoDB 的库存表。作为一项额外的保护措施，如果任务在 AWS Batch 中失败， CloudWatch 事件事件会启动亚马逊简单通知服务 (Amazon SNS) Simple Notification Service 通知。 

## 先决条件和限制
<a name="automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 现有托管或非托管计算环境。有关更多信息，请参阅 AWS Batch 文档中的[托管和非托管计算环境](https://docs.aws.amazon.com/batch/latest/userguide/compute_environments.html)。 
+ [AWS 命令行界面（CLI）版本 2 Docker 映像](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-docker.html)，已安装并配置。
+ 现有的 Amazon RDS for PostgreSQL 数据库实例。 
+ 现有的 S3 存储桶。 
+ [Docker](https://www.docker.com/)，已在 Linux、macOS 或 Windows 上安装并配置。
+ 熟悉 Lambda 编码。 

## 架构
<a name="automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch-architecture"></a>

![\[使用 pg_dump 实用程序备份 Amazon RDS for PostgreSQL 数据库实例的架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/3283f739-980b-43d4-aca0-9d77a2ce3b85/images/352e2eab-1b7d-44ec-840a-a772a175e873.png)


 

**技术堆栈**
+ 亚马逊 CloudWatch 活动
+ Amazon DynamoDB
+ Amazon Elastic Container Registry (Amazon ECR)
+ Amazon RDS
+ Amazon SNS
+ Amazon S3
+ AWS Batch
+ AWS Key Management Service（AWS KMS）
+ AWS Lambda
+ AWS Secrets Manager
+ Docker

## 工具
<a name="automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch-tools"></a>
+ [Amazon CloudWatch ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) Ev CloudWatch ents — Events 提供近乎实时的系统事件流，这些事件描述了 AWS 资源的变化。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) - DynamoDB 是一种全托管 NoSQL 数据库服务，提供快速而可预测的性能，能够实现无缝扩展。
+ [Amazon ECR](https://docs.aws.amazon.com/ecr/index.html) - Amazon Elastic Container Registry (Amazon ECR) 是一项安全、可靠且可扩展的 AWS 托管容器映像注册表服务。
+ [Amazon RDS](https://docs.aws.amazon.com/rds/index.html) - Amazon Relational Database Service (Amazon RDS) 是一项 Web 服务，让用户能够在 Amazon Web Services Cloud 中轻松设置、操作和扩展关系数据库。
+ [Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) - Amazon Simple Notification Service（Amazon SNS）是一项托管服务，提供从发布者至订阅用户的消息传输。
+ [Amazon S3](https://docs.aws.amazon.com/s3/index.html) – Amazon Simple Storage Service (Amazon S3) 是一项面向互联网的存储服务。
+ [AWS Batch](https://docs.aws.amazon.com/batch/index.html) – AWS Batch 可帮助您在 AWS Cloud上运行批量计算工作负载。
+ [AWS KMS](https://docs.aws.amazon.com/kms/index.html) - AWS Key Management Service（AWS KMS）是一项托管服务，可让您轻松创建和控制加密您的数据所用的加密密钥。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/index.html) – AWS Lambda 是一项计算服务，可使您无需预置或管理服务器即可运行代码。
+ [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/index.html) - Secrets Manager 帮助您将代码中的硬编码凭证（包括密码）替换为对 Secrets Manager 的 API 调用，以便以编程方式检索密钥。
+ [Docker](https://www.docker.com/) - Docker 有助于开发人员轻松打包、交付和运行任何应用程序，将其作为轻量级、便携且自给自足的容器。

您在 Amazon RDS 上的 PostgreSQL 数据库实例必须[为其元数据应用标签](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Tagging.html)。Lambda 函数搜索标签以识别应备份的数据库实例，这通常使用以下标签。


| 
| 
| Tag | 说明 | 
| --- |--- |
| BKP: 自动 = 激活 DBDump  | 将 Amazon RDS 数据库实例标识为备份候选实例。 | 
| bkp: = AutomatedBackupSecret <secret\$1name > | 标识 Secrets Manager 密钥，其中包含 Amazon RDS 登录凭证。 | 
| bkp: 自动 S3Bucket = DBDump <s3\$1bucket\$1name> | 标识要向其发送备份的目标 S3 存储桶。 | 
| bkpDBDump: 自动频率bkpDBDump: 自动时间 | 确定数据库备份的频率和时间。  | 
| bkp:pgdumpcommand = <pgdump\$1command> | 标识需要对其执行备份的数据库。 | 

## 操作说明
<a name="automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch-epics"></a>

### 在 DynamoDB 中创建清单表
<a name="create-an-inventory-table-in-dynamodb"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 DynamoDB 中创建表。 | 登录 AWS 管理控制台，打开 Amazon DynamoDB 控制台，然后创建表。要获取有关此操作和其他操作的帮助，请参阅*相关资源*部分。 | 云管理员、数据库管理员 | 
| 确认已创建表格。 | 运行 `aws dynamodb describe-table --table-name <table-name> \| grep TableStatus`命令。如果该表存在，则该命令将返回 `"TableStatus": "ACTIVE",` 结果。 | 云管理员、数据库管理员 | 

### 在 AWS Batch 中为失败作业事件创建 SNS 主题
<a name="create-an-sns-topic-for-failed-job-events-in-aws-batch"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个 SNS 主题。 | 打开 Amazon SNS 控制台，选择**主题**，然后创建名为 `JobFailedAlert` 的 SNS 主题。以有效电子邮箱地址订阅此主题，并查看您的电子邮件收件箱以确认来自 AWS Notifications 的 SNS 订阅电子邮件。 | 云管理员 | 
| 为 AWS Batch 创建失败作业事件规则。 | 打开 Amazon CloudWatch 控制台，选择**事件**，然后选择**创建规则**。选择**显示高级选项**，并选择**编辑**。对于**构建模式，选择按您的目标处理的事件**，将现有文本替换为*其他信息*部分的“失败作业事件”代码。此代码定义了在 A CloudWatch WS Batch 有`Failed`事件时启动的事件规则。 | 云管理员 | 
| 添加事件规则目标。 | 在**目标**中，选择**添加目标**，然后选择 `JobFailedAlert` SNS 主题。配置其余详细信息，并创建 Cloudwatch Events 规则。 | 云管理员 | 

### 推送 Docker 映像到 Amazon ECR 存储库
<a name="build-a-docker-image-and-push-it-to-an-amazon-ecr-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon ECR 存储库。 | 打开 Amazon ECR 控制台，选择要在其中创建存储库的 AWS 区域。选择**存储库**，然后选择**创建存储库**。根据要求配置存储库。 | 云管理员 | 
| 撰写 Dockerfile。 | 登录 Docker，使用*其他信息*部分中的“示例 Dockerfile”和“示例 entrypoint.sh 文件”构建 Dockerfile。 | DevOps 工程师 | 
| 创建 Docker 映像并将其推送到 Amazon ECR 存储库。 | 将 Dockerfile 构建至 Docker 映像，并将其推送至 Amazon ECR 存储库。有关此步骤的帮助，请参阅*相关资源*部分。 | DevOps 工程师 | 

### 创建 AWS Batch 组件
<a name="create-the-aws-batch-components"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 AWS Batch 作业定义。 | 打开 AWS Batch 控制台，创建作业定义，其将 Amazon ECR 存储库的 Uniform Resource Identifier (URI) 包含为 `Image` 属性。 | 云管理员 | 
| 配置 AWS Batch 作业队列。 | 在 AWS Batch 控制台，选择**作业队列**，然后选择**创建队列**。创建作业存储队列，直至 AWS Batch 在您的计算环境资源中运行这些任务。重要提示：请务必为 AWS Batch 编写逻辑，以将备份详细信息记录至 DynamoDB 清单表。 | 云管理员 | 

### 创建并计划 Lambda 函数
<a name="create-and-schedule-a-lambda-function"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Lambda 函数以搜索标签。 | 创建 Lambda 函数，用于在您的 PostgreSQL 数据库实例上搜索标签并识别备用备份。确保您的 Lambda 函数可以识别 `bkp:AutomatedDBDump = Active` 标签和所有其他必需的标签。重要提示：Lambda 函数还必须能够将任务添加至 AWS Batch 作业队列中。 | DevOps 工程师 | 
| 创建基于时间 CloudWatch 的事件事件。 | 打开 Amazon CloudWatch 控制台并创建一个 CloudWatch 事件事件，该事件使用 cron 表达式定期运行您的 Lambda 函数。重要提示：所有计划的事件都使用 UTC 时区。 | 云管理员 | 

### 测试备份自动化
<a name="test-the-backup-automation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon KMS 密钥。 | 打开 Amazon KMS 控制台并创建 KMS 密钥，该密钥可用于加密存储在 AWS Secrets Manager 中的 Amazon RDS 证书。 | 云管理员 | 
| 创建 AWS Secrets Manager 密钥。 | 打开 AWS Secrets Manager 控制台，将您的 Amazon RDS for PostgreSQL 数据库证书存储为机密。 | 云管理员 | 
| 向 PostgreSQL 数据库实例添加所需标签。 | 打开 Amazon RDS 控制台，为要自动备份的 PostgreSQL 数据库实例添加标签。您可以使用*工具*部分表格中的标签。如果您需要从同一 Amazon RDS 实例中的多个 PostgreSQL 数据库进行备份，请使用 `-d test:-d test1` 作为 `bkp:pgdumpcommand` 标签值。`test` 和 `test1` 是数据库名称。确保冒号 (:) 后没有空格。 | 云管理员 | 
| 验证备份自动化。 | 若要验证备份自动化，您可以调用 Lambda 函数或等待备份计划开始。备份过程完成后，请检查 DynamoDB 清单表中是否包含适用于 PostgreSQL 数据库实例的有效备份条目。如果其匹配，则表示备份自动化过程成功。 | 云管理员 | 

## 相关资源
<a name="automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch-resources"></a>

**在 DynamoDB 中创建清单表**
+ [创建 Amazon DynamoDB 表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html)

 

**在 AWS Batch 中为失败作业事件创建 SNS 主题**
+ [创建 Amazon SNS 主题](https://docs.aws.amazon.com/sns/latest/dg/sns-tutorial-create-topic.html)
+ [在 AWS Batch 中针对失败作业事件发送 SNS 提醒](https://docs.aws.amazon.com/batch/latest/userguide/batch_sns_tutorial.html)

 

**推送 Docker 映像到 Amazon ECR 存储库**
+ [创建 Amazon ECR 存储库](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)    
+ [编写 Dockerfile，创建 Docker 映像，然后将其推送至 Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/getting-started-cli.html)

 

**创建 AWS Batch 组件**
+ [创建 AWS Batch 作业定义](https://docs.aws.amazon.com/batch/latest/userguide/Batch_GetStarted.html#first-run-step-1)    
+ [配置您的计算环境和 AWS Batch 作业队列](https://docs.aws.amazon.com/batch/latest/userguide/Batch_GetStarted.html#first-run-step-2)   
+ [在 AWS Batch 中创建作业队列](https://docs.aws.amazon.com/batch/latest/userguide/create-job-queue.html)

 

**创建 Lambda 函数**
+ [创建 Lambda 函数和编写代码](https://docs.aws.amazon.com/lambda/latest/dg/getting-started-create-function.html)
+ [将 Lambda 与 DynamoDB 共同使用](https://docs.aws.amazon.com/lambda/latest/dg/with-ddb.html)

 

**创建 CloudWatch 活动事件**
+ [创建基于时间 CloudWatch 的事件事件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/Create-CloudWatch-Events-Scheduled-Rule.html)   
+ [在 Cloudwatch 事件中采用 cron 表达式](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html)

 

**测试备份自动化**
+ [创建 Amazon KMS 密钥](https://docs.aws.amazon.com/kms/latest/developerguide/create-keys.html)    
+ [创建 Secrets Manager 密钥](https://docs.aws.amazon.com/secretsmanager/latest/userguide/tutorials_basic.html)
+ [为 Amazon RDS 实例添加标签](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Tagging.html)

## 附加信息
<a name="automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch-additional"></a>

**失败作业事件：**

```
{
  "detail-type": [
    "Batch Job State Change"
  ],
  "source": [
    "aws.batch"
  ],
  "detail": {
    "status": [
      "FAILED"
    ]
  }
}
```

**示例 Dockerfile：**

```
FROM alpine:latest
RUN apk --update add py-pip postgresql-client jq bash && \
pip install awscli && \
rm -rf /var/cache/apk/*
ADD entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
```

**entrypoint.sh 文件示例：**

```
 #!/bin/bash
set -e
DATETIME=`date +"%Y-%m-%d_%H_%M"`
FILENAME=RDS_PostGres_dump_${RDS_INSTANCE_NAME}
FILE=${FILENAME}_${DATETIME}

aws configure --profile new-profile set role_arn arn:aws:iam::${TargetAccountId}:role/${TargetAccountRoleName}
aws configure --profile new-profile set credential_source EcsContainer

echo "Central Account access provider IAM role is: "
aws sts get-caller-identity

echo "Target Customer Account access provider IAM role is: "
aws sts get-caller-identity --profile new-profile

securestring=$(aws secretsmanager get-secret-value --secret-id $SECRETID --output json --query 'SecretString' --region=$REGION --profile new-profile)

if [[ ${securestring} ]]; then
    echo "successfully accessed secrets manager and got the credentials"
    export PGPASSWORD=$(echo $securestring | jq --raw-output | jq -r '.DB_PASSWORD')
    PGSQL_USER=$(echo $securestring | jq --raw-output | jq -r '.DB_USERNAME')
    echo "Executing pg_dump for the PostGres endpoint ${PGSQL_HOST}"
    # pg_dump -h $PGSQL_HOST -U $PGSQL_USER -n dms_sample | gzip -9 -c  | aws s3 cp - --region=$REGION  --profile new-profile s3://$BUCKET/$FILE
    # in="-n public:-n private"
    IFS=':' list=($EXECUTE_COMMAND);
    for command in "${list[@]}";
      do
        echo $command;
        pg_dump -h $PGSQL_HOST -U $PGSQL_USER ${command} | gzip -9 -c  | aws s3 cp - --region=$REGION --profile new-profile s3://${BUCKET}/${FILE}-${command}".sql.gz"
        echo $?;
        if  [[ $? -ne 0 ]]; then
            echo "Error occurred in database backup process. Exiting now....."
            exit 1
        else
            echo "Postgresql dump was successfully taken for the RDS endpoint ${PGSQL_HOST} and is uploaded to the following S3 location s3://${BUCKET}/${FILE}-${command}.sql.gz"
            #write the details into the inventory table in central account
            echo "Writing to DynamoDB inventory table"
            aws dynamodb put-item --table-name ${RDS_POSTGRES_DUMP_INVENTORY_TABLE} --region=$REGION --item '{ "accountId": { "S": "'"${TargetAccountId}"'" }, "dumpFileUrl": {"S": "'"s3://${BUCKET}/${FILE}-${command}.sql.gz"'" }, "DumpAvailableTime": {"S": "'"`date +"%Y-%m-%d::%H::%M::%S"` UTC"'"}}'
            echo $?
            if  [[ $? -ne 0 ]]; then
                echo "Error occurred while putting item to DynamoDb Inventory Table. Exiting now....."
                exit 1
            else
                echo "Successfully written to DynamoDb Inventory Table ${RDS_POSTGRES_DUMP_INVENTORY_TABLE}"
            fi
        fi
      done;
else
    echo "Something went wrong {$?}"
    exit 1
fi

exec "$@"
```

# 使用 CI/CD 管道在 Amazon EKS 中自动部署节点终止处理程序
<a name="automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline"></a>

*Sandip Gangapadhyay、Sandeep Gawande、Viyoma Sachdeva、Pragtideep Singh 和 John Vargas，Amazon Web Services*

## Summary
<a name="automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline-summary"></a>

**注意**： CodeCommit AWS 不再向新客户开放。AWS 的现有客户 CodeCommit 可以继续照常使用该服务。[了解详情](https://aws.amazon.com/blogs/devops/how-to-migrate-your-aws-codecommit-repository-to-another-git-provider/)

在亚马逊网络服务 (AWS) 云上，您可以使用开源项目 [AWS 节点终止处理程序](https://github.com/aws/aws-node-termination-handler)来优雅地处理 Kubernetes 中的亚马逊弹性计算云 (Amazon EC2) 实例关闭。AWS 节点终止处理程序有助于确保 Kubernetes 控制平面对可能导致您的 EC2 实例不可用的事件做出适当的响应。这些事件包括：
+ [EC2 实例定期维护](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/monitoring-instances-status-check_sched.html)
+ [Amazon EC2 竞价型实例中断](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-interruptions.html)
+ [自动扩缩组横向缩减](https://docs.aws.amazon.com/autoscaling/ec2/userguide/AutoScalingGroupLifecycle.html#as-lifecycle-scale-in)
+ [自动扩缩组在可用区域间再平衡](https://docs.aws.amazon.com/autoscaling/ec2/userguide/auto-scaling-benefits.html#AutoScalingBehavior.InstanceUsage)
+ EC2 通过 API 或 AWS 管理控制台终止实例

如果未处理事件，您的应用程序代码可能无法正常停止。恢复完全可用性也可能需要更长的时间，或者可能会意外地将工作安排到正在关闭的节点上。`aws-node-termination-handler`（NTH）可以在两种不同的模式下运行：实例元数据服务（IMDS）或队列处理器。有关这两种模式的更多信息，请参阅[自述文件](https://github.com/aws/aws-node-termination-handler#readme)。

这种模式使用 AWS CodeCommit，它通过持续集成和持续交付 (CI/CD) 管道使用队列处理器自动部署 NTH。

**注意**  
如果您使用的是 [EKS 托管节点组](https://docs.aws.amazon.com/eks/latest/userguide/managed-node-groups.html)，则不需要 `aws-node-termination-handler`。

## 先决条件和限制
<a name="automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 支持与 AWS 管理控制台 配合使用的 Web 浏览器。参阅[支持的浏览器列表](https://aws.amazon.com/premiumsupport/knowledge-center/browsers-management-console/)。
+ AWS Cloud Development Kit (AWS CDK) [已安装](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_install)。
+ `kubectl`，Kubernetes 命令行工具，[已安装](https://kubernetes.io/docs/tasks/tools/)。
+ `eksctl`，[安装了](https://docs.aws.amazon.com/eks/latest/userguide/eksctl.html)适用于 Amazon Elastic Kubernetes Service (Amazon EKS) 的 AWS 命令行界面（AWS CLI）。
+ 运行的 EKS 集群，版本 1.20 或以上。
+ 连接至 EKS 集群的自托管式节点组。运行以下命令创建具有自托管式节点组的Amazon EKS集群。

  ```
  eksctl create cluster --managed=false --region <region> --name <cluster_name>
  ```

  有关 `eksctl` 的更多信息，请参阅 [eksctl 文档](https://eksctl.io/usage/creating-and-managing-clusters/)。
+ 适用于您的集群的 AWS Identity and Access Management (IAM) OpenID Connect (OIDC) 提供程序。有关更多信息，请参阅[为您的集群创建 IAM OIDC 提供程序](https://docs.aws.amazon.com/eks/latest/userguide/enable-iam-roles-for-service-accounts.html)。

**限制**
+ 您必须使用支持 Amazon EKS 服务的 AWS 区域。

**产品版本**
+ Kubernetes 版本 1.20 或更高版本
+ `eksctl` 版本 0.107.0 或更高版本
+ AWS CDK 版本 2.27.0 或更高版本

## 架构
<a name="automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline-architecture"></a>

**目标技术堆栈**
+ 虚拟私有云（VPC）
+ EKS 集群
+ Amazon Simple Queue Service(Amazon SQS)
+ IAM
+ Kubernetes

**目标架构**** **

下图显示了节点终止开始时 end-to-end步骤的高级视图。

![\[具有自动扩缩组的 VPC、具有节点终止处理程序的 EKS 集群以及 SQS 队列。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/970dfb73-9526-4942-a974-e8eef6416596/images/9e0125ae-d55b-49dd-ae70-ccaedf03832a.png)


图中显示的工作流包含以下概要步骤：

1. 自动扩展 EC2 实例终止事件被发送到 SQS 队列。

1. NTH 容器组（pod）监控 SQS 队列中的新消息。

1. NTH 容器组（pod）收到新消息并执行以下操作：
   + 封锁节点，这样新的容器组（pod）就不会在该节点上运行。
   + 排空节点，以便撤出现有容器组（pod）
   + 向自动扩缩组发送生命周期挂钩信号，以便可以终止该节点。

**自动化和扩缩**
+ 代码由 AWS CDK 管理和部署，由 AWS CloudFormation 嵌套堆栈提供支持。
+ [Amazon EKS 控制面板](https://docs.aws.amazon.com/eks/latest/userguide/disaster-recovery-resiliency.html)跨多个可用区运行以确保高可用性。
+ 为了实现[自动扩缩](https://docs.aws.amazon.com/eks/latest/userguide/autoscaling.html)，Amazon EKS 支持 Kubernetes [集群自动扩缩程序](https://github.com/kubernetes/autoscaler/tree/master/cluster-autoscaler)和 [Karpenter](https://karpenter.sh/)。

## 工具
<a name="automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline-tools"></a>

**Amazon Web Services**
+ [AWS Cloud Development Kit（AWS CDK）](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一个软件开发框架，可帮助您在代码中定义并预调配 AWS 云基础设施。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管的构建服务，可帮助您编译源代码、运行单元测试和生成可随时部署的项目。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) 是一项版本控制服务，可帮助您私下存储和管理 Git 存储库，而无需管理自己的源代码控制系统。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可帮助您快速建模和配置软件发布的不同阶段，并自动执行持续发布软件变更所需的步骤。
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) 可帮助您在 AWS 上运行 Kubernetes，而无需安装或维护您自己的 Kubernetes 控制面板或节点。
+ [Amazon A EC2 uto Scaling](https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html) 可帮助您保持应用程序的可用性，并允许您根据自己定义的条件自动添加或删除亚马逊 EC2 实例。
+ [Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) 提供了一个安全、持久且可用的托管队列，它可帮助您集成和分离分布式软件系统与组件。

**其他工具**
+ [kubectl](https://kubernetes.io/docs/reference/kubectl/kubectl/) 是针对 Kubernetes 集群运行命令的Kubernetes命令行工具。您可使用 kubectl 部署应用程序、检查和管理集群资源以及查看日志。

**代码**

此模式的代码可在 GitHub .com 的[deploy-nth-to-eks](https://github.com/aws-samples/deploy-nth-to-eks)存储库中找到。代码库包含以下文件和文件夹。
+ `nth folder`— Helm 图表、值文件以及用于扫描和部署节点终止处理程序的 AWS CloudFormation 模板的脚本。
+ `config/config.json` — 应用程序的配置参数文件。此文件包含部署 CDK 所需所有参数。
+ `cdk` — AWS CDK 源代码。
+ `setup.sh`— 用于部署 AWS CDK 应用程序以创建所需 CI/CD 管道和其他所需资源的脚本。
+ `uninstall.sh` — 用于清理资源的脚本。

要使用示例代码，请按照*操作说明*部分中的说明执行操作。

## 最佳实践
<a name="automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline-best-practices"></a>

有关自动化 AWS Node Termination Handler 的最佳实践，请参见以下内容：
+ [EKS 最佳实践指南](https://aws.github.io/aws-eks-best-practices/)
+ [Node Termination Handler - 配置](https://github.com/aws/aws-node-termination-handler/tree/main/config/helm/aws-node-termination-handler)

## 操作说明
<a name="automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline-epics"></a>

### 设置您的环境
<a name="set-up-your-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要使用 SSH（Secure Shell）克隆存储库，请运行以下命令。<pre>git clone git@github.com:aws-samples/deploy-nth-to-eks.git</pre>要使用HTTPS克隆存储库，请运行以下命令。<pre>git clone https://github.com/aws-samples/deploy-nth-to-eks.git</pre>克隆存储库会创建一个名为 `deploy-nth-to-eks` 的文件夹。切换到该目录。<pre>cd deploy-nth-to-eks</pre> | 应用程序开发人员、AWS DevOps、 DevOps 工程师 | 
| 设置 kubeconfig 文件。 | 在您的终端设置您的 AWS 凭证，并确认您有权担任集群角色。您可使用以下示例代码。<pre>aws eks update-kubeconfig --name <Cluster_Name> --region <region>--role-arn <Role_ARN></pre> | AWS DevOps， DevOps 工程师，应用程序开发人员 | 

### 部署 CI/CD 管道
<a name="deploy-the-ci-cd-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置参数。 | 在 `config/config.json` 文件中，设置以下必需参数。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline.html) | 应用程序开发人员、AWS DevOps、 DevOps 工程师 | 
| 创建用于部署 NTH 的 CI/CD 管道。 | 运行setup.sh脚本。<pre>./setup.sh</pre>该脚本将部署 AWS CDK 应用程序，该应用程序将根据文件中的`config/config.json`用户输入参数使用示例代码、管道和 CodeBuild 项目创建 CodeCommit 存储库。该脚本在使用 sudo 命令安装 npm 软件包时将要求输入密码。 | 应用程序开发人员、AWS DevOps、 DevOps 工程师 | 
| 查看 CI/CD 管道。 | 打开 AWS 管理控制台，查看在堆栈中创建的以下资源。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline.html)管道成功运行后，Helm 版本 `aws-node-termination-handler` 将安装在 EKS 集群中。此外，名为 `aws-node-termination-handler` 的容器组（pod）正在集群的 `kube-system` 命名空间中运行。 | 应用程序开发人员、AWS DevOps、 DevOps 工程师 | 

### 测试NTH部署
<a name="test-nth-deployment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 模拟自动扩缩组横向缩减事件。 | 要模拟自动扩缩横向缩减事件，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline.html) |  | 
| 查看日志。 | 在缩容事件期间，第 N 个 Pod 将封锁并耗尽相应的工作节点（作为缩容事件的一部分终止的 EC2 实例）。要查看日志，请使用*其他信息*部分中的代码。 | 应用程序开发人员、AWS DevOps、 DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理全部 AWS 资源。 | 锐欧要清理此模式创建的资源，请运行以下命令。<pre>./uninstall.sh</pre>这将通过删除 CloudFormation 堆栈来清理在此模式中创建的所有资源。 | DevOps 工程师 | 

## 问题排查
<a name="automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| npm 注册表设置不正确。 | 在此解决方案的安装过程中，脚本会安装 npm install 以下载所有必需的软件包。如果在安装过程中看到找不到模块的消息，则可能无法正确设置 npm 注册表。要查看当前的注册表设置，请运行以下命令。<pre>npm config get registry</pre>运行以下命令以设置 `https://registry.npmjs.org/` 注册表。<pre>npm config set registry https://registry.npmjs.org</pre> | 
| 延迟 SQS 消息传送。 | 作为故障排除的一部分，如果您想延迟向 NTH 容器组（pod）传送 SQS 消息，可以调整 SQS 传送延迟参数。有关更多信息，请参阅 [Amazon SQS 延迟队列](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-delay-queues.html)。 | 

## 相关资源
<a name="automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline-resources"></a>
+ [AWS Node Termination Handler 源代码](https://github.com/aws/aws-node-termination-handler)
+ [EC2 工作坊](https://ec2spotworkshops.com/using_ec2_spot_instances_with_eks/070_selfmanagednodegroupswithspot/deployhandler.html)
+ [AWS CodePipeline](https://aws.amazon.com/codepipeline/)
+ [Amazon Elastic Kubernetes Service(Amazon EKS)](https://aws.amazon.com/eks/)
+ [AWS Cloud Development Kit](https://aws.amazon.com/cdk/)
+ [AWS CloudFormation](https://aws.amazon.com/cloudformation/)

## 附加信息
<a name="automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline-additional"></a>

1. 找到 NTH 容器组（pod）的名字。

```
kubectl get pods -n kube-system |grep aws-node-termination-handler
aws-node-termination-handler-65445555-kbqc7   1/1     Running   0          26m
kubectl get pods -n kube-system |grep aws-node-termination-handler
aws-node-termination-handler-65445555-kbqc7   1/1     Running   0          26m
```

2. 检查日志。日志示例如下所示。它表明在发送自动扩缩组生命周期挂钩完成信号之前，该节点已被封锁并耗尽。

```
kubectl -n kube-system logs aws-node-termination-handler-65445555-kbqc7
022/07/17 20:20:43 INF Adding new event to the event store event={"AutoScalingGroupName":"eksctl-my-cluster-target-nodegroup-ng-10d99c89-NodeGroup-ZME36IGAP7O1","Description":"ASG Lifecycle Termination event received. Instance will be interrupted at 2022-07-17 20:20:42.702 +0000 UTC \n","EndTime":"0001-01-01T00:00:00Z","EventID":"asg-lifecycle-term-33383831316538382d353564362d343332362d613931352d383430666165636334333564","InProgress":false,"InstanceID":"i-0409f2a9d3085b80e","IsManaged":true,"Kind":"SQS_TERMINATE","NodeLabels":null,"NodeName":"ip-192-168-75-60.us-east-2.compute.internal","NodeProcessed":false,"Pods":null,"ProviderID":"aws:///us-east-2c/i-0409f2a9d3085b80e","StartTime":"2022-07-17T20:20:42.702Z","State":""}
2022/07/17 20:20:44 INF Requesting instance drain event-id=asg-lifecycle-term-33383831316538382d353564362d343332362d613931352d383430666165636334333564 instance-id=i-0409f2a9d3085b80e kind=SQS_TERMINATE node-name=ip-192-168-75-60.us-east-2.compute.internal provider-id=aws:///us-east-2c/i-0409f2a9d3085b80e
2022/07/17 20:20:44 INF Pods on node node_name=ip-192-168-75-60.us-east-2.compute.internal pod_names=["aws-node-qchsw","aws-node-termination-handler-65445555-kbqc7","kube-proxy-mz5x5"]
2022/07/17 20:20:44 INF Draining the node
2022/07/17 20:20:44 ??? WARNING: ignoring DaemonSet-managed Pods: kube-system/aws-node-qchsw, kube-system/kube-proxy-mz5x5
2022/07/17 20:20:44 INF Node successfully cordoned and drained node_name=ip-192-168-75-60.us-east-2.compute.internal reason="ASG Lifecycle Termination event received. Instance will be interrupted at 2022-07-17 20:20:42.702 +0000 UTC \n"
2022/07/17 20:20:44 INF Completed ASG Lifecycle Hook (NTH-K8S-TERM-HOOK) for instance i-0409f2a9d3085b80e
```

# 使用 CI/CD 管道自动构建 Java 应用程序并将其部署到 Amazon EKS
<a name="automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline"></a>

*MAHESH RAGHUNANDANAN、Jomcy Pappachen 和 James Radtke，Amazon Web Services*

## Summary
<a name="automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline-summary"></a>

此模式描述了如何创建持续集成和持续交付 (CI/CD) 管道，该管道可根据推荐的 DevSecOps 做法自动构建并部署到上的 Amazon Elastic Kubernetes Service (Amazon EKS) 集群。 AWS 云此模式使用采用 Spring Boot Java 框架开发的问候应用程序，该应用程序使用 Apache Maven。

您可以使用这种模式的方法为 Java 应用程序构建代码，将应用程序构件打包为 Docker 映像，对映像进行安全扫描，然后将该映像作为工作负载容器上传到 Amazon EKS 上。如果您想从紧密耦合的单片架构迁移到微服务架构，则此模式的方法非常有用。该方法还可以帮助您监控和管理 Java 应用程序的整个生命周期，从而确保更高的自动化水平并有助于避免错误或程序错误。

## 先决条件和限制
<a name="automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ AWS Command Line Interface (AWS CLI) 版本 2，已安装并配置。有关这方面的更多信息，请参阅 AWS CLI 文档 AWS CLI中的[安装或更新到最新版本](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)的。

  AWS CLI 版本 2 必须使用与创建 Amazon EKS 集群的相同 AWS Identity and Access Management (IAM) 角色进行配置，因为只有该角色才有权向中添加其他 IAM 角色`aws-auth``ConfigMap`。有关配置的信息和步骤 AWS CLI，请参阅 AWS CLI 文档中的[配置设置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html)。
+ 具有完全访问权限的 IAM 角色和权限 AWS CloudFormation。有关这方面的更多信息，请参阅 CloudFormation 文档中的[使用 IAM 控制访问权限](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html)。
+ 现有的 Amazon EKS 集群，包含 EKS 集群中 Worker 节点的 IAM 角色名称和 IAM 角色 Amazon 资源名称（ARN）的详细信息。
+ Kubernetes 集群自动扩缩器，已在 Amazon EKS 集群中安装和配置。有关更多信息，请参阅 Amazon EKS 文档中的[使用 Karpenter 和 Cluster Autoscaler 扩展集群计算](https://docs.aws.amazon.com/eks/latest/userguide/cluster-autoscaler.html)。 
+ 访问 GitHub 存储库中的代码。

**重要**  
AWS Security Hub CSPM 已作为此模式代码中包含的 CloudFormation 模板的一部分启用。默认情况下，启用 Security Hub CSPM 后，它会提供 30 天的免费试用期。试用结束后，会产生与此 AWS 服务相关的费用。有关定价的更多信息，请参阅 [AWS Security Hub CSPM 定价](https://aws.amazon.com/security-hub/pricing/)。

**产品版本**
+ Helm 版本 3.4.2 或更高版本
+ Apache Maven 版本 3.6.3 或更高版本
+ BridgeCrew Checkov 版本 2.2 或更高版本
+ Aqua Security Trivy 版本 0.37 或更高版本

## 架构
<a name="automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline-architecture"></a>

**技术堆栈**
+ AWS CodeBuild
+ AWS CodeCommit
+ Amazon CodeGuru
+ AWS CodePipeline
+ Amazon Elastic Container Registry (Amazon ECR)
+ Amazon EKS
+ Amazon EventBridge
+ AWS Security Hub CSPM
+ Amazon Simple Notification Service（Amazon SNS）

**目标架构**

![\[将 Java 应用程序部署到 Amazon EKS 的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/95a5b5c2-d7fb-41eb-9089-455318c0d585/images/4f5fd8c2-2b6d-4945-aa64-fcf317521711.png)


下图显示了如下工作流：

1. 开发人员更新 CodeCommit 存储库基础分支中的 Java 应用程序代码，从而创建拉取请求 (PR)。

1. 提交 PR 后，Amazon CodeGuru Reviewer 会自动审查代码，根据 Java 的最佳实践对其进行分析，并向开发者提供建议。

1. PR 合并到基础分支后，将创建一个 Amazon EventBridge 事件。

1. 该 EventBridge 事件启动 CodePipeline 管道，管道启动。

1. CodePipeline 运行 CodeSecurity 扫描阶段（持续安全）。

1. AWS CodeBuild 启动安全扫描流程，在该流程中，使用 Checkov 扫描 Dockerfile 和 Kubernetes 部署 Helm 文件，并根据增量代码更改扫描应用程序源代码。应用程序源代码扫描由 [CodeGuru Reviewer 命令行界面 (CLI) 包装器](https://github.com/aws/aws-codeguru-cli)执行。
**注意**  
自 2025 年 11 月 7 日起，您无法在 Amazon CodeGuru Reviewer 中创建新的存储库关联。要了解具有类似审阅者功能的服务，请参阅 CodeGuru Reviewer 文档中的 [Amazon CodeGuru Reviewer 可用性变更](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/codeguru-reviewer-availability-change.html)。 CodeGuru 

1. 如果安全扫描阶段成功，则启动构建阶段（持续集成）。

1. 在构建阶段， CodeBuild 构建工件，将构件打包到 Docker 镜像，使用 Aqua Security Trivy 扫描映像中是否存在安全漏洞，然后将映像存储在 Amazon ECR 中。

1. 步骤 8 中检测到的漏洞将上传到 Security Hub CSPM，供开发人员或工程师进一步分析。Security Hub CSPM 提供了修复漏洞的概述和建议。

1.  CodePipeline 管道中连续阶段的电子邮件通知通过 Amazon SNS 发送。

1. 持续集成阶段完成后， CodePipeline 进入部署阶段（持续交付）。

1. 使用 Helm 图表将 Docker 映像作为容器工作负载（容器组（pod））部署到 Amazon EKS。

1. 应用程序容器使用 Amazon P CodeGuru rofiler 代理进行配置，该代理会将应用程序的分析数据（CPU、堆使用情况和延迟）发送到 P CodeGuru rofiler，从而帮助开发人员了解应用程序的行为。

## 工具
<a name="automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline-tools"></a>

**AWS 服务**
+ [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在资源的整个生命周期中跨地区对其 AWS 账户 进行管理。
+  [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管式构建服务，可编译源代码、运行单元测试和生成部署就绪的构件。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) 是一项版本控制服务，可帮助您私下存储和管理 Git 存储库，而无需管理自己的源代码控制系统。
+ [Amazon CodeGuru Profiler](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/what-is-codeguru-profiler.html) 会从您的实时应用程序收集运行时性能数据，并提供建议，以帮助您微调应用程序性能。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可帮助您快速对软件发布过程的不同阶段进行建模和配置，并自动执行持续发布软件变更所需步骤。
+ [Amazon Elastic Container Registry（Amazon ECR）](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)是一项安全、可扩展且可靠的托管容器映像注册表服务。
+ [亚马逊 Elastic Kubernetes Service（亚马逊](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一项无服务器事件总线服务，可帮助您将应用程序与来自各种来源的实时数据连接起来，包括 AWS Lambda 函数、使用 API 目标的 HTTP 调用终端节点或其他来源的事件总线。 AWS 账户
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [AWS Security Hub CSPM](https://docs.aws.amazon.com/securityhub/latest/userguide/what-is-securityhub.html)提供了您的安全状态的全面视图 AWS。它还可以帮助您根据安全行业标准和最佳实践检查您的 AWS 环境。
+ [Amazon Simple Notification Service（Amazon SNS）](https://docs.aws.amazon.com/sns/latest/dg/welcome.html)可帮助您协调和管理发布者与客户端（包括 Web 服务器和电子邮件地址）之间的消息交换。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**其他服务**
+ [Helm](https://helm.sh/docs/) 是 Kubernetes 的开源软件包管理器。
+ [Apache Maven](https://maven.apache.org/) 是一款软件项目管理及理解工具。
+ [BridgeCrew Checkov](https://www.checkov.io/1.Welcome/What%20is%20Checkov.html) 是一种静态代码分析工具，用于扫描基础设施即代码 (IaC) 文件，以查找可能导致安全性或合规性问题的错误配置。
+ [Aqua Security Trivy](https://github.com/aquasecurity/trivy) 是一款全面的扫描工具，可检测容器映像、文件系统和 Git 存储库中的漏洞以及配置问题。

**代码**

此模式的代码可在 GitHub [aws-codepipeline-devsecops-amazoneks](https://github.com/aws-samples/aws-codepipeline-devsecops-amazoneks)存储库中找到。

## 最佳实践
<a name="automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline-best-practices"></a>
+ 此模式遵循 [IAM 安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)，在解决方案的所有阶段都对 IAM 实体应用最低权限原则。如果您想使用其他工具 AWS 服务 或第三方工具扩展解决方案，我们建议您查看 IAM 文档中有关[应用最低权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)的部分。
+ 如果您有多个 Java 应用程序，我们建议您为每个应用程序创建单独的 CI/CD 管道。
+ 如果您使用的是单体应用程序，我们建议在可能的情况下将应用程序分解为微服务。微服务更加灵活，可以更轻松地将应用程序部署为容器，并且可以更好地了解应用程序的整体构建和部署。

## 操作说明
<a name="automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline-epics"></a>

### 设置环境
<a name="set-up-the-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆 GitHub 存储库。 | 要克隆存储库，请运行以下命令。<pre>git clone https://github.com/aws-samples/aws-codepipeline-devsecops-amazoneks</pre> | 应用程序开发者、 DevOps 工程师 | 
| 创建 S3 存储桶并上传代码。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.html) | AWS DevOps，云管理员， DevOps 工程师 | 
| 创建 CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.html) | AWS DevOps， DevOps 工程师 | 
| 验证 CloudFormation 堆栈部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.html) | AWS DevOps， DevOps 工程师 | 
| 删除 S3 存储桶。 | 清空并删除您之前创建的 S3 存储桶。有关更多信息，请参阅 Amazon S3 文档中的[删除存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/delete-bucket.html)。 | AWS DevOps， DevOps 工程师 | 

### 配置 Helm 图表
<a name="configure-the-helm-charts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置 Java 应用程序的 Helm 图表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.html) | DevOps 工程师 | 
| 验证 Helm 图表是否存在语法错误。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.html) | DevOps 工程师 | 

### 设置 Java CI/CD 管道
<a name="set-up-the-java-ci-cd-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 CI/CD 管道。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.html) | AWS DevOps | 

### 激活 Security Hub CSPM 和 Aqua Security 之间的集成
<a name="activate-integration-between-ash-and-aqua-security"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 打开 Aqua Security 集成。 | 要将 Trivy 报告的 Docker 镜像漏洞发现上传到 Security Hub CSPM，必须执行此步骤。由于 CloudFormation 不支持 Security Hub CSPM 集成，因此必须手动完成此过程。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.html) | AWS 管理员、 DevOps 工程师 | 

### 配置 CodeBuild 为运行 Helm 或 kubectl 命令
<a name="configure-acb-to-run-helm-or-kubectl-commands"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  CodeBuild 允许在 Amazon EKS 集群中运行 Helm 或 kubectl 命令。 |  CodeBuild 要通过身份验证才能在 Amazon EKS 集群中使用 Helm 或`kubectl`命令，您必须将 IAM 角色添加到`aws-auth``ConfigMap`。在本例中，添加 IAM 角色的 ARN`EksCodeBuildkubeRoleARN`，即为 CodeBuild 服务创建的 IAM 角色，用于访问 Amazon EKS 集群并在其上部署工作负载。这是一次性活动。在部署批准阶段之前，必须完成以下程序 CodePipeline。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.html)已配置 `aws_auth` `ConfigMap`，并授予访问权限。 | DevOps | 

### 验证 CI/CD 管道
<a name="validate-the-ci-cd-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证 CI/CD 管道是否自动启动。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.html)有关使用启动管道的更多信息 CodePipeline，请参阅 CodePipeline 文档[中的启动管](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-about-starting.html)[道CodePipeline、手动](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-rerun-manually.html)[启动管道和按计划](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-trigger-source-schedule.html)启动管道。 | DevOps | 
| 批准部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.html) | DevOps | 
| 验证应用程序分析。 | 部署完成并将应用程序容器部署在 Amazon EKS 中后，在应用程序中配置的 Amazon P CodeGuru rofiler 代理将尝试将应用程序的分析数据（CPU、堆摘要、延迟和瓶颈）发送到 CodeGuru Profiler。对于应用程序的初始部署， CodeGuru Profiler 大约需要 15 分钟来可视化分析数据。 | AWS DevOps | 

## 相关资源
<a name="automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline-resources"></a>
+ [AWS CodePipeline 文档](https://docs.aws.amazon.com/codepipeline/index.html)
+ 在 AWS CodePipeline（AWS 博客文章）[中使用 Trivy 扫描图像](https://aws.amazon.com/blogs/containers/scanning-images-with-trivy-in-an-aws-codepipeline/)
+ [使用 Amazon P CodeGuru rofiler 改进您的 Java 应用程序](https://aws.amazon.com/blogs/devops/improving-your-java-applications-using-amazon-codeguru-profiler)（AWS 博客文章）
+ [AWS 安全调查结果格式 (ASFF) 语法](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-findings-format-syntax.html)
+ [亚马逊 EventBridge 事件模式](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-patterns.html)
+ [Helm 升级](https://helm.sh/docs/helm/helm_upgrade/)

## 附加信息
<a name="automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline-additional"></a>
+ CodeGuru 在功能方面，不应将 Profiler 与 AWS X-Ray 服务混淆。我们建议您使用 CodeGuru Profiler 来识别可能导致瓶颈或安全问题的最昂贵的代码行，并在它们成为潜在风险之前对其进行修复。X-Ray 服务用于监控应用程序性能。
+ 在此模式中，事件规则与默认事件总线相关联。如果需要，您可以扩展模式以使用自定义事件总线。
+ 此模式使用 CodeGuru Reviewer 作为应用程序代码的静态应用程序安全测试 (SAST) 工具。您也可以将此管道用于其他工具，例如 SonarQube 或 Checkmarx。您可以添加其中任何工具的扫描设置说明`buildspec/buildspec_secscan.yaml`来替换 CodeGuru 扫描指令。
**注意**  
自 2025 年 11 月 7 日起，您无法在 Amazon CodeGuru Reviewer 中创建新的存储库关联。要了解具有类似审阅者功能的服务，请参阅 CodeGuru Reviewer 文档中的 [Amazon CodeGuru Reviewer 可用性变更](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/codeguru-reviewer-availability-change.html)。 CodeGuru 

# 将 Amazon ECR 容器镜像复制到各处 AWS 账户 AWS 区域
<a name="copy-ecr-container-images-across-accounts-regions"></a>

*Faisal Shahdad，Amazon Web Services*

## Summary
<a name="copy-ecr-container-images-across-accounts-regions-summary"></a>

此模式向您展示了如何使用无服务器方法将带标签的图像从现有的 Amazon Elastic Container Registry (Amazon ECR) 存储库复制到其他和。 AWS 账户 AWS 区域该解决方案 AWS Step Functions 用于管理复制工作流程和复制大型容器映像的 AWS Lambda 功能。

Amazon ECR 使用原生[跨区域](https://docs.aws.amazon.com/AmazonECR/latest/userguide/registry-settings-examples.html#registry-settings-examples-crr-single)和[跨账户](https://docs.aws.amazon.com/AmazonECR/latest/userguide/registry-settings-examples.html#registry-settings-examples-crossaccount)复制功能，可以跨区域和账户复制容器映像。但是这些功能只能从开启复制的那一刻起复制映像。目前没有机制能够将现有映像复制到不同区域和账户。

这种模式可以帮助人工智能 (AI) 团队向其他账户和区域分发容器化机器学习 (ML) 模型、框架（例如 PyTorch TensorFlow、和 Hugging Face）以及依赖关系。这可以帮助您克服服务限制并优化 GPU 计算资源。您也可以选择性地从特定来源账户和地区复制 Amazon ECR 存储库。有关更多信息，请参阅 [Amazon ECR 中的跨区域复制已实现](https://aws.amazon.com/blogs/containers/cross-region-replication-in-amazon-ecr-has-landed/)。

## 先决条件和限制
<a name="copy-ecr-container-images-across-accounts-regions-prereqs"></a>

**先决条件**
+ 两个或更多活跃账户 AWS 账户 （至少有一个源账户和一个目标账户）
+ 所有账户都有相应的 AWS Identity and Access Management (IAM) 权限
+ 用于构建 Lambda 容器映像的 Docker
+ AWS Command Line Interface (AWS CLI) 已为所有账户配置

**限制**
+ **未标记的映像排除-** 该解决方案仅复制具有显式标签的容器映像。它会跳过摘要中存在的未加标签的 `SHA256` 映像。
+ **Lambda 执行超时限制 — AWS Lambda 限制**为最长 15 分钟的执行超时，这可能不足以复制大型容器映像或存储库。
+ **手动管理容器映像 —** `crane-app.py` Python 代码需要重新构建和重新部署 Lambda 容器映像。
+ **并行处理容量有限 —** `MaxConcurrency` 状态设置限制了您可以同时复制的存储库数量。但是，您可以在来源账户的 AWS CloudFormation 模板中修改此设置。请注意，较高的并发值可能会导致您超过服务速率限制和账户级 Lambda 执行配额。

## 架构
<a name="copy-ecr-container-images-across-accounts-regions-architecture"></a>

**目标堆栈**

该模式有四个主要组成部分：
+ **源账户基础架构 —** 创建编排组件的 CloudFormation 模板
+ **目标账户基础设施-** 创建跨账户访问角色的 CloudFormation 模板
+ **Lambda 函数 —** 基于 Python 的函数，使用 Crane 进行高效的映像复制
+ **容器映像 – **将 Lambda 函数与所需工具打包在一起的 Docker 容器

**目标架构**

![\[alt text not found\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/787185e7-664b-4ed8-b30f-1d9507f13377/images/cc7d9823-3dc8-4090-a203-910b1ac4447c.png)


**Step Function 工作流**

Step Functions 状态机会编排以下内容，如下图所示：
+ `PopulateRepositoryList`**—** 扫描 Amazon ECR 存储库并填充 Amazon DynamoDB
+ `GetRepositoryList`**—** 从 DynamoDB 检索唯一的存储库列表
+ `DeduplicateRepositories`**—** 确保没有重复处理
+ `CopyRepositories`**—** 处理存储库的并行复制
+ `NotifySuccess`/`NotifyFailure`** –** 基于执行结果的 Amazon Simple Notification Service（Amazon SNS）通知

![\[alt text not found\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/787185e7-664b-4ed8-b30f-1d9507f13377/images/1b740084-ba2b-4956-aa12-ebbf52be5e7d.png)


## 工具
<a name="copy-ecr-container-images-across-accounts-regions-tools"></a>

**Amazon 工具**
+ [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 数据库服务，可提供快速、可预测、可扩展的性能。
+ [Amazon Simple Notification Service（Amazon SNS）](https://docs.aws.amazon.com/sns/latest/dg/welcome.html)可帮助您协调和管理发布者与客户端（包括 Web 服务器和电子邮件地址）之间的消息交换。
+ [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 Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)是一项无服务器编排服务，可帮助您组合 Lambda 函数和其他函数 AWS 服务 来构建业务关键型应用程序。

**其他工具**
+ [Crane](https://michaelsauter.github.io/crane/index.html) 是一款 Docker 编排工具。它与 Docker Compose 类似，但还有其他功能。
+ [Docker](https://www.docker.com/) 是一组平台即服务（PaaS）产品，它们使用操作系统级别的虚拟化技术在容器中交付软件。

**代码存储库**
+ 此模式的代码可在 GitHub [sample-ecr-copy 存储库](https://github.com/aws-samples/sample-ecr-copy)中找到。您可以使用存储库中的 CloudFormation 模板来创建底层资源。

## 最佳实践
<a name="copy-ecr-container-images-across-accounts-regions-best-practices"></a>

遵循最低权限原则，并授予执行任务所需的最低权限。有关详情，请参阅 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="copy-ecr-container-images-across-accounts-regions-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置 AWS CLI 配置文件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | DevOps 工程师、数据工程师、机器学习工程师 | 
| 收集所需信息。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | DevOps 工程师、数据工程师、机器学习工程师 | 
| 克隆存储库。 | 将项目的 存储库克隆到本地工作站。<pre>git clone https://github.com/aws-samples/sample-ecr-copy</pre> | DevOps 工程师、数据工程师、机器学习工程师 | 

### 为目标账户部署基础设施
<a name="deploy-infrastructure-for-the-destination-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证模版。 | 验证 CloudFormation 模板：<pre>aws cloudformation validate-template \<br />  --template-body file://"Destination Account cf_template.yml" \<br />  --profile destination-account</pre> | DevOps 工程师、机器学习工程师、数据工程师 | 
| 部署目标基础设施。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | 数据工程师、机器学习工程师、 DevOps 工程师 | 
| 验证部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | DevOps 工程师、机器学习工程师、数据工程师 | 

### 构建和部署 Lambda 容器映像
<a name="build-and-deploy-the-lam-container-image"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 准备容器构建。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | 数据工程师、机器学习工程师、 DevOps 工程师 | 
| 构建容器映像。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | 数据工程师、机器学习工程师、 DevOps 工程师 | 
| 创建存储库并上传映像。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | 数据工程师、机器学习工程师、 DevOps 工程师 | 
| Verify the image. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | 数据工程师、机器学习工程师、 DevOps 工程师 | 

### 部署源账户基础设施
<a name="deploy-the-source-account-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 准备部署参数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | 数据工程师、 DevOps 工程师、机器学习工程师 | 
| 验证源模版。 | 验证源 CloudFormation 模板：<pre>aws cloudformation validate-template \<br />  --template-body file://"Source Account Cf template.yml" \<br />  --profile source-account</pre> | 数据工程师、机器学习工程师、 DevOps 工程师 | 
| 部署源基础设施。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | 数据工程师、机器学习工程师、 DevOps 工程师 | 
| 验证部署并收集输出。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | DevOps 工程师、机器学习工程师、数据工程师 | 
| 确认电子邮件订阅。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | 数据工程师、机器学习工程师、 DevOps 工程师 | 

### 运行并监控复制过程
<a name="run-and-monitor-the-copy-process"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 运行并监控复制过程 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | DevOps 工程师、机器学习工程师、数据工程师 | 
| 运行 Step Function。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | DevOps 工程师、机器学习工程师、数据工程师 | 
| 监控进度。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | DevOps 工程师、机器学习工程师、数据工程师 | 
| 检查结果。 | 等待该过程完成（每 30 秒更新一次）：<pre>while true; do<br />  STATUS=$(aws stepfunctions describe-execution \<br />    --execution-arn $EXECUTION_ARN \<br />    --profile source-account \<br />    --region $SOURCE_REGION \<br />    --query 'status' \<br />    --output text)<br />  <br />  echo "Current status: $STATUS"<br />  <br />  if [[ "$STATUS" == "SUCCEEDED" || "$STATUS" == "FAILED" || "$STATUS" == "TIMED_OUT" || "$STATUS" == "ABORTED" ]]; then<br />    break<br />  fi<br />  <br />  sleep 30<br />done<br /><br />echo "Final execution status: $STATUS"</pre> | DevOps 工程师、机器学习工程师、数据工程师 | 
| 验证映像。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | DevOps 工程师、数据工程师、机器学习工程师 | 

## 问题排查
<a name="copy-ecr-container-images-across-accounts-regions-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| Step Function 无法运行。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/copy-ecr-container-images-across-accounts-regions.html) | 

## 相关资源
<a name="copy-ecr-container-images-across-accounts-regions-resources"></a>
+ [Crane 文档](https://github.com/google/go-containerregistry/blob/main/cmd/crane/doc/crane.md)
+ [什么是 Amazon 弹性容器注册表？](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)
+ [什么是 AWS Lambda？](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)
+ [什么是 Step Functions？](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)

## 附加信息
<a name="copy-ecr-container-images-across-accounts-regions-additional"></a>

**配置参数**


| 
| 
| 参数 | 说明 | 示例 | 
| --- |--- |--- |
| `SourceAccountId` | 来源 AWS 账户 ID | `11111111111` | 
| `DestinationAccountId` | 目的地 AWS 账户 ID | `22222222222` | 
| `DestinationRegion` | 目标 AWS 区域 | `us-east-2` | 
| `SourceRegion` | 来源 AWS 区域 | `us-east-1` | 
| `NotificationEmail` | 电子邮件通知 | `abc@xyz.com` | 
| `RepositoryList` | 要复制的存储库 | `repo1,repo2,repo3` | 
| `LambdaImageUri` | Lambda 容器映像 | `${ACCOUNT}.dkr.ecr.${REGION}.amazonaws.com/ecr-copy-lambda:latest` | 

# 使用 Amazon EFS 创建 Amazon ECS 任务定义并在 EC2 实例上挂载文件系统
<a name="create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs"></a>

*Durga Prasad Cheepuri，Amazon Web Services*

## Summary
<a name="create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs-summary"></a>

此模式提供了创建亚马逊弹性容器服务 (Amazon ECS) 任务定义的代码示例和步骤，该任务定义在亚马逊网络服务 (AWS) 云的 EC2亚马逊弹性计算云 (Amazon) 实例上运行，同时使用亚马逊弹性文件系统 (Amazon EFS) 在这些实例上 EC2 挂载文件系统。使用 Amazon EFS 的 Amazon ECS 任务会自动挂载您在任务定义中指定的文件系统，并使这些文件系统可供 AWS 区域中所有可用区中的任务容器使用。

为了满足您的持久性存储和共享存储要求，您可以结合使用 Amazon ECS 和 Amazon EFS。例如，您可以使用 Amazon EFS 存储持久性用户数据和应用程序数据，并在不同的可用区中运行活动和备用 ECS 容器对以实现高可用性。您还可以使用 Amazon EFS 存储可由 ECS 容器和分布式作业工作负载并行访问的共享数据。

要将 Amazon EFS 与 Amazon ECS 结合使用，您可以将一个或多个卷定义添加到任务定义中。卷定义包括 Amazon EFS 文件系统 ID、接入点 ID 以及 AWS Identity and Access Management（AWS IAM）授权或传输层安全性协议(TLS)传输中加密的配置。您可以在任务定义中使用容器定义来指定容器运行时挂载的任务定义卷。当使用 Amazon EFS 文件系统的任务运行时，Amazon ECS 会确保文件系统已挂载并可供需要访问该文件系统的容器使用。

## 先决条件和限制
<a name="create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account。
+ 具有虚拟专用网络(VPN) 端点或路由器的虚拟私有云(VPC)
+ （推荐）[Amazon ECS 容器代理 1.38.0 或更高版本](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-versions.html)，以与 Amazon EFS 接入点和 IAM 授权功能兼容（有关更多信息，请参阅 AWS Blog 文章 [Amazon EFS 的新增功能 - IAM 授权和接入点](https://aws.amazon.com/blogs/aws/new-for-amazon-efs-iam-authorization-and-access-points/)）。

**限制**
+ 1.35.0 之前的 Amazon ECS 容器代理版本不支持 Amazon EFS 文件系统执行使用 EC2 启动类型的任务。

## 架构
<a name="create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs-architecture"></a>

下图显示了一个应用程序的示例，该应用程序使用 Amazon ECS 创建任务定义并将一个 Amazon EFS 文件系统挂载到 ECS 容器中的 EC2 实例上。

![\[Amazon ECS architecture with task definition, ECS service, containers, and EFS file system integration.\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/090a3f03-a4c6-47e3-b1ae-b0eb5c5b269c/images/343e0f1d-44ee-4ec2-8392-aeddc0e48b83.png)


下图显示了如下工作流：

1. 创建 Amazon EFS 文件系统。

1. 创建带有容器的任务定义。

1. 配置容器实例以挂载 Amazon EFS 文件系统。任务定义引用卷挂载，因此容器实例可使用 Amazon EFS 文件系统。ECS 任务可以访问相同的 Amazon EFS 文件系统，无论这些任务是在哪个容器实例上创建的。

1. 创建具有三个任务定义实例的 Amazon ECS 服务。

**技术堆栈**
+ Amazon EC2
+ Amazon ECS
+ Amazon EFS

## 工具
<a name="create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs-tools"></a>
+ [亚马逊 EC2](https://docs.aws.amazon.com/ec2/?id=docs_gateway) — 亚马逊弹性计算云 (Amazon EC2) 在 AWS 云中提供可扩展的计算容量。您可以根据需要使用 Amazon EC2 启动任意数量或数量的虚拟服务器，也可以进行横向扩展或扩展。
+ [Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) - Amazon Elastic Container Service (Amazon ECS) 是一项高度可扩展的快速容器管理服务，可助您轻松运行、停止和管理集群上的容器。您可以在由 AWS Fargate 托管的无服务器基础设施上运行任务和服务。或者，为了更好地控制您的基础架构，您可以在自己管理的 EC2 实例集群上运行任务和服务。
+ [Amazon EFS](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html) - Amazon Elastic File System (Amazon EFS) 可提供简单、可扩展、完全托管的弹性 NFS 文件系统，以便与 Amazon Web Services Cloud 服务和本地资源配合使用。
+ [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) - AWS 命令行界面（AWS CLI）是一种开源工具，它使您能够使用命令行 Shell 中的命令与 Amazon Web Services 交互。仅需最少的配置，即可使用 AWS CLI 开始运行命令，以便从终端程序中的命令提示符实现与基于浏览器的 AWS 管理控制台所提供的功能等同的功能。

## 操作说明
<a name="create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs-epics"></a>

### 创建 Amazon EFS 文件系统
<a name="create-an-amazon-efs-file-system"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 AWS 管理控制台 创建 Amazon EFS 文件系统。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs.html) | AWS DevOps | 

### 使用 Amazon EFS 文件系统或 AWS CLI 创建 Amazon ECS 任务定义
<a name="create-an-amazon-ecs-task-definition-by-using-either-an-amazon-efs-file-system-or-the-aws-cli"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 Amazon EFS 文件系统创建任务定义。 | 使用具有以下配置的[新 Amazon ECS 控制台](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-task-definition.html)或[经典 Amazon ECS 控制台](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-task-definition-classic.html)创建任务定义：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs.html) | AWS DevOps | 
| 使用 AWS CLI 创建任务定义。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs.html) | AWS DevOps | 

## 相关资源
<a name="create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs-resources"></a>
+ [Amazon ECS 任务定义](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)
+ [Amazon EFS 卷](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/efs-volumes.html)

## 附件
<a name="attachments-090a3f03-a4c6-47e3-b1ae-b0eb5c5b269c"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/090a3f03-a4c6-47e3-b1ae-b0eb5c5b269c/attachments/attachment.zip)

# 使用容器映像部署 Lambda 函数
<a name="deploy-lambda-functions-with-container-images"></a>

*Ram Kandaswamy，Amazon Web Services*

## Summary
<a name="deploy-lambda-functions-with-container-images-summary"></a>

AWS Lambda 支持将容器镜像作为部署模型。此模式介绍了如何通过容器映像部署 Lambda 函数。 

Lambda 是一项无服务器、事件驱动计算服务，让您能够为几乎任何类型的应用程序或后端服务运行代码，而无需预调配或管理服务器。借助对 Lambda 函数的容器映像支持，您可以为应用程序构件提供高达 10 GB 的存储空间，并能够使用熟悉的容器映像开发工具。

此模式中的示例使用 Python 作为基础编程语言，但您也可以使用其他语言，例如 Java、Node.js 或 Go。要获取来源，可以考虑基于 Git 的系统，例如 GitHub、或 Bitbucket GitLab，或者使用亚马逊简单存储服务 (Amazon S3) Service。

## 先决条件和限制
<a name="deploy-lambda-functions-with-container-images-prereqs"></a>

**先决条件**
+ Amazon Elastic Container Registry(Amazon ECR) 已激活
+ 应用程序代码
+ 带运行时系统接口客户端以及最新版本的 Python 的 Docker 映像
+ Git 的工作知识

**限制**
+ 支持的最大映像大小为 10 GB。
+ 基于容器部署的 Lambda 的最长运行时间为 15 分钟。

## 架构
<a name="deploy-lambda-functions-with-container-images-architecture"></a>

**目标架构**

![\[创建 Lambda 函数的四步流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e421cc58-d33e-493d-b0bb-c3ffe39c2eb9/images/7f36d3d8-d161-497a-b036-26d886a16c69.png)


 

1. 您可以创建 Git 存储库，并将应用程序代码提交至该存储库。

1. 该 AWS CodeBuild 项目由提交更改触发。

1. 该 CodeBuild 项目创建 Docker 映像并将构建的映像发布到 Amazon ECR。

1. 您可以使用 Amazon ECR 中的映像创建 Lambda 函数。

**自动化和扩展**

可以通过使用 SDK 中的 AWS CloudFormation AWS Cloud Development Kit (AWS CDK)、或 API 操作来自动执行此模式。Lambda 可根据请求数量自动扩缩，您可以使用并发参数对其进行优化。有关更多信息，请参阅 [Lambda 文档](https://docs.aws.amazon.com/lambda/latest/dg/lambda-concurrency.html)。

## 工具
<a name="deploy-lambda-functions-with-container-images-tools"></a>

**AWS 服务**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)AWS CloudFormationhelps 您可以设置 AWS 资源，快速一致地配置资源，并在和的整个生命周期中 AWS 账户 对其进行管理 AWS 区域。此模式使用 App [AWS CloudFormation lication Composer](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/app-composer-for-cloudformation.html)，它可以帮助您直观地查看和编辑 CloudFormation 模板。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管式构建服务，可编译源代码、运行单元测试和生成部署就绪的构件。
+ [Amazon Elastic Container Registry（Amazon ECR）](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)是一项安全、可扩展且可靠的托管容器映像注册表服务。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。

**其他工具**
+ [Docker](https://www.docker.com/) 是一组平台即服务（PaaS）产品，它们利用操作系统级的虚拟化技术在容器中提供软件。
+ [GitHub[GitLab](https://docs.gitlab.com/ee/user/get_started/get_started_projects.html)](https://docs.github.com/en/repositories/creating-and-managing-repositories/quickstart-for-repositories)、和 [Bitbucket](https://support.atlassian.com/bitbucket-cloud/docs/tutorial-learn-bitbucket-with-git/) 是一些常用的基于 Git 的源代码控制系统，用于跟踪源代码更改。

## 最佳实践
<a name="deploy-lambda-functions-with-container-images-best-practices"></a>
+ 使函数足够高效足够小，以避免加载不必要的文件。
+ 努力将静态层置于 Docker 文件列表的高处，并将变化频率更高的层置于低处。这将改善缓存，从而提高性能。
+ 映像拥有者负责更新和修补映像。将此更新周期添加至您的操作流程。有关详情，请参阅 [AWS Lambda 文档](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html#function-code)。

## 操作说明
<a name="deploy-lambda-functions-with-container-images-epics"></a>

### 在中创建项目 CodeBuild
<a name="create-a-project-in-codebuild"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Git 存储库。 | 创建 Git 存储库，其中将包含应用程序源代码、Dockerfile 和 `buildspec.yaml` 文件。 | 开发者版 | 
| 创建 CodeBuild 项目。 | 要使用 CodeBuild 项目创建自定义 Lambda 映像，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-lambda-functions-with-container-images.html) | 开发者版 | 
| 编辑 Dockerfile。 | Dockerfile 应位于您开发应用程序的顶级目录中。Python 代码应该在 `src` 文件夹中。创建映像时，使用 [Lambda 支持的官方映像](https://gallery.ecr.aws/lambda?page=1)。否则，将发生引导错误，从而导致打包过程更加困难。有关详细信息，请参阅[其他信息](#deploy-lambda-functions-with-container-images-additional)部分。 | 开发者版 | 
| 在 Amazon ECR 中创建一个存储库。 | 在 Amazon ECR 中创建容器存储库。在以下示例命令中，创建名为 `cf-demo` 的存储库：<pre>aws ecr create-repository --cf-demo </pre>存储库将在 `buildspec.yaml` 文件中引用。 | AWS 管理员、开发人员 | 
| 将映像推送到 Amazon ECR | 您可以使用 CodeBuild 来执行映像构建过程。 CodeBuild 需要获得权限才能与 Amazon ECR 交互并使用 S3。作为该过程的一部分，将构建 Docker 映像并将其推送至 Amazon ECR 注册表。有关模板和代码的详细信息，请参阅 [其他信息](#deploy-lambda-functions-with-container-images-additional)部分。 | 开发者版 | 
| 验证映像是否在存储库中。 | 若要验证映像是否在存储库中，请在 Amazon ECR 控制台上选择**存储库**。如果 Amazon ECR 设置中启用了漏洞扫描功能，则应列出带有标签和漏洞扫描报告结果的映像。 有关更多信息，请参阅 [AWS 文档](https://docs.aws.amazon.com/cli/latest/reference/ecr/put-registry-scanning-configuration.html)。 | 开发者版 | 

### 创建运行映像的 Lambda 函数
<a name="create-the-lambda-function-to-run-the-image"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Lambda 函数。 | 在 Lambda 控制台上，选择**创建函数**，然后选择**容器映像**。输入函数名称和 Amazon ECR 存储库中映像的 URI，然后选择**创建函数**。有关更多信息，请参阅 [AWS Lambda 文档](https://docs.aws.amazon.com/lambda/latest/dg/API_CreateFunction.html)。 | 应用程序开发人员 | 
| 测试 Lambda 函数。 | 若要调用并测试该函数，请选择**测试**。有关更多信息，请参阅 [AWS Lambda 文档](https://docs.aws.amazon.com/lambda/latest/dg/testing-functions.html)。 | 应用程序开发人员 | 

## 问题排查
<a name="deploy-lambda-functions-with-container-images-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 构建未成功。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-lambda-functions-with-container-images.html) | 

## 相关资源
<a name="deploy-lambda-functions-with-container-images-resources"></a>
+ [Lambda 的基本映像](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-images.html)
+ [的 Docker 示例 CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/sample-docker.html)
+ [传递临时凭证](https://aws.amazon.com/premiumsupport/knowledge-center/codebuild-temporary-credentials-docker/)

## 附加信息
<a name="deploy-lambda-functions-with-container-images-additional"></a>

**编辑 Dockerfile**

以下代码显示了您在 Dockerfile 中编辑的命令。

```
FROM public.ecr.aws/lambda/python:3.xx

# Copy function code
COPY app.py ${LAMBDA_TASK_ROOT} 
COPY requirements.txt  ${LAMBDA_TASK_ROOT} 

# install dependencies
RUN pip3 install --user -r requirements.txt

# Set the CMD to your handler (could also be done as a parameter override outside of the Dockerfile)
CMD [ "app.lambda_handler" ]
```

在 `FROM` 命令中，为 Lambda 支持的 Python 版本使用适当的值（例如，`3.12`）。这将是公有 Amazon ECR 映像存储库中可用的基础映像。 

`COPY app.py ${LAMBDA_TASK_ROOT}` 命令将代码复制至 Lambda 函数将使用的任务根目录。此命令使用环境变量，因此我们无要担心实际路径。将要运行的函数作为参数传递至 `CMD [ "app.lambda_handler" ]` 命令。

`COPY requirements.txt` 命令捕获代码所需依赖项。 

`RUN pip install --user -r requirements.txt` 命令将依赖项安装至本地用户目录。 

若要构建映像，请运行以下命令。

```
docker build -t <image name> .
```

**在 Amazon ECR 中添加映像**

在以下代码中，将 `aws_account_id` 替换为账号，如果正在使用其他区域，则替换为 `us-east-1`。该`buildspec`文件使用 CodeBuild 内部版本号将图像版本唯一标识为标签值。您可以更改此设置，以满足您的要求。

*buildspec 自定义代码*

```
phases:
  install:
    runtime-versions:
       python: 3.xx
  pre_build:
    commands:
      - python3 --version
      - pip3 install --upgrade pip
      - pip3 install --upgrade awscli
      - sudo docker info
  build:
    commands:
      - echo Build started on `date`
      - echo Building the Docker image...
      - ls
      - cd app
      - docker build -t cf-demo:$CODEBUILD_BUILD_NUMBER .
      - docker container ls
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker image...
      - aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin aws_account_id.dkr.ecr.us-east-1.amazonaws.com
      - docker tag cf-demo:$CODEBUILD_BUILD_NUMBER aws_account_id.dkr.ecr.us-east-1.amazonaws.com/cf-demo:$CODEBUILD_BUILD_NUMBER
      - docker push aws_account_id.dkr.ecr.us-east-1.amazonaws.com/cf-demo:$CODEBUILD_BUILD_NUMBER
```

# 使用 AWS Fargate 在 Amazon ECS 上部署 Java 微服务
<a name="deploy-java-microservices-on-amazon-ecs-using-aws-fargate"></a>

*Vijay Thompson 和 Sandeep Bondugula，Amazon Web Services*

## Summary
<a name="deploy-java-microservices-on-amazon-ecs-using-aws-fargate-summary"></a>

此模式为使用 AWS Fargate 在 Amazon Elastic Container Service (Amazon ECS) 上部署容器化 Java 微服务提供了指导。该模式不使用 Amazon Elastic Container Registry (Amazon ECR) 进行容器管理；相反，Docker 映像是从某 Docker 中心提取的。

## 先决条件和限制
<a name="deploy-java-microservices-on-amazon-ecs-using-aws-fargate-prereqs"></a>

**先决条件**
+ 在 Docker 中心上的现有 Java 微服务应用程序
+ 公共 Docker 存储库
+ 一个有效的 Amazon Web Services account
+ 熟悉 Amazon Web Services，包括 Amazon ECS 和 Fargate
+ Docker、Java 和 Spring Boot 框架
+ Amazon Relational Database Service（Amazon RDS）已启动并运行（可选）
+ 如果应用程序需要 Amazon RDS（可选），则为虚拟私有云（VPC）

## 架构
<a name="deploy-java-microservices-on-amazon-ecs-using-aws-fargate-architecture"></a>

**源技术堆栈**
+ Java 微服务（例如，在 Spring Boot 中实施）并部署在 Docker 上

**源架构**

![\[部署在 Docker 上的 Java 微服务的源架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/65185957-2b8b-43a6-964c-95ce0a45ba17/images/0a946ca8-fe37-4ede-85cb-a80a1c36105d.png)


**目标技术堆栈**
+ 使用 Fargate 托管每项微服务的 Amazon ECS 集群
+ 用于托管 Amazon ECS 集群和相关安全组的 VPC 网络 
+ 使用 Fargate 启动容器的每项微服务的 cluster/task 定义

**目标架构**

![\[Amazon ECS 上 Java 微服务的目标架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/65185957-2b8b-43a6-964c-95ce0a45ba17/images/b21349ea-21fc-4688-b76a-1bde479858aa.png)


## 工具
<a name="deploy-java-microservices-on-amazon-ecs-using-aws-fargate-tools"></a>

**工具**
+ [Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) 使您无需安装和操作自己的容器编排软件、管理和扩展虚拟机集群，也不需要在这些虚拟机上调度容器。 
+ [AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/userguide/what-is-fargate.html) 可帮助您运行容器，而无需管理服务器或亚马逊弹性计算云 (Amazon EC2) 实例。它与 Amazon Elastic Container Service（Amazon ECS）配合使用。
+ [Docker](https://www.docker.com/) 软件平台可以快速构建、测试和部署应用程序。Docker 将软件打包成称为*容器*的标准化单元，容器拥有软件运行所需一切，包括库、系统工具、代码和运行时系统。 

**Docker 代码**

以下 Dockerfile 指定了所使用的 Java 开发套件（JDK）版本、Java 存档（JAR）文件所在的版本、公开的端口号以及应用程序的入口点。

```
FROM openjdk:11
ADD target/Spring-docker.jar Spring-docker.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","Spring-docker.jar"]
```

## 操作说明
<a name="deploy-java-microservices-on-amazon-ecs-using-aws-fargate-epics"></a>

### 创建新的任务定义
<a name="create-new-task-definitions"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建任务定义。 | 在 Amazon ECS 中运行 Docker 容器需要任务定义。打开 Amazon ECS 控制台 [https://console.aws.amazon.com/ecs/](https://console.aws.amazon.com/ecs/)，选择**任务定义**，然后创建新的任务定义。有关更多信息，请参阅 [Amazon ECS 文档](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-task-definition.html)。 | AWS 系统管理员、应用程序开发人员 | 
| 选择启动类型。 | 选择 **Fargate** 作为启动类型。 | AWS 系统管理员、应用程序开发人员 | 
| 配置任务。 | 定义任务名称并使用适当数量的任务内存和 CPU 配置应用程序。 | AWS 系统管理员、应用程序开发人员 | 
| 定义容器。 | 指定容器名称。对于映像，输入 Docker 站点名称、存储库名称和 Docker 映像的标签名称（`docker.io/sample-repo/sample-application:sample-tag-name`）。为应用程序设置内存限制，为允许的端口设置端口映射（`8080, 80`）。 | AWS 系统管理员、应用程序开发人员 | 
| 创建任务。 | 任务和容器配置到位后，创建任务。有关详细说明，请查看*相关资源*部分的链接。 | AWS 系统管理员、应用程序开发人员 | 

### 配置集群
<a name="configure-the-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建和配置集群。 | 选择**仅限网络**作为集群类型，配置名称，然后创建集群或使用现有集群（如果有）。有关更多信息，请参阅 [Amazon ECS 文档](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create_cluster.html)。 | AWS 系统管理员、应用程序开发人员 | 

### 配置任务
<a name="configure-task"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 任务。 | 在集群中，选择**运行新任务**。 | AWS 系统管理员、应用程序开发人员 | 
| 选择启动类型。 | 选择 **Fargate** 作为启动类型。 | AWS 系统管理员、应用程序开发人员 | 
| 选择任务定义、修订版和平台版本。 | 选择要运行的任务，然后选择任务定义的修订版和平台版本。 | AWS 系统管理员、应用程序开发人员 | 
| 选择 集群。 | 选择要在其中运行任务的集群。 | AWS 系统管理员、应用程序开发人员 | 
| 指定任务数量。 | 配置应运行的任务数。如果您启动时有两个或更多任务，则需要负载均衡器在这些任务中分发流量。 | AWS 系统管理员、应用程序开发人员 | 
| 指定任务组。 | （可选）指定任务组名称以将一组相关任务标识为任务组。 | AWS 系统管理员、应用程序开发人员 | 
| 配置集群 VPC、子网和安全组。 | 配置集群 VPC 和要在其中部署应用程序的子网。创建或更新安全组（HTTP、HTTPS 和端口 8080）以提供对入站和出站连接的访问权限。 | AWS 系统管理员、应用程序开发人员 | 
| 配置公有 IP 设置。 | 启用或禁用公有 IP，具体取决于您是否要使用公有 IP 地址执行 Fargate 任务。推荐的默认选项为**启用**。 | AWS 系统管理员、应用程序开发人员 | 
| 查看设置并创建任务 | 查看设置，然后选择**运行任务**。 | AWS 系统管理员、应用程序开发人员 | 

### 割接
<a name="cut-over"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 复制应用程序 URL。 | 当任务状态更新为*正在运行*时，选择该任务。在“网络”部分中，复制公有 IP。 | AWS 系统管理员、应用程序开发人员 | 
| 测试您的应用程序。 | 在浏览器中，输入公有 IP 以测试应用程序。 | AWS 系统管理员、应用程序开发人员 | 

## 相关资源
<a name="deploy-java-microservices-on-amazon-ecs-using-aws-fargate-resources"></a>
+ [Amazon ECS 的 Docker 基础知识](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html)（Amazon ECS 文档）
+ [AWS Fargate 上的 Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html)（Amazon ECS 文档）
+ [创建任务定义](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-task-definition.html)（Amazon ECS 文档）
+ [创建集群](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create_cluster.html)（Amazon ECS 文档）
+ [配置基本服务参数](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/basic-service-params.html)（Amazon ECS 文档）
+ [配置网络](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service-configure-network.html)（Amazon ECS 文档）
+ [在 Amazon ECS 上部署 Java 微服务](https://aws.amazon.com/blogs/compute/deploying-java-microservices-on-amazon-ec2-container-service/)（博客文章）

# 使用 Amazon EKS 和 Amazon S3 中的 Helm 图表存储库部署 Kubernetes 资源和软件包
<a name="deploy-kubernetes-resources-and-packages-using-amazon-eks-and-a-helm-chart-repository-in-amazon-s3"></a>

*Sagar Panigrahi，Amazon Web Services*

## Summary
<a name="deploy-kubernetes-resources-and-packages-using-amazon-eks-and-a-helm-chart-repository-in-amazon-s3-summary"></a>

此模式可帮助您高效管理 Kubernetes 应用程序，无论复杂性如何。此模式将 Helm 集成至现有持续集成和持续交付 (CI/CD) 管道，以便将应用程序部署至 Kubernetes 集群。Helm 是 Kubernetes 软件包管理器，可以帮助您管理 Kubernetes 应用程序。Helm 图表可用于定义、安装和升级复杂的 Kubernetes 应用程序。图表可以版本控制，并存储在 Helm 存储库中，从而缩短停机期间的平均恢复时间 (MTTR)。 

此模式对 Kubernetes 集群使用了 Amazon Elastic Kubernetes Service (Amazon EKS)。其使用 Amazon Simple Storage Service (Amazon S3) 作为 Helm 图表存储库，如此整个组织的开发人员即可集中管理和访问此类图表。

## 先决条件和限制
<a name="deploy-kubernetes-resources-and-packages-using-amazon-eks-and-a-helm-chart-repository-in-amazon-s3-prereqs"></a>

**先决条件**
+ 具有虚拟私有云（VPC）的活跃 Amazon Web Services (AWS) Account
+ Amazon EKS 集群 
+ 在 Amazon EKS 集群中设置并准备处理工作负载的工作节点
+ 在客户端计算机中为目标集群配置 Amazon EKS kubeconfig 文件的 Kubectl
+ 用于创建 S3 存储桶的 AWS Identity and Access Management (IAM) 访问权限
+ 通过客户端计算机访问 Amazon S3 的 IAM（编程或角色）
+ 源代码管理和 CI/CD 管道

**限制**
+ 目前不支持升级、删除或管理自定义资源定义 (CRDs)。
+ 如果使用的是引用 CRD 的资源，则必须单独安装 CRD（图表外）。

**产品版本**
+ Helm v3.6.3

## 架构
<a name="deploy-kubernetes-resources-and-packages-using-amazon-eks-and-a-helm-chart-repository-in-amazon-s3-architecture"></a>

**目标技术堆栈**
+ Amazon EKS
+ Amazon VPC
+ Amazon S3
+ 源代码管理
+ Helm
+ Kubectl

**目标架构 **

![\[客户端 Helm 和 Kubectl 在 Amazon S3 中为 Amazon EKS 集群部署了 Helm 图表存储库。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/d3f993e6-4d96-4cb9-a075-c4debe431fd7/images/2f09f7bb-440a-4c4b-b29f-08d136d1ada4.png)


 

**自动化和扩展**
+ AWS CloudFormation 可用于自动创建基础设施。有关更多信息，请参阅 A [mazon EKS 文档 CloudFormation中的使用 AWS 创建亚马逊 EKS 资源](https://docs.aws.amazon.com/eks/latest/userguide/creating-resources-with-cloudformation.html)。
+ Helm 将整合到您现有的 CI/CD 自动化工具中，以自动化 Helm 图表的打包和版本控制（超出此模式的范围）。
+ GitVersion 或者 Jenkins 内部版本号可用于自动化图表的版本控制。

## 工具
<a name="deploy-kubernetes-resources-and-packages-using-amazon-eks-and-a-helm-chart-repository-in-amazon-s3-tools"></a>

**工具**
+ [Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) – Amazon Elastic Kubernetes Service (Amazon EKS) 是一项托管服务，可用来在 AWS 上运行 Kubernetes，而无需支持或维护您自己的 Kubernetes 控制面板。Kubernetes 是一个用于实现容器化应用程序的部署、扩缩和管理自动化的开源系统。
+ [Helm](https://helm.sh/docs/) – Helm 是 Kubernetes 的软件包管理器，可帮助您在 Kubernetes 集群上安装和管理应用程序。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/gsg/GetStartedWithS3.html) – Amazon Simple Storage Service (Amazon S3) 是一项面向互联网的存储服务。您可以通过 Amazon S3 随时在 Web 上的任何位置存储和检索的任意大小的数据。
+ [Kubectl](https://kubernetes.io/docs/reference/kubectl/overview/) – Kubectl 是针对 Kubernetes 集群运行命令的命令行实用程序。

**代码**

示例代码附后。

## 操作说明
<a name="deploy-kubernetes-resources-and-packages-using-amazon-eks-and-a-helm-chart-repository-in-amazon-s3-epics"></a>

### 配置并初始化 Helm
<a name="configure-and-initialize-helm"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装 Helm 客户端。 | 若要在本地系统上下载并安装 Helm 客户端，请使用以下命令。 <pre>sudo curl https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash</pre> | DevOps 工程师 | 
| 验证 Helm 安装 | 若要验证 Helm 是否与 Amazon EKS 集群中的 Kubernetes API 服务器通信，请运行 `helm version`。 | DevOps 工程师 | 

### 在 Amazon EKS 集群中创建并安装 Helm 图表
<a name="create-and-install-a-helm-chart-in-the-amazon-eks-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 NGINX 创建 Helm 图表。 | 若要在客户端计算机上创建名为 `my-nginx` 的 Helm 图表，请运行 `helm create my-nginx`。 | DevOps 工程师 | 
| 查看图表结构。 | 若要查看图表的结构，请运行树命令 `tree my-nginx/`。 | DevOps 工程师 | 
| 在图表中停用服务账户创建。 | 在 `values.yaml` 的 `serviceAccount` 部分下，将 `create` 密钥设置为 `false`。将其关闭，原因在于无需为此模式创建服务账户。 | DevOps 工程师 | 
| 验证 (lint) 修改后的图表是否存在语法错误。 | 若要验证将图表安装至目标集群之前图表是否存在任何语法错误，请运行 `helm lint my-nginx/`。 | DevOps 工程师 | 
| 安装部署 Kubernetes 资源的图表。 | 若要运行 Helm 图表 安装程序，请使用以下命令。 <pre>helm install --name my-nginx-release --debug my-nginx/ --namespace helm-space </pre>可选 `debug` 标志在安装过程中输出所有调试消息。`namespace` 标志指定将在其中创建此图表的资源部分的命名空间。 | DevOps 工程师 | 
| 查看 Amazon EKS 集群中的资源。 | 若要查看 `helm-space` 命名空间中的 Helm 图表部分创建的资源，请使用以下命令。 <pre>kubectl get all -n helm-space</pre> | DevOps 工程师 | 

### 回滚至 Kubernetes 应用程序的先前版本
<a name="roll-back-to-a-previous-version-of-a-kubernetes-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 修改并升级版本。 | 若要修改图表，请在 `values.yaml` 中将 `replicaCount` 值更改为 `2`。然后通过运行以下命令升级已安装发布：<pre>helm upgrade my-nginx-release my-nginx/ --namespace helm-space</pre> | DevOps 工程师 | 
| 查看 Helm 版本的历史记录。 | 若要列出使用 Helm 安装的特定版本的所有修订版本，请运行以下命令。 <pre>helm history my-nginx-release</pre> | DevOps 工程师 | 
| 查看特定修订版的详细信息。 | 在切换或回滚至工作版本前以及在安装修订版前进行额外验证前，请使用以下命令查看已传递至每个修订版本的值。<pre>helm get --revision=2 my-nginx-release</pre> | DevOps 工程师 | 
| 回滚至先前版本。 | 若要回滚至以前的修订版，请使用以下命令。 <pre>helm rollback my-nginx-release 1 </pre>此示例正在回滚至修订版号 1。 | DevOps 工程师 | 

### 将 S3 存储桶初始化为 Helm 存储库
<a name="initialize-an-s3-bucket-as-a-helm-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 Helm 图表创建 S3 存储桶。 | 创建唯一 S3 存储桶。在存储桶中，创建一个名为 `charts` 的文件夹。此模式中的示例使用 `s3://my-helm-charts/charts` 作为目标图表存储库。 | 云管理员 | 
| 安装适用于 Amazon S3 的 Helm 插件。 | 若要在客户端计算机上安装 helm-s3 插件，请使用以下命令。 <pre>helm plugin install https://github.com/hypnoglow/helm-s3.git --version 0.10.0</pre>请注意：提供使用插件版本 0.9.0 及更高版本的 Helm V3 支持。 | DevOps 工程师 | 
| 初始化 Amazon S3 Helm 存储库。 | 若要将目标文件夹初始化为 Helm 存储库，请使用以下命令。 <pre>helm S3 init s3://my-helm-charts/charts </pre>该命令在目标系统中创建 `index.yaml` 文件，用于跟踪存储在该位置的所有图表信息。 | DevOps 工程师 | 
| 将 Amazon S3 存储库添加至 Helm。 | 要向客户端计算机中添加存储库，请使用以下命令。<pre>helm repo add my-helm-charts s3://my-helm-charts/charts </pre>此命令将别名添加至 Helm 客户端计算机中的目标存储库。 | DevOps 工程师 | 
| 查看存储库列表。 | 若要查看 Helm 客户端计算机中的存储库列表，请运行 `helm repo list`。 | DevOps 工程师 | 

### 在 Amazon S3 Helm 存储库中打包和存储图表
<a name="package-and-store-charts-in-the-amazon-s3-helm-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 打包图表。 | 若要打包您创建的 `my-nginx` 图表，请运行 `helm package ./my-nginx/`。该命令将 `my-nginx` 图表文件夹的所有内容打包成存档文件，该文件使用 `Chart.yaml` 文件中提到的版本号命名。 | DevOps 工程师 | 
| 将包存储至 Amazon S3 Helm 存储库。 | 若要将数据包上传至 Amazon S3 中的 Helm 存储库，请使用正确的 `.tgz` 文件名运行以下命令。<pre>helm s3 push ./my-nginx-0.1.0.tgz my-helm-charts</pre> | DevOps 工程师 | 
| 搜索 Helm 图表。 | 若要确认图表同时出现在本地和 Amazon S3 的 Helm 存储库中，请运行以下命令。<pre>helm search repo my-nginx</pre> | DevOps 工程师 | 

### 修改、版本化和打包图表
<a name="modify-version-and-package-a-chart"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 修改并打包图表。 | 将 `values.yaml` 中，将 `replicaCount` 的值设为 `1`。然后通过运行 `helm package ./my-nginx/` 来打包图表，这次是将版本 `Chart.yaml` 更改为 `0.1.1`。 理想情况下，版本控制是在管道中使用诸如 GitVersion 或 Jenkins 内部版本号之类的工具通过自动化进行 CI/CD 更新。自动生成的版本号超出了这种模式范围。 | DevOps 工程师 | 
| 将新版本推送至 Amazon S3 中的 Helm 存储库。 | 若要将版本为 0.1.1 的新软件包推送至 Amazon S3 中的 `my-helm-charts` Helm 存储库，请运行以下命令。<pre>helm s3 push ./my-nginx-0.1.1.tgz my-helm-charts</pre> | DevOps 工程师 | 

### 从 Amazon S3 Helm 存储库中搜索并安装图表
<a name="search-for-and-install-a-chart-from-the-amazon-s3-helm-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 搜索 my-nginx 图表的所有版本。 | 若要查看图表的所有可用版本，请使用 `--versions` 标志运行以下命令：<pre>helm search repo my-nginx --versions</pre>如果没有标志，Helm 默认会显示图表的最新上传版本。 | DevOps 工程师 | 
| 从 Amazon S3 Helm 存储库安装图表。 | 上一个任务的搜索结果显示了 `my-nginx` 图表的多个版本。若要从 Amazon S3 Helm 存储库安装新版本 (0.1.1)，请使用以下命令。<pre>helm upgrade my-nginx-release my-helm-charts/my-nginx --version 0.1.1 --namespace helm-space</pre> | DevOps 工程师 | 

## 相关资源
<a name="deploy-kubernetes-resources-and-packages-using-amazon-eks-and-a-helm-chart-repository-in-amazon-s3-resources"></a>
+ [HELM 文档](https://helm.sh/docs/)
+ [helm-s3 插件（MIT 许可证）](https://github.com/hypnoglow/helm-s3.git)
+ [HELM 客户端二进制](https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3)
+ [Amazon EKS 文档](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html)

## 附件
<a name="attachments-d3f993e6-4d96-4cb9-a075-c4debe431fd7"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/d3f993e6-4d96-4cb9-a075-c4debe431fd7/attachments/attachment.zip)

# 使用 Terraform 在亚马逊 EKS 中部署 CockroachDB 集群
<a name="deploy-cockroachdb-on-eks-using-terraform"></a>

*亚马逊 Web Services 的 Sandip Gangapadhyay 和 Kalyan Senthilnathan*

## Summary
<a name="deploy-cockroachdb-on-eks-using-terraform-summary"></a>

[这种模式提供了一个 HashiCorp Terraform 模块，用于使用 [CockroachDB 运算符在亚马逊 Elastic Kubernetes Service（Amazon EKS）上部署多节点 Coc](https://www.cockroachlabs.com/docs/stable/) kroachDB 集群。](https://www.cockroachlabs.com/docs/v25.4/cockroachdb-operator-overview)CockRoachDB 是一个分布式 SQL 数据库，可跨地理分布的集群提供自动水平分片、高可用性和一致的性能。此模式使用 Amazon EKS 作为托管 Kubernetes 平台，并实现[证书管理器用于受 TL](https://cert-manager.io/docs/) S 保护的节点通信。它还使用 [Network Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/introduction.html) 进行流量分配，并创建 CockroachDB [StatefulSets](https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/)，其容错能力和性能可自动复制数据。

**目标受众**

要实现此模式，我们建议您熟悉以下内容：
+ HashiCorp Terraform 概念和基础设施即代码 (IaC) 实践
+ AWS 服务，尤其是 Amazon EKS
+ Kubernetes 基础知识 StatefulSets，包括运算符和服务配置
+ 分布式 SQL 数据库
+ 安全概念，例如 TLS 证书管理。
+ DevOps 实践、 CI/CD 工作流程和基础设施自动化

## 先决条件和限制
<a name="deploy-cockroachdb-on-eks-using-terraform-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 在 Amazon EKS 集群中部署资源的权限
+ Amazon EKS 集群版本 1.23 或更高版本，其节点标记为 `node=cockroachdb`
+ [Amazon Elastic Block Store 容器存储接口 (CSI) 驱动程序](https://github.com/kubernetes-sigs/aws-ebs-csi-driver)版本 1.19.0 或更高版本，安装在 Amazon EKS 集群中
+ [Terraform CLI 版本 1.0.0 或更高版本，已安装](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli)
+ [kubectl，已安装](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)
+ Git，[已安装](https://git-scm.com/install/)
+ AWS Command Line Interface [(AWS CLI) 版本 2.9.18 或更高版本，[已安装并配置](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)

**限制**
+ CockroachDB Kubernetes 运营商不支持多个 Kubernetes 集群进行多区域部署。[有关更多限制，请参阅[跨多个 Kubernetes 集群编排 CockroachDB（CockroachDB 文档）和 CockroachDB Kubernetes](https://www.cockroachlabs.com/docs/stable/orchestrate-cockroachdb-with-kubernetes-multi-cluster.html#eks) Operator ()。](https://github.com/cockroachdb/cockroach-operator) GitHub
+ 默认情况下，永久卷声明的自动修剪功能 (PVCs) 处于禁用状态。这意味着，在停用和移除节点后，操作员将不会移除已安装到其 pod 上的永久卷。有关更多信息，请参阅 CockroachDB 文档中的[自动 PVC 修剪](https://www.cockroachlabs.com/docs/stable/scale-cockroachdb-kubernetes.html#automatic-pvc-pruning)。

**产品版本**
+ CockroachDB 版本 22.2.2

## 架构
<a name="deploy-cockroachdb-on-eks-using-terraform-architecture"></a>

**目标架构**

下图显示了虚拟私有云 (VPC) 中跨三个可用区域的高 AWS 可用性 CockroachDB 部署。CockroachDB 吊舱通过亚马逊 EKS 进行管理。该架构说明了用户如何通过 Network Load Balancer 访问数据库，该负载均衡器将流量分配到 CockroachDB 容器。Pod 在每个可用区的亚马逊弹性计算云 (Amazon EC2) 实例上运行，这提供了弹性和容错能力。

![\[在 VPC 内的三个 AWS 可用区域中部署的高可用性 CockroachDB。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e22d81ab-b85c-4709-8579-4c9cdb4afdb6/images/4b163abf-6fdc-4310-840c-bda621ab25dd.png)


**资源已创建**

部署此模式中使用的 Terraform 模块会创建以下资源：

1. **Network Load Balancer** — 此资源充当客户端请求的入口点，并在 CockroachDB 实例之间均匀分配流量。

1. **CockroachDB StatefulSet** — StatefulSet 定义了 Amazon EKS 集群中 CockroachDB 部署的所需状态。它管理 CockroachDB 容器的有序部署、扩展和更新。

1. **CockroachDB pod** — 这些 pod 是 CockroachDB 在 Kubernetes 容器中作为容器运行的实例。这些 Pod 存储和管理分布式集群中的数据。

1. **CockroachDB 数据库** — 这是由 CockroachDB 管理的分布式数据库，跨越多个 pod。它复制数据以实现高可用性、容错能力和性能。

## 工具
<a name="deploy-cockroachdb-on-eks-using-terraform-tools"></a>

**AWS 服务**
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您 AWS 服务 通过命令行 shell 中的命令进行交互。
+ [亚马逊 Elastic Kubernetes Service（亚马逊](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。

**其他工具**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款基础设施即代码（IaC）工具，可帮助您使用代码来预调配和管理云基础设施和资源。
+ [kubectl](https://kubernetes.io/docs/tasks/tools/)：针对 Kubernetes 集群运行命令的命令行界面。

**代码存储库**

此模式的代码可在使用 Terra [form 存储库的 Amazon EKS 中 GitHub 部署 CockroachDB 集群中](https://github.com/aws-samples/crdb-cluster-eks-terraform)找到。代码存储库包含以下适用于 Terraform 的文件和文件夹：
+ `modules`文件夹 — 此文件夹包含 CockroachDB 的 Terraform 模块
+ `main`文件夹 — 此文件夹包含调用 CockroachDB 子模块来创建 CockroachDB 数据库集群的根模块。

## 最佳实践
<a name="deploy-cockroachdb-on-eks-using-terraform-best-practices"></a>
+ 不要缩减到少于三个节点。这被认为是 CockroachDB 上的反模式，可能会导致错误。有关更多信息，请参阅 CockroachDB 文档中的[集群扩展](https://www.cockroachlabs.com/docs/stable/scale-cockroachdb-kubernetes.html)。
+ 使用 Karpernter 或集群自动扩缩器实现 Amazon EKS 自动扩展。这允许 CockroachDB 集群进行水平扩展，并自动添加新节点。有关更多信息，请参阅 Amazon EKS 文档中的[使用 Karpenter 和 Cluster Autoscaler 扩展集群计算](https://docs.aws.amazon.com/eks/latest/userguide/autoscaling.html)。
**注意**  
由于 `podAntiAffinity` Kubernetes 的调度规则，只能在一个 Amazon EKS 节点中调度一个 CockroachDB 容器。
+ 有关 Amazon EKS 安全最佳实践，请参阅 Amazon EKS 文档中的[安全最佳实](https://docs.aws.amazon.com/eks/latest/best-practices/security.html)践。
+ 有关 CockroachDB 的 SQL 性能最佳实践，请参阅 CockroachDB 文档中的 [SQL 性能最佳实践](https://www.cockroachlabs.com/docs/stable/performance-best-practices-overview.html)。
+ 有关为 Terraform 状态文件设置亚马逊简单存储服务 (Amazon S3) 远程后端的更多信息，请参阅 Terraform 文档中的亚马逊 [S](https://developer.hashicorp.com/terraform/language/backend/s3) 3。

## 操作说明
<a name="deploy-cockroachdb-on-eks-using-terraform-epics"></a>

### 设置您的环境
<a name="set-up-your-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆代码存储库。 | 输入以下命令来克隆存储库：<pre>git clone https://github.com/aws-samples/crdb-cluster-eks-terraform.git</pre> | DevOps 工程师，Git | 
| 更新 Terraform 变量。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-cockroachdb-on-eks-using-terraform.html) | DevOps 工程师，Terraform | 

### 部署资源
<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/deploy-cockroachdb-on-eks-using-terraform.html) | DevOps 工程师，Terraform | 

### 验证部署
<a name="verify-the-deployment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证资源创建。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-cockroachdb-on-eks-using-terraform.html) | DevOps 工程师 | 
| （可选）向上或向下扩展。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-cockroachdb-on-eks-using-terraform.html) | DevOps 工程师，Terraform | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除基础设施。 | `0`将节点扩展到可以降低计算成本。但是，对于由此模块创建的永久性 Amazon EBS 卷，您仍然需要付费。要消除存储成本，请按照以下步骤删除所有卷：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-cockroachdb-on-eks-using-terraform.html) | Terraform | 

## 问题排查
<a name="deploy-cockroachdb-on-eks-using-terraform-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 验证提供商凭证时出错 | 当你运行 Terraform `apply` 或`destroy`命令时，你可能会遇到以下错误：`Error: configuring Terraform AWS Provider: error validating provider  credentials: error calling sts:GetCallerIdentity: operation error STS: GetCallerIdentity, https response error StatusCode: 403, RequestID: 123456a9-fbc1-40ed-b8d8-513d0133ba7f, api error InvalidClientTokenId: The security token included in the request is invalid.`此错误是由本地计算机配置中使用的凭证安全令牌过期引起的。有关如何解决该错误的说明，请参阅 AWS CLI 文档中的[设置和查看配置设置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-methods)。 | 
| CockroachDB 吊舱处于待处理状态 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-cockroachdb-on-eks-using-terraform.html) | 

## 相关资源
<a name="deploy-cockroachdb-on-eks-using-terraform-resources"></a>
+ 在@@ [单个 Kubernetes 集群中部署 CockroachDB（Cock](https://www.cockroachlabs.com/docs/dev/deploy-cockroachdb-with-kubernetes.html) roachDB 文档）
+ 在@@ [多个 Kubernetes 集群中编排 CockroachDB](https://www.cockroachlabs.com/docs/dev/orchestrate-cockroachdb-with-kubernetes-multi-cluster.html)（CockroachDB 文档）
+ [AWS 提供者](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)（Terraform 文档）

## 附件
<a name="attachments-e22d81ab-b85c-4709-8579-4c9cdb4afdb6"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/e22d81ab-b85c-4709-8579-4c9cdb4afdb6/attachments/attachment.zip)

# 在 Amazon EKS 上部署示例 Java 微服务并使用应用程序负载均衡器公开该微服务
<a name="deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer"></a>

*Vijay Thompson 和 Akkamahadevi Hiremath，Amazon Web Services*

## Summary
<a name="deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-summary"></a>

此模式描述如何使用 `eksctl` 命令行实用程序和 Amazon Elastic Container Registry (Amazon ECR) 将示例 Java 微服务部署为 Amazon Elastic Kubernetes Service (Amazon EKS) 上的容器化应用程序。您可以使用应用程序负载均衡器均衡应用程序流量。

## 先决条件和限制
<a name="deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ AWS 命令行界面（AWS CLI）版本 1.7 或更高版本，已在 macOS、Linux 或 Windows上安装和配置。
+ 正在运行的 [Docker 进程守护程序](https://docs.docker.com/config/daemon/)
+ 在 macOS、Linux 或 Windows 上安装和配置的 `eksctl` 命令行实用程序（有关更多信息，请参阅 Amazon EKS 文档中的 [Amazon EKS 入门 — eksctl](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html)。）
+ 在 macOS、Linux 或 Windows 上安装和配置的`kubectl`命令行实用程序（有关更多信息，请参阅 Amazon EKS 文档中的[安装或更新 kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)。）

**限制**
+ 此模式不包括为应用程序负载均衡器安装 SSL 证书。

## 架构
<a name="deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-architecture"></a>

**目标技术堆栈**
+ Amazon ECR
+ Amazon EKS
+ Elastic Load Balancing

**目标架构**

下图显示了在 Amazon EKS 上容器化 Java 微服务的架构。

![\[将 Java 微服务部署为 Amazon EKS 上的容器化应用程序。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e1dd8ab0-9e1e-4d2b-b7af-89d3e583e57c/images/aaca4fd9-5aaa-4df5-aebd-02a2ed881c3b.png)


## 工具
<a name="deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-tools"></a>
+ [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 是一项安全、可扩展且可靠的托管容器映像注册表服务。
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) 可帮助您在 AWS 上运行 Kubernetes，而无需安装或维护您自己的 Kubernetes 控制面板或节点。
+ [AWS 命令行界面（AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它可帮助您通过命令行 Shell 中的命令与 Amazon Web Services 交互。
+ [Elastic L](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) oad Balancing 会自动将您的传入流量分配到一个或多个可用区域中的多个目标，例如亚马逊弹性计算云 (Amazon EC2) 实例、容器和 IP 地址。
+ [eksctl](https://eksctl.io/) 可以帮助您在Amazon EKS 上创建集群。
+ [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) 使对 Kubernetes 集群运行命令成为可能。
+ [Docker](https://www.docker.com/) 帮助您在名为容器的软件包中构建、测试和交付应用程序。

## 操作说明
<a name="deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-epics"></a>

### 使用 eksctl 创建 Amazon EKS 集群
<a name="create-an-amazon-eks-cluster-by-using-eksctl"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个 Amazon EKS 集群。 | 要创建使用两个 t2.small Amazon EC2 实例作为节点的 Amazon EKS 集群，请运行以下命令：<pre>eksctl create cluster --name <your-cluster-name> --version <version-number> --nodes=1 --node-type=t2.small</pre>该过程可能需要 15 到 20 分钟。创建集群后，相应的 Kubernetes 配置将添加至您的 [kubeconfig](https://docs.aws.amazon.com/eks/latest/userguide/create-kubeconfig.html) 文件中。您可将该 `kubeconfig` 文件与 `kubectl` ****一起使用，以便在后续步骤中部署应用程序。 | 开发人员、系统管理员 | 
| 验证 Amazon EKS 集群。 | 要验证集群是否已创建并且您可连接到该集群，请运行 `kubectl get nodes` 命令。 | 开发人员、系统管理员 | 

### 创建 Amazon ECR 存储库并推送 Docker 映像。
<a name="create-an-amazon-ecr-repository-and-push-the-docker-image"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon ECR 存储库。 | 请遵循 Amazon ECR 文档中的[创建私有存储库](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)的说明操作。 | 开发人员、系统管理员 | 
| 创建 POM XML 文件。 | 根据此模式的[其他信息](#deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-additional)部分中的*示例 POM 文件*代码创建 `pom.xml` 文件。 | 开发人员、系统管理员 | 
| 创建源文件。 | 根据以下示例，按 `src/main/java/eksExample` 路径创建名为 `HelloWorld.java` 的源文件。<pre>package eksExample;<br />import static spark.Spark.get;<br /><br />public class HelloWorld {<br />    public static void main(String[] args) {<br />        get("/", (req, res) -> {<br />            return "Hello World!";<br />        });<br />    }<br />}</pre>请确保采用以下目录结构：<pre>├── Dockerfile<br />├── deployment.yaml<br />├── ingress.yaml<br />├── pom.xml<br />├── service.yaml<br />└── src<br />    └── main<br />        └── java<br />            └── eksExample<br />                └── HelloWorld.java</pre> |  | 
| 创建 Dockerfile。 | 根据此模式的[其他信息](#deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-additional)部分中的*示例 Dockerfile*代码创建 `Dockerfile`。 | 开发人员、系统管理员 | 
| 构建和推送 Docker 映像。 | 在您想要 `Dockerfile` 构建、标记映像并将其推送至 Amazon ECR 的目录中，运行以下命令：<pre>aws ecr get-login-password --region <region>| docker login --username <username> --password-stdin <account_number>.dkr.ecr.<region>.amazonaws.com<br />docker buildx build --platform linux/amd64 -t hello-world-java:v1 .<br />docker tag hello-world-java:v1 <account_number>.dkr.ecr.<region>.amazonaws.com/<repository_name>:v1<br />docker push <account_number>.dkr.ecr.<region>.amazonaws.com/<repository_name>:v1</pre>在上述命令中修改 AWS 区域 、账号和存储库详细信息。请务必记下图片网 URL，以备日后使用。搭载 M1 芯片的 macOS 系统在构建与平台上运行的 Amazon EKS 兼容的映像时出现问题。 AMD64 要解决此问题，请使用 [docker buildx](https://docs.docker.com/engine/reference/commandline/buildx/)构建可在 Amazon EKS 上运行的 Docker 映像。 |  | 

### 部署 Java 微服务
<a name="deploy-the-java-microservices"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建部署文件。 | 根据此模式的[其他信息](#deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-additional)部分中的*示例部署文件*代码创建名为 `deployment.yaml` 的 YAML 文件。使用您之前复制的图片 URL 作为 Amazon ECR 存储库的映像文件路径。 | 开发人员、系统管理员 | 
| 在Amazon EKS 集群上部署 Java 微服务。 | 要在您的 Amazon EKS 集群中创建部署，请运行 `kubectl apply -f deployment.yaml` 命令。 | 开发人员、系统管理员 | 
| 验证容器组（pod）的状态。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer.html) | 开发人员、系统管理员 | 
| 创建服务。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer.html) | 开发人员、系统管理员 | 
| 安装 AWS Load Balancer Controller 附加组件。 | 按照 Amazon EKS 文档中的[安装 AWS Load Balancer Controller 附加组件](https://docs.aws.amazon.com/eks/latest/userguide/aws-load-balancer-controller.html)进行操作。您必须安装插件，才能为 Kubernetes 服务创建应用程序负载均衡器或网络负载均衡器。 | 开发人员、系统管理员 | 
| 创建入口资源。 | 根据此模式的[其他信息](#deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-additional)部分中的*示例入口资源文件*代码创建名为 `ingress.yaml` 的 YAML 文件。 | 开发人员、系统管理员 | 
| 创建应用程序负载均衡器。 | 要部署入口资源并创建应用程序负载均衡器，请运行 `kubectl apply -f ingress.yaml` 命令。 | 开发人员、系统管理员 | 

### 测试应用程序
<a name="test-the-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 测试和验证应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer.html) | 开发人员、系统管理员 | 

## 相关资源
<a name="deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-resources"></a>
+ [创建私有存储库](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)（Amazon ECR 文档）
+ [推送 Docker 映像](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)（Amazon ECR 文档）
+ [入口控制器](https://www.eksworkshop.com/beginner/130_exposing-service/ingress_controller_alb/)（Amazon EKS Workshop）
+ [Docker buildx](https://docs.docker.com/engine/reference/commandline/buildx/)（Docker 文档）

## 附加信息
<a name="deploy-a-sample-java-microservice-on-amazon-eks-and-expose-the-microservice-using-an-application-load-balancer-additional"></a>

**POM 文件示例**

```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>


  <groupId>helloWorld</groupId>
  <artifactId>helloWorld</artifactId>
  <version>1.0-SNAPSHOT</version>


  <dependencies>
    <dependency>
      <groupId>com.sparkjava</groupId><artifactId>spark-core</artifactId><version>2.0.0</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId><artifactId>maven-jar-plugin</artifactId><version>2.4</version>
        <configuration><finalName>eksExample</finalName><archive><manifest>
              <addClasspath>true</addClasspath><mainClass>eksExample.HelloWorld</mainClass><classpathPrefix>dependency-jars/</classpathPrefix>
            </manifest></archive>
        </configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.1</version>
        <configuration><source>1.8</source><target>1.8</target></configuration>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId><artifactId>maven-assembly-plugin</artifactId>
        <executions>
          <execution>
            <goals><goal>attached</goal></goals><phase>package</phase>
            <configuration>
              <finalName>eksExample</finalName>
              <descriptorRefs><descriptorRef>jar-with-dependencies</descriptorRef></descriptorRefs>
              <archive><manifest><mainClass>eksExample.HelloWorld</mainClass></manifest></archive>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>
```

**Dockerfile 示例**

```
FROM bellsoft/liberica-openjdk-alpine-musl:17

RUN apk add maven
WORKDIR /code

# Prepare by downloading dependencies
ADD pom.xml /code/pom.xml
RUN ["mvn", "dependency:resolve"]
RUN ["mvn", "verify"]

# Adding source, compile and package into a fat jar
ADD src /code/src
RUN ["mvn", "package"]

EXPOSE 4567
CMD ["java", "-jar", "target/eksExample-jar-with-dependencies.jar"]
```

**部署文件示例**

```
apiVersion: apps/v1
kind: Deployment
metadata:
  name: microservice-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app.kubernetes.io/name: java-microservice
  template:
    metadata:
      labels:
        app.kubernetes.io/name: java-microservice
    spec:
      containers:
      - name: java-microservice-container
        image: .dkr.ecr.amazonaws.com/:
        ports:
        - containerPort: 4567
```

**示例服务文件**

```
apiVersion: v1
kind: Service
metadata:
  name: "service-java-microservice"
spec:
  ports:
    - port: 80
      targetPort: 4567
      protocol: TCP
  type: NodePort
  selector:
    app.kubernetes.io/name: java-microservice
```

**入口资源文件示例**

```
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: "java-microservice-ingress"
  annotations:
    kubernetes.io/ingress.class: alb
    alb.ingress.kubernetes.io/load-balancer-name: apg2
    alb.ingress.kubernetes.io/target-type: ip
  labels:
    app: java-microservice
spec:
  rules:
    - http:
        paths:
          - path: /
            pathType: Prefix
            backend:
              service:
                name: "service-java-microservice"
                port:
                  number: 80
```

# 在 Amazon EKS 集群上部署基于 gRPC 的应用程序并使用应用程序负载均衡器访问它
<a name="deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer"></a>

*Kirankumar Chandrashekar 和 Huy Nguyen，Amazon Web Services*

## Summary
<a name="deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer-summary"></a>

此模式描述如何在 Amazon Elastic Kubernetes Service (Amazon EKS) 集群上托管基于 gRPC 的应用程序，并通过应用程序负载均衡器安全地访问该应用程序。

[gRPC](https://grpc.io/) 是一个开源远程过程调用 (RPC) 框架，可以在任何环境中运行。您可将其用于微服务集成和客户端-服务器通信。有关 gRPC 的更多信息，请参阅 AWS 博客文章 App [lication Load Balancer 对 end-to-end HTTP/2 和 gRPC 的支持](https://aws.amazon.com/blogs/aws/new-application-load-balancer-support-for-end-to-end-http-2-and-grpc/)。

此模式向您介绍如何在 Amazon EKS 上托管作为 Kubernetes 容器组（pod）运行的基于 gRPC 的应用程序。gRPC 客户端通过加密连接通过 HTTP/2 协议连接到 Application Load Balancer。 SSL/TLS 应用程序负载均衡器将流量转发至 Amazon EKS 容器组（pod）上运行的 gRPC 应用程序。使用 [Kubernetes Horizontal Pod Autoscaler](https://docs.aws.amazon.com/eks/latest/userguide/horizontal-pod-autoscaler.html)，可以根据流量自动扩缩 gRPC 容器组（pod）的数量。应用程序负载均衡器的目标组对 Amazon EKS 节点执行运行状况检查，评估目标是否运行状况良好，并且仅将流量转发到运行状况良好的节点。

## 先决条件和限制
<a name="deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ [Docker](https://www.docker.com/)，已在 Linux、macOS 或 Windows 上安装并配置。
+ [AWS 命令行界面（AWS CLI）版本 2](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)，已在 Linux、macOS 或 Windows 上安装并配置。
+ [eksctl](https://github.com/eksctl-io/eksctl#installation)，已在 Linux、macOS 或 Windows 上安装并配置。
+ `kubectl`，已安装并配置为访问 Amazon EKS 集群上的资源。有关更多信息，请参阅 Amazon EKS 文档中的[安装或更新 kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)。 
+ [g RPCurl](https://github.com/fullstorydev/grpcurl)，已安装并配置。
+ 新的或现有的 Amazon EKS 集群。有关更多信息，请参阅 [Amazon EKS 入门](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html)。
+ 您的计算机终端被配置为访问 Amazon EKS 集群。有关详情，请参阅 Amazon EKS 文档中的[将计算机配置为与您的集群通信](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-console.html#eks-configure-kubectl)。
+ [AWS Load Balancer Controller](https://docs.aws.amazon.com/eks/latest/userguide/aws-load-balancer-controller.html)，在 Amazon EKS 集群中配备。
+ 具有有效 SSL 或 SSL/TLS 证书的现有 DNS 主机名。您可通过使用 AWS Certificate Manager (ACM) 或将现有证书上载到 ACM 获取域证书。有关这两个选项的更多信息，请参阅 ACM 文档中的[请求公共证书](https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-public.html)和[将证书导入 AWS Certificate Manager](https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html)。

## 架构
<a name="deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer-architecture"></a>

下图显示了此模式实施的架构。

![\[在 Amazon EKS 上的基于 gRPC 的应用程序的架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/abf727c1-ff8b-43a7-923f-bce825d1b459/images/281936fa-bc43-4b4e-a343-ba1eab97df38.png)


 

下图显示了一个工作流程，其中从 gRPC 客户端接收 SSL/TLS 流量，然后将其卸载到 Application Load Balancer。由于流量来自虚拟私有云（VPC），因此以明文形式转发到 gRPC 服务器。

![\[向 gRP SSL/TLS C 服务器发送流量的工作流程\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/abf727c1-ff8b-43a7-923f-bce825d1b459/images/09e0c3f6-0c39-40b7-908f-8c4c693a5f02.png)


## 工具
<a name="deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer-tools"></a>

**AWS 服务**
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它可帮助您通过命令行 Shell 中的命令与 Amazon Web Services 交互。
+ [弹性负载均衡](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html)在多个目标上分配传入的应用程序或网络流量。例如您可以将流量分配到一个或多个可用区中的 Amazon Elastic Compute Cloud (Amazon EC2) 实例、容器以及 IP 地址。
+ [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 是一项安全、可扩展且可靠的托管容器映像注册表服务。 
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) 可帮助您在 AWS 上运行 Kubernetes，而无需安装或维护您自己的 Kubernetes 控制面板或节点。 

**工具**
+ [eksctl](https://eksctl.io/) 是一个用于在 Amazon EKS 上创建集群的简单 CLI 工具。
+ [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) 是针对 Kubernetes 集群运行命令的命令行实用程序。
+ [AWS 负载均衡器控制器](https://docs.aws.amazon.com/eks/latest/userguide/aws-load-balancer-controller.html)帮助管理 Kubernetes 集群的 AWS 弹性负载均衡器。
+ [g RPCurl](https://github.com/fullstorydev/grpcurl) 是一个命令行工具，可帮助您与 gRPC 服务进行交互。

**代码存储库**

此模式的代码可在 to-e GitHub [grpc-traffic-on-albks 存储库中找到](https://github.com/aws-samples/grpc-traffic-on-alb-to-eks.git)。

## 操作说明
<a name="deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer-epics"></a>

### 构建 gRPC 服务器的 Docker 映像并将其推送到 Amazon ECR
<a name="build-and-push-the-grpc-serverrsquor-s-docker-image-to-amazon-ecr"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon ECR 存储库。 | 登录 AWS 管理控制台并打开[ Amazon ECR 控制台](https://console.aws.amazon.com/ecr/)，然后创建 Amazon ECR 存储库。有关更多信息，请参阅 Amazon ECR 文档中的[创建存储库](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)。请务必记录 Amazon ECR 存储库的 URL。您也可以通过运行以下命令，使用 AWS CLI 创建 Amazon ECR 存储库：<pre>aws ecr create-repository --repository-name helloworld-grpc</pre> | 云管理员 | 
| 构建 Docker 映像。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer.html) | DevOps 工程师 | 
| 将 Docker 映像推送到 Amazon ECR。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer.html) | DevOps 工程师 | 

### 将 Kubernetes 清单部署到 Amazon EKS 集群
<a name="deploy-the-kubernetes-manifests-to-the-amazon-eks-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 修改 Kubernetes 清单文件值。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer.html) | DevOps 工程师 | 
| 部署 Kubernetes 清单文件。 | 通过运行以下 `kubectl` 命令，将 `grpc-sample.yaml` 文件部署到 Amazon EKS 集群： <pre>kubectl apply -f ./kubernetes/grpc-sample.yaml</pre> | DevOps 工程师 | 

### 为应用程序负载均衡器的 FQDN 创建 DNS 记录
<a name="create-the-dns-record-for-the-application-load-balancerapos-s-fqdn"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 应用程序负载均衡器的 FQDN 记录。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer.html) | DevOps 工程师 | 

### 测试解决方案
<a name="test-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 测试 gRPC 服务器。 | 使用 g 通过运行以下命令RPCurl 来测试端点：<pre>grpcurl grpc.example.com:443 list <br />grpc.reflection.v1alpha.ServerReflection<br />helloworld.helloworld</pre>将 `grpc.example.com` 替换为您的 DNS 名称。 | DevOps 工程师 | 
| 使用 gRPC 客户端测试 gRPC 服务器。 | 在 `helloworld_client_ssl.py` 示例 gRPC 客户端中，将 `grpc.example.com` 中的主机名替换为用于 gRPC 服务器的主机名。 下列代码示例显示了 gRPC 服务器对客户端请求的响应：<pre>python ./app/helloworld_client_ssl.py<br />message: "Hello to gRPC server from Client"<br /><br />message: "Thanks for talking to gRPC server!! Welcome to hello world. Received message is \"Hello to gRPC server from Client\""<br />received: true</pre>这表明客户端可与服务器通信，并且连接成功。 | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 移除 DNS 记录。 | 移除指向您之前创建的应用程序负载均衡器的 FQDN 的 DNS 记录。 | 云管理员 | 
| 移除负载均衡器。 | 在 [Amazon EC2 控制台](https://console.aws.amazon.com/ec2/)上，选择**负载均衡器**，然后移除 Kubernetes 控制器为您的入口资源创建的负载均衡器。 | 云管理员 | 
| 删除 Amazon EKS 集群。 | 使用 `eksctl` 删除 Amazon EKS 集群：<pre>eksctl delete cluster -f ./eks.yaml</pre> | AWS DevOps | 

## 相关资源
<a name="deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer-resources"></a>
+ [Amazon EKS 上的网络负载均衡器](https://docs.aws.amazon.com/eks/latest/userguide/load-balancing.html)
+ [应用程序负载均衡器的目标组](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-target-groups.html#target-group-protocol-version)

## 附加信息
<a name="deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer-additional"></a>

**入口资源示例：**

```
---
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  annotations:
    alb.ingress.kubernetes.io/healthcheck-protocol: HTTP
    alb.ingress.kubernetes.io/ssl-redirect: "443"
    alb.ingress.kubernetes.io/backend-protocol-version: "GRPC"
    alb.ingress.kubernetes.io/listen-ports: '[{"HTTP": 80}, {"HTTPS":443}]'
    alb.ingress.kubernetes.io/scheme: internet-facing
    alb.ingress.kubernetes.io/target-type: ip
    alb.ingress.kubernetes.io/certificate-arn: arn:aws:acm:<AWS-Region>:<AccountId>:certificate/<certificate_ID>
  labels:
    app: grpcserver
    environment: dev
  name: grpcserver
  namespace: grpcserver
spec:
  ingressClassName: alb
  rules:
  - host: grpc.example.com # <----- replace this as per your host name for which the SSL certtficate is available in ACM
    http:
      paths:
      - backend:
          service:
            name: grpcserver
            port:
              number: 9000
        path: /
        pathType: Prefix
```

**部署资源示例：**

```
apiVersion: apps/v1
kind: Deployment
metadata:
  name: grpcserver
  namespace: grpcserver
spec:
  selector:
    matchLabels:
      app: grpcserver
  replicas: 1
  template:
    metadata:
      labels:
        app: grpcserver
    spec:
      containers:
      - name: grpc-demo
        image: <your_aws_account_id>.dkr.ecr.us-east-1.amazonaws.com/helloworld-grpc:1.0   #<------- Change to the URI that the Docker image is pushed to
        imagePullPolicy: Always
        ports:
        - name: grpc-api
          containerPort: 9000
        env:
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
      restartPolicy: Always
```

**示例输出**：

```
NAME             CLASS           HOSTS                          Address                PORTS          AGE
 grpcserver      <none>      <DNS-HostName>                  <ELB-address>              80            27d
```

# 在作为 Docker 容器 AWS IoT Greengrass V2 运行时部署容器化应用程序
<a name="deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container"></a>

*亚马逊 Web Services 的 Salih Bakir、Giuseppe Di Bella 和 Gustav Svalander*

## Summary
<a name="deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container-summary"></a>

AWS IoT Greengrass Version 2，当部署为 Docker 容器时，本机不支持运行 Docker 应用程序容器。此模式向您展示如何基于启用 Docker-in-Docker (DinD) 功能的最新版本创建自定义容器镜像。 AWS IoT Greengrass V2 借助 DinD，您可以在环境中运行容器化应用程序。 AWS IoT Greengrass V2 

您可以将此模式部署为独立解决方案，也可以将其与 Amazon ECS Anywhere 等容器编排平台集成。在这两种部署模式中，您都可以保持包括 AWS IoT SiteWise 边缘处理 AWS IoT Greengrass V2 功能在内的全部功能，同时支持基于容器的可扩展部署。

## 先决条件和限制
<a name="deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ 有关一般 AWS IoT Greengrass Version 2 先决条件，请参阅 AWS IoT Greengrass Version 2 文档中的[先决条件](https://docs.aws.amazon.com/greengrass/v2/developerguide/getting-started-prerequisites.html)。
+ Docker Engine，在 Linux、macOS 或 Windows 上安装和配置。
+ Docker Compose（如果你使用 Docker Compose 命令行界面 (CLI) 来运行 Docker 镜像）。
+ 一个 Linux 操作系统。
+ 带有支持虚拟化的主机服务器的虚拟机管理程序。
+ 系统要求：
  + 2 GB 内存（最小值）
  + 5 GB 可用磁盘空间（最小）
  + 对于 AWS IoT SiteWise Edge，这是一款具有 16 GB 内存和 50 GB 可用磁盘空间的 x86\$164 四核 CPU。有关 AWS IoT SiteWise 数据处理的更多信息，请参阅 AWS IoT SiteWise 文档中的[数据处理包要求](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/configure-gateway-ggv2.html#w2aac17c19c13b7)。

**产品版本**
+ AWS IoT Greengrass Version 2 版本 2.5.3 或更高版本
+ Docker-in-Docker 版本 1.0.0 或更高版本
+ Docker Compose 版本 1.22 或更高版本
+ Docker Engine 版本 20.10.12 或更高版本

**限制**
+ 有些 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="deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container-architecture"></a>

**目标技术堆栈**
+ **数据源** — 生成数据进行处理的物联网设备、传感器或工业设备
+ **AWS IoT Greengrass V2**— 作为具有 D-in-D功能的 Docker 容器运行，部署在边缘基础架构上
+ **容器化应用程序** — 作为嵌套 Docker 容器在 AWS IoT Greengrass V2 环境中运行的自定义应用程序
+ **（可选）Amazon ECS Anywhere** — 管理容器部署的 AWS IoT Greengrass V2 容器编排
+ **其他 AWS 服务** — AWS IoT Core AWS IoT SiteWise、以及其他 AWS 服务 用于数据处理和管理

**目标架构 **

下图显示了使用 Amazon ECS Anywhere（一种容器管理工具）的目标部署架构示例。

![\[使用 Amazon ECS Anywhere 部署架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/2ecf5354-40e0-4fd9-9798-086719059784/images/5ed2652e-9604-4809-8962-b167e1991658.png)


下图显示了如下工作流：

**1：容器映像存储** — Amazon ECR 存储边缘处理所需的容器映像和任何自定义应用程序容器。 AWS IoT Greengrass 

**2** 和 **3：容器部署** — Amazon ECS Anywhere 将 AWS IoT Greengrass 容器映像从 Amazon ECR 部署到边缘站点，管理容器生命周期和部署过程。

**4：组件部署** — 已部署的 AWS IoT Greengrass 核心会根据其配置自动部署其相关组件。组件包括 AWS IoT SiteWise 容器化环境中的 Edge 和其他必要的边缘处理组件。

**5：数据摄取** — 完全配置完毕后， AWS IoT Greengrass 开始从边缘位置的各种 IoT 数据源提取遥测和传感器数据。

**6：数据处理和云集成** — 容器化 AWS IoT Greengrass 核心使用其部署的组件（包括用于工业数据的 AWS IoT SiteWise 边缘）在本地处理数据。然后，它将处理后的数据发送到 AWS 云 服务部门进行进一步分析和存储。

## 工具
<a name="deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container-tools"></a>

**AWS 服务**
+ [Amazon ECS Anywhere](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch-type-external.html) 可帮助您在自己的基础设施上部署、使用和管理亚马逊 ECS 任务和服务。
+ [亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) 在中提供可扩展的计算容量 AWS 云。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [Amazon Elastic Container Registry（Amazon ECR）](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)是一项安全、可扩展且可靠的托管容器映像注册表服务。
+ [AWS IoT Greengrass](https://docs.aws.amazon.com/greengrass/v2/developerguide/what-is-iot-greengrass.html) 是一项开源物联网（IoT）边缘运行时和云服务，可帮助您在设备上构建、部署和管理 IoT 应用程序。
+ [AWS IoT SiteWise](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/what-is-sitewise.html) 可帮您大规模采集、建模、分析和可视化显示来自工业设备的数据。

**其他工具**
+ [Docker](https://www.docker.com/) 是一组平台即服务（PaaS）产品，它们利用操作系统级的虚拟化技术在容器中提供软件。
+ [Docker Compose](https://docs.docker.com/compose/) 是一款工具，用于定义和运行多容器应用程序。
+ [Docker Engin](https://docs.docker.com/engine/) e 是一种开源容器化技术，用于构建和容器化应用程序。

**代码存储库**

此模式的代码可在 GitHub [AWS IoT Greengrass v2 Docker-in-Docker](https://github.com/aws-samples/aws-iot-greengrass-docker-in-docker) 存储库中找到。

## 操作说明
<a name="deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container-epics"></a>

### 构建 AWS IoT Greengrass V2 Docker-in-Docker 镜像
<a name="build-the-gg2-docker-in-docker-image"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆并导航到存储库。 | 要克隆存储库，请使用以下命令：`git clone https://github.com/aws-samples/aws-iot-greengrass-v2-docker-in-docker.git`要导航到该`docker`目录，请使用以下命令：`cd aws-iot-greengrass-v2-docker-in-docker/docker` | DevOps 工程师，AWS DevOps | 
| 构建 Docker 映像。 | 要使用默认（最新）版本构建 Docker 镜像，请运行以下命令：`docker build -t x86_64/aws-iot-greengrass:latest .`或者，要使用特定版本构建 Docker 镜像，请运行以下命令：`docker build --build-arg GREENGRASS_RELEASE_VERSION=2.12.0 -t x86_64/aws-iot-greengrass:2.12.0 .`要验证构建，请运行以下命令：`docker images \| grep aws-iot-greengrass`  | AWS DevOps， DevOps 工程师，应用程序开发人员 | 
| （可选）推送到 Amazon ECR。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | 应用程序开发人员、AWS DevOps、 DevOps 工程师 | 

### 配置 AWS 凭证
<a name="configure-aws-credentials"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 选择身份验证方法。 | 请选择以下选项之一：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | AWS 管理员 | 
| 配置身份验证方法。 | 对于您选择的身份验证方法，请使用以下配置指南：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | AWS 管理员 | 

### 使用 Docker Compose 运行
<a name="run-with-docker-compose"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| Configure `docker-compose.yml`。 | 使用环境变量更新`docker-compose.yml`文件，如下所示：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | DevOps 工程师 | 
| 启动并验证容器。 | 要从前台开始，请运行以下命令：`docker-compose up --build`或者，要在后台启动，请运行以下命令：`docker-compose up --build -d`要验证状态，请运行以下命令：`docker-compose ps`要监控日志，请运行以下命令：`docker-compose logs -f` | DevOps 工程师 | 

### 使用 Docker CLI 运行
<a name="run-with-docker-cli"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 Docker CLI 运行容器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | DevOps 工程师 | 
| 验证容器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | DevOps 工程师 | 

### 管理容器化应用程序
<a name="manage-containerized-applications"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | 应用程序开发人员 | 
| 访问和测试 Docker-in-Docker。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | DevOps 工程师 | 

### （可选）与 Amazon ECS Anywhere 集成
<a name="optional-integrate-with-ecs-anywhere"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 Amazon ECS 集群。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | AWS 管理员 | 
| 部署 Amazon ECS 任务。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | AWS 管理员 | 

### 停下来清理
<a name="stop-and-cleanup"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 停止容器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | DevOps 工程师 | 

## 问题排查
<a name="deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 容器启动失败，出现权限错误。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)`--privileged`向容器授予扩展权限。 | 
| 由于凭据错误，置备失败。 | 要验证凭据配置是否正确，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)确保 IAM 权限包括`iot:CreateThing``iot:CreatePolicy`、`iot:AttachPolicy`、`iam:CreateRole`、和`iam:AttachRolePolicy`。 | 
| 无法连接到容器内的 Docker 守护程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | 
| 容器的磁盘空间不足。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)确保最小磁盘空间：5 GB 用于基本操作，50 GB 用于 AWS IoT SiteWise 边缘操作 | 
| 构建问题。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html) | 
| 网络连接问题。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)验证防火墙是否允许出站 HTTPS (443) 和 MQTT (8883) 流量。 | 
| Greengrass 组件无法部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)检查目录中特定于组件的`/greengrass/v2/logs/`日志。 | 
| 容器启动后立即退出。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.html)验证是否正确设置了所有必需的环境变量`PROVISION=true`。确保在启动容器时使用该`--init`标志。 | 

## 相关资源
<a name="deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container-resources"></a>

**AWS resources**
+ [Amazon Elastic Container Service](https://aws.amazon.com/ecs/)
+ [为 AWS IoT SiteWise 模型和资产配置边缘数据处理](https://docs.aws.amazon.com/iot-sitewise/latest/userguide/edge-processing.html)
+ [什么是 AWS IoT Greengrass](https://docs.aws.amazon.com/greengrass/v2/developerguide/what-is-iot-greengrass.html)

**其他资源**
+ [Docker 文档](https://docs.docker.com/)

## 附加信息
<a name="deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container-additional"></a>
+ 要进行 AWS IoT SiteWise 边缘数据处理，Docker 必须在 AWS IoT Greengrass 环境中可用。
+ 要运行嵌套容器，必须使用管理员级别的凭 AWS IoT Greengrass 据运行该容器。

# 使用 Elastic Beanstalk 部署容器
<a name="deploy-containers-by-using-elastic-beanstalk"></a>

*Thomas Scott 和 Jean-Baptiste Guillois，Amazon Web Services*

## Summary
<a name="deploy-containers-by-using-elastic-beanstalk-summary"></a>

在 Amazon Web Services（AWS）Cloud 上，AWS Elastic Beanstalk 支持 Docker 作为可用平台，因此容器可以在创建的环境中运行。此模式展示了如何使用 Elastic Beanstalk 服务部署容器。此模式的部署将使用基于 Docker 平台的 Web 服务器环境。

要使用 Elastic Beanstalk 部署和扩展 Web 应用程序和服务，您需要上传代码，部署就会自动处理。还包括容量预调配、负载均衡、自动扩缩和应用程序运行状况监控。当您使用 Elastic Beanstalk 时，您可以完全控制它代表您创建的 AWS 资源。Elastic Beanstalk 不收取额外费用。您只需为用于存储和运行应用程序的 AWS 资源付费。

此模式包括使用 [AWS Elastic Beanstalk 命令行界面（EB CLI）](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install-advanced.html)和 AWS 管理控制台 进行部署的说明。

**使用案例**

Elastic Beanstalk 的使用场景包括： 
+ 部署原型环境来演示前端应用程序。（此模式以 Dockerfile** **为例。）
+ 部署 API 来处理给定域名的 API 请求。
+ 使用 Docker-Compose 部署编排解决方案（在此模式中 `docker-compose.yml` ** **未用作实际示例）。

## 先决条件和限制
<a name="deploy-containers-by-using-elastic-beanstalk-prereqs"></a>

**先决条件**
+ Amazon Web Services account 
+ 本地已安装 AWS EB CLI
+ Docker 已安装在本地机器上

**限制**
+ 在免费套餐中，每个 IP 地址的 Docker 拉取限制为每 6 小时拉取 100 次。

## 架构
<a name="deploy-containers-by-using-elastic-beanstalk-architecture"></a>

**目标技术堆栈**
+ 亚马逊弹性计算云 (Amazon EC2) 实例
+ 安全组
+ 应用程序负载均衡器
+ 自动扩缩组

**目标架构 **

![\[使用 Elastic Beanstalk 部署容器的架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/dfabcdc2-747f-40e2-a603-08ea31ba71d3/images/1d17ff09-1aea-4c72-adb5-eaf741601428.png)


**自动化和扩展**

AWS Elastic Beanstalk 可以根据发出的请求数自动扩缩。为环境创建的 AWS 资源包括一个 Application Load Balancer、一个 Auto Scaling 组和一个或多个 Amazon EC2 实例。 

负载均衡器位于作为 Auto Scaling 组一部分的 Amazon EC2 实例的前面。Amazon A EC2 uto Scaling 会自动启动额外的亚马逊 EC2 实例，以适应应用程序不断增加的负载。如果您的应用程序的负载减少，Amazon A EC2 uto Scaling 会停止实例，但它会使至少一个实例保持运行。

**自动扩缩触发器**

您的 Elastic Beanstalk 环境中的 Auto Scaling 组使用 CloudWatch 两个亚马逊警报来启动扩展操作。当每个实例的平均出站网络流量在 5 分钟时间段内高于 6 MB 或低于 2 MB 时，默认触发器将扩展。要有效地使用 Amazon A EC2 uto Scaling，请配置适合您的应用程序、实例类型和服务要求的触发器。您可以基于若干个统计数据 (包括延迟、磁盘 I/O、CPU 使用率和请求计数) 来进行扩展。有关更多信息，请参阅[自动扩缩触发器](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environments-cfg-autoscaling-triggers.html)。

## 工具
<a name="deploy-containers-by-using-elastic-beanstalk-tools"></a>

**Amazon Web Services**
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它可帮助您通过命令行 Shell 中的命令与 Amazon Web Services 交互。
+ [AWS EB 命令行界面 (EB CLI)](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html) 是一个可用来创建、配置和管理 Elastic Beanstalk 环境的命令行客户端。
+ [弹性负载均衡](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html)将传入的应用程序或网络流量分发到多个目标。例如，您可以跨亚马逊弹性计算云 (Amazon EC2) 实例、容器以及一个或多个可用区中的 IP 地址分配流量。

**其他服务**
+ [Docker](https://www.docker.com/) 将软件打包成称为容器的标准化单元，其中包括库、系统工具、代码和运行时系统。

**代码**

此模式的代码可在 GitHub [集群示例应用程序](https://github.com/aws-samples/cluster-sample-app)存储库中找到。

## 操作说明
<a name="deploy-containers-by-using-elastic-beanstalk-epics"></a>

### 使用 Dockerfile 构建
<a name="build-with-a-dockerfile"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆远程存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containers-by-using-elastic-beanstalk.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 初始化 Elastic Beanstalk Docker 项目。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containers-by-using-elastic-beanstalk.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 在本地测试项目。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containers-by-using-elastic-beanstalk.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 

### 使用 EB CLI 进行部署
<a name="deploy-using-eb-cli"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 运行部署命令 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containers-by-using-elastic-beanstalk.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 访问已部署的版本。 | 部署命令完成后，使用该 `eb open`命令访问项目。 | 应用程序开发人员、AWS 管理员、AWS DevOps | 

### 使用控制台进行部署
<a name="deploy-using-the-console"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用浏览器部署应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-containers-by-using-elastic-beanstalk.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 访问已部署的版本。 | 部署后，访问已部署的应用程序，然后选择提供的 URL。 | 应用程序开发人员、AWS 管理员、AWS DevOps | 

## 相关资源
<a name="deploy-containers-by-using-elastic-beanstalk-resources"></a>
+ [Web 服务器环境](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/concepts-webserver.html)
+ [在 macOS 上安装 EB CLI](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install-osx.html)
+ [手动安装 EB CLI](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install-advanced.html)

## 附加信息
<a name="deploy-containers-by-using-elastic-beanstalk-additional"></a>

**使用 Elastic Beanstalk 的好处**
+ 自动预调配基础设施
+ 自动管理底层平台
+ 自动修补和更新以支持应用程序
+ 自动扩缩应用程序
+ 能够自定义节点数
+ 能够在需要时访问基础设施组件
+ 与其他容器部署解决方案相比，易于部署

# 使用 Lambda 函数、Amazon VPC 和无服务器架构生成静态出站 IP 地址
<a name="generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture"></a>

*Thomas Scott，Amazon Web Services*

## Summary
<a name="generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture-summary"></a>

此模式描述如何使用无服务器架构在 Amazon Web Services (AWS) Cloud 中生成静态出站 IP 地址。如果您的组织想要使用安全文件传输协议 (SFTP) 将文件发送到单独的业务实体，则可以从此方法中受益。这意味着业务实体必须有权访问允许文件通过防火墙的 IP 地址。 

该模式的方法可以帮助您创建使用[弹性 IP 地址](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)作为出站 IP 地址的 AWS Lambda 函数。通过遵循此模式中的步骤，您可以创建 Lambda 函数和虚拟私有云（VPC），通过具有静态 IP 地址的互联网网关路由出站流量。要使用静态 IP 地址，您可将 Lambda 函数附加到 VPC 及其子网。 

## 先决条件和限制
<a name="generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account。 
+ AWS Identity and Access Management (IAM) 权限，用于创建和部署 Lambda 函数，以创建 VPC 及其子网。有关这方面的更多信息，请参阅 AWS Lambda 文档中的[执行角色和用户权限](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html#vpc-permissions)。
+ 如果您计划使用基础设施即代码（IaC）实施此模式的方法，则需要集成式开发环境（IDE），例如 AWS Cloud9。有关这方面的更多信息，请参阅 AWS Cloud9 文档中的 [AWS Cloud9 是什么？](https://docs.aws.amazon.com/cloud9/latest/user-guide/welcome.html)。

## 架构
<a name="generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture-architecture"></a>

下图显示此模式的无服务器架构。

![\[AWS 云 VPC architecture with two availability zones, public and private subnets, NAT gateways, and a Lambda function.\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/eb1d0b05-df33-45ae-b27e-36090055b300/images/c15cc6da-ce4e-4ea0-9feb-de1c845d3ce8.png)


下图显示了如下工作流：

1. 出站流量离开 `Public subnet 1` 中的 `NAT gateway 1`。

1. 出站流量离开 `Public subnet 2` 中的 `NAT gateway 2`。

1. Lambda 函数可在 `Private subnet 1` 或 `Private subnet 2` 中运行。

1. `Private subnet 1` 和 `Private subnet 2` 将流量路由到公有子网中的 NAT 网关。

1. NAT 网关将出站流量从公共子网发送至互联网网关。

1. 出站数据从互联网网关传输至外部服务器。



**技术堆栈**
+ Lambda
+ Amazon Virtual Private Cloud (Amazon VPC)

 

**自动化和扩缩**

您可以通过在不同的可用区使用两个公有子网和两个私有子网，确保高可用性 (HA)。即使一个可用区不可用，该模式的解决方案仍能继续发挥作用。

## 工具
<a name="generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture-tools"></a>
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) – AWS Lambda 是一项计算服务，支持无需预置或管理服务器即可运行代码。只有在需要时 Lambda 才运行您的代码，并且能自动扩缩，从每天几个请求扩展到每秒数千个请求。您只需为消耗的计算时间付费 - 代码未运行时不产生费用。
+ [Amazon VPC](https://docs.aws.amazon.com/vpc/) – Amazon Virtual Private Cloud (Amazon VPC) 预调配 Amazon Web Services Cloud 的逻辑隔离部分，您可以在其中启动您定义的虚拟网络中的 AWS 资源。此虚拟网络与您在自己的数据中心中运营的传统网络极其相似，您将获得使用 AWS 可扩展基础设施的优势。

## 操作说明
<a name="generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture-epics"></a>

### 创建新的 VPC
<a name="create-a-new-vpc"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建新的 VPC。 | 登录 AWS 管理控制台，打开 Amazon VPC 控制台，然后创建一个名为 `Lambda VPC` IPv4 CIDR 范围的 VPC。`10.0.0.0/25`****有关创建 VPC 的更多信息，请参阅 Amazon VPC 文档中的 [Amazon VPC 入门](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-getting-started.html#getting-started-create-vpc)。  | AWS 管理员 | 

### 创建两个公有子网
<a name="create-two-public-subnets"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建第一个公有子网。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 
| 创建第二个公有子网。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 

### 创建两个私有子网
<a name="create-two-private-subnets"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建第一个私有子网。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 
| 创建第二个私有子网。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 

### 为您的 NAT 网关创建两个弹性 IP 地址
<a name="create-two-elastic-ip-addresses-for-your-nat-gateways"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  创建第一个弹性 IP 地址。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html)此弹性 IP 地址用于您的第一个 NAT 网关。  | AWS 管理员 | 
| 创建第二个弹性 IP 地址。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html)此弹性 IP 地址用于您的第二个 NAT 网关。 | AWS 管理员 | 

### 创建互联网网关
<a name="create-an-internet-gateway"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建互联网网关。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 
| 将互联网网关连接到 VPC。 | 选择刚刚创建的 Internet 网关，然后选择 **Actions, Attach to VPC (操作，附加到 VPC)**。 | AWS 管理员 | 

### 创建两个 NAT 网关
<a name="create-two-nat-gateways"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建第一个 NAT 网关。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 
| 创建第二个 NAT 网关。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 

### 为您的公有子网与私有子网创建路由表
<a name="create-route-tables-for-your-public-and-private-subnets"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为公有子网创建路由表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 
| 为 public-two 子网创建路由表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 
| 为 private-one 子网创建路由表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 
| 为 private-two 子网创建路由表。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 

### 创建 Lambda 函数，将其添加至 VPC，然后测试解决方案
<a name="create-the-lambda-function-add-it-to-the-vpc-and-test-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 新建 Lambda 函数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 
| 将 Lambda 函数添加到您的 VPC。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 
| 编写代码来调用外部服务。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture.html) | AWS 管理员 | 

## 相关资源
<a name="generate-a-static-outbound-ip-address-using-a-lambda-function-amazon-vpc-and-a-serverless-architecture-resources"></a>
+ [配置 Lambda 函数以访问 VPC 中的资源](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)

# 迁移到 Amazon ECR 存储库时自动识别重复的容器映像
<a name="identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository"></a>

*Rishabh Yadav 和 Rishi Singla，Amazon Web Services*

## Summary
<a name="identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository-summary"></a>

此模式提供了一种自动解决方案，可识别存储在不同容器存储库中的映像是否重复。如果您计划将映像从其他容器存储库迁移到 Amazon Elastic Container Registry（Amazon ECR），此检查非常有用。

有关基础信息，此模式还描述了容器映像的组件，例如映像摘要、清单和标签。当您计划迁移到 Amazon ECR 时，您可能会决定通过比较映像摘要来跨容器注册表同步您的容器映像。迁移容器映像之前，您需要检查这些映像是否已存在于 Amazon ECR 存储库中，以防止重复。但是，可能很难通过比较映像摘要来检测重复，并且这可能会导致初始迁移阶段就出现问题。 此模式比较了存储在不同容器注册表中的两个相似映像的摘要，并解释了摘要不同的原因，以帮助您准确比较映像。

## 先决条件和限制
<a name="identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository-prereqs"></a>
+ 活跃的 AWS 账户
+ 访问 [Amazon ECR 公有注册表](https://gallery.ecr.aws/)
+ 熟悉以下内容： AWS 服务
  + [AWS CodeCommit](https://aws.amazon.com/codecommit/)
  + [AWS CodePipeline](https://aws.amazon.com/codepipeline/)
  + [AWS CodeBuild](https://aws.amazon.com/codebuild/)
  + [AWS Identity and Access Management (IAM)](https://aws.amazon.com/iam/)
  + [Amazon Simple Storage Service（Amazon S3）](https://aws.amazon.com/s3/)
+ 已配置的 CodeCommit 凭证（参见[说明](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html)）

## 架构
<a name="identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository-architecture"></a>

**容器映像组件**

下图阐明了容器映像的其中一些组件。有关这些组件的描述，可参阅图表后面的内容。

![\[清单、配置、文件系统层和摘要。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/7db5020c-6f5b-4e91-b91a-5b8ae844be1b/images/71b99c67-a934-4f94-8af8-2a8431fb91f5.png)


**术语和定义**

[开放容器倡议（OCI）映像规范](https://github.com/opencontainers/image-spec/blob/main/spec.md)中定义了以下术语。
+ **注册表：**用于映像存储和管理的服务。
+ **客户端：**与注册机构通信并处理本地映像的工具。
+ **推送：**将映像上传到注册表的过程。
+ **拉取：**从注册表下载映像的过程。
+ **Blob：**由注册表存储且可通过摘要进行寻址的二进制形式内容。
+ **索引：**用于识别不同计算机平台（例如 x86-64 或 ARM 64 位）或媒体类型的多个映像清单的构造。有关更多信息，请参阅 [OCI 映像索引规范](https://github.com/opencontainers/image-spec/blob/main/image-index.md)。
+ **清单：**用于定义通过清单端点上传的映像或构件的 JSON 文档。清单可以通过使用描述符来引用存储库中的其他 Blob。有关更多信息，请参阅 [OCI 映像清单规范](https://github.com/opencontainers/image-spec/blob/main/manifest.md)。
+ **文件系统层：**映像的系统库和其他依赖项。
+ **配置：**包含构件元数据且可在清单中引用的 blob。有关更多信息，请参阅 [OCI 映像设置规范](https://github.com/opencontainers/image-spec/blob/main/config.md)。
+ **对象或构件：**存储为 blob 并与具有配置的配套清单关联的概念性内容项。
+ **摘要：**根据清单内容的加密哈希值创建的唯一标识符。映像摘要有助于唯一标识不可变容器映像。使用其摘要拉取映像时，无论在何种操作系统或架构上，每次都会下载相同的映像。有关更多信息，请参阅 [OCI 映像规范](https://github.com/opencontainers/image-spec/blob/main/descriptor.md#digests)。
+ **标签：**人类可读的清单标识符。相较于不可变的映像摘要，标签是动态变化的。指向映像的标签可以更改并从一个映像移动到另一个映像，不过其底层映像摘会保持不变。

**目标架构**

下图显示了此模式提供的解决方案的高级架构，即通过比较存储在 Amazon ECR 和私有存储库中的映像来识别重复的容器映像。

![\[使用 CodePipeline 和 CodeBuild自动检测重复项。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/7db5020c-6f5b-4e91-b91a-5b8ae844be1b/images/5ee62bc8-db8d-48a3-9e79-f3392b6e9bf7.png)


## 工具
<a name="identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository-tools"></a>

**AWS 服务**
+ [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在资源的整个生命周期中跨地区对其 AWS 账户 进行管理。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管式构建服务，可编译源代码、运行单元测试和生成部署就绪的构件。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) 是一项版本控制服务，可帮助您私下存储和管理 Git 存储库，而无需管理自己的源代码控制系统。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可帮助您快速对软件发布过程的不同阶段进行建模和配置，并自动执行持续发布软件变更所需步骤。
+ [Amazon Elastic Container Registry（Amazon ECR）](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)是一项安全、可扩展且可靠的托管容器映像注册表服务。

**代码**

此模式的代码可在存储库中[找到，用于识别 GitHub 存储库之间重复的容器镜像的****自动解决方案](https://github.com/aws-samples/automated-solution-to-identify-duplicate-container-images-between-repositories/)。

## 最佳实践
<a name="identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository-best-practices"></a>
+ [CloudFormation  ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html) 最佳实践
+ [AWS CodePipeline  ](https://docs.aws.amazon.com/codepipeline/latest/userguide/best-practices.html) 最佳实践

## 操作说明
<a name="identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository-epics"></a>

### 从 Amazon ECR 公有和私有存储库中拉取容器映像
<a name="pull-container-images-from-ecr-public-and-private-repositories"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 从 Amazon ECR 公有存储库中拉取映像。 | 从终端运行以下命令，以从 Amazon ECR 公有存储库中拉取映像 `amazonlinux`。<pre>$~ % docker pull public.ecr.aws/amazonlinux/amazonlinux:2018.03 </pre>将映像拉取到本地计算机后，您将看到以下拉取摘要，而该摘要可表示映像索引。<pre>2018.03: Pulling from amazonlinux/amazonlinux<br />4ddc0f8d367f: Pull complete <br /><br />Digest: sha256:f972d24199508c52de7ad37a298bda35d8a1bd7df158149b381c03f6c6e363b5<br /><br />Status: Downloaded newer image for public.ecr.aws/amazonlinux/amazonlinux:2018.03<br />public.ecr.aws/amazonlinux/amazonlinux:2018.03</pre> | 应用程序开发人员、AWS DevOps、AWS 管理员 | 
| 将映像推送到 Amazon ECR 私有存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.html) | AWS 管理员、AWS DevOps、应用程序开发者 | 
| 从 Amazon ECR 私有存储库中拉取相同的映像。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.html) | 应用程序开发人员、AWS DevOps、AWS 管理员 | 

### 比较映像清单
<a name="compare-the-image-manifests"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查找存储在 Amazon ECR 公有存储库中的映像的清单。 | 从终端运行以下命令，以从 Amazon ECR 公有存储库中拉取映像 `public.ecr.aws/amazonlinux/amazonlinux:2018.03` 的清单。<pre>$~ % docker manifest inspect public.ecr.aws/amazonlinux/amazonlinux:2018.03<br />{<br />   "schemaVersion": 2,<br />   "mediaType": "application/vnd.docker.distribution.manifest.list.v2+json",<br />   "manifests": [<br />      {<br />         "mediaType": "application/vnd.docker.distribution.manifest.v2+json",<br />         "size": 529,<br />         "digest": "sha256:52db9000073d93b9bdee6a7246a68c35a741aaade05a8f4febba0bf795cdac02",<br />         "platform": {<br />            "architecture": "amd64",<br />            "os": "linux"<br />         }<br />      }<br />   ]<br />}</pre> | AWS 管理员、AWS DevOps、应用程序开发者 | 
| 查找存储在 Amazon ECR 私有存储库中的映像的清单。 | 从终端运行以下命令，以从 Amazon ECR 私有存储库中拉取映像 `<account-id>.dkr.ecr.us-east-1.amazonaws.com/test_ecr_repository:latest` 的清单。<pre>$~ % docker manifest inspect <account-id>.dkr.ecr.us-east-1.amazonaws.com/test_ecr_repository:latest                                          <br />{<br />	"schemaVersion": 2,<br />	"mediaType": "application/vnd.docker.distribution.manifest.v2+json",<br />	"config": {<br />		"mediaType": "application/vnd.docker.container.image.v1+json",<br />		"size": 1477,<br />		"digest": "sha256:f7cee5e1af28ad4e147589c474d399b12d9b551ef4c3e11e02d982fce5eebc68"<br />	},<br />	"layers": [<br />		{<br />			"mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",<br />			"size": 62267075,<br />			"digest": "sha256:4ddc0f8d367f424871a060e2067749f32bd36a91085e714dcb159952f2d71453"<br />		}<br />	]<br />}</pre> | AWS DevOps、AWS 系统管理员、应用程序开发者 | 
| 将 Docker 拉取的摘要与 Amazon ECR 私有存储库中映像的清单摘要进行比较。 | 另一个问题是，为什么 **docker pull** 命令提供的摘要与映像 `<account-id>.dkr.ecr.us-east-1.amazonaws.com/test_ecr_repository:latest` 的清单摘要不同。用于 **docker pull** 的摘要表示存储在注册表中的映像清单的摘要。此摘要可视为哈希链的根，因为清单包含将下载并导入到 Docker 中的内容的哈希值。Docker 中使用的映像 ID 可以在此清单 `config.digest` 中找到。这表示 Docker 使用的映像配置。因此，您可以这样说，清单就像是信封，而映像就是信封的内容。清单摘要始终与映像 ID 不同。但是，特定的清单应始终会创建相同的映像 ID。由于清单摘要是一个哈希链，因此我们不能保证指定映像 ID 的哈希链总是相同。在大多数情况下，它会创建相同的摘要，尽管 Docker 无法对此做出保证。清单摘要中可能存在的区别源于 Docker 没有在本地存储用 gzip 压缩的 blob。因此，尽管未压缩的内容保持不变，但导出层可能会创建不同的摘要。映像 ID 可确认未压缩的内容是否相同；也就是说，映像 ID 现在是内容可寻址标识符（`chainID`）。要确认此信息，您可以比较 Amazon ECR 公有和私有存储库上的 **docker inspect** 命令的输出：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.html)结果验证了两个映像具有相同的映像 ID 摘要和层摘要。身份证:`f7cee5e1af28ad4e147589c474d399b12d9b551ef4c3e11e02d982fce5eebc68`层：`d5655967c2c4e8d68f8ec7cf753218938669e6c16ac1324303c073c736a2e2a2`此外，摘要的基础是本地管理的对象的字节（本地文件是容器映像层的 tar）或推送到注册表服务器的 blob。但是，当您将 blob 推送到注册表时，tar 会被压缩，并在压缩的 tar 文件中计算摘要。因此，**docker pull** 摘要值的差异源于在注册表（Amazon ECR 私有或公有）级别应用的压缩。此解释专门针对使用 Docker 客户端的情况。您不会在其他客户端（例如 **nerdctl** 或 **Finch**）上看到这种行为，因为在推拉操作期间，其不会自动压缩映像。 | AWS DevOps、AWS 系统管理员、应用程序开发者 | 

### 自动识别 Amazon ECR 公有和私有存储库之间的重复映像
<a name="automatically-identify-duplicate-images-between-ecr-public-and-private-repositories"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 将此模式的 GitHub 存储库克隆到本地文件夹：<pre>$git clone https://github.com/aws-samples/automated-solution-to-identify-duplicate-container-images-between-repositories</pre> | AWS 管理员，AWS DevOps | 
| 设置 CI/CD 管道。 |  GitHub 存储库中包含一个用于创建 CloudFormation 堆栈的`.yaml`文件，用于在其中设置管道 AWS CodePipeline。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.html)该管道将设置为两个阶段（CodeCommit 以及 CodeBuild，如架构图所示），以识别私有存储库中也存在于公共存储库中的图像。管道配置有以下资源：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.html) | AWS 管理员，AWS DevOps | 
| 填充 CodeCommit 存储库。 | 要填充 CodeCommit 存储库，请执行以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.html) | AWS 管理员，AWS DevOps | 
| 清理。 | 为避免将来产生费用，请按照以下步骤删除资源：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.html) | AWS 管理员 | 

## 问题排查
<a name="identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 当您尝试从终端或命令行推送、拉取 CodeCommit 存储库或以其他方式与仓库交互时，系统会提示您提供用户名和密码，并且必须为您的 IAM 用户提供 Git 证书。 | 出现此错误的最常见原因如下：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.html)根据您的操作系统和本地环境，您可能需要安装凭证管理器、配置操作系统随附的凭证管理器或自定义您的本地环境以使用凭证存储。例如，如果您的计算机运行的是 macOS，您可以使用 Keychain Access 实用程序存储您的凭证。如果您的计算机运行的是 Windows，您可以使用随 Windows 版 Git 安装的 Git Credential Manager。有关更多信息，请参阅文档中的[使用 Git 凭据为 HTTPS 用户设置](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-gc.html)和 Git CodeCommit 文档中的[凭据存储](https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage)。 | 
| 将映像推送到 Amazon ECR 存储库时，您会遇到 HTTP 403 或“没有基本的身份验证凭证”错误。 | **即使你已使用 aws ecr 命令成功向 **Docker 进行了身份验证，你也可能会在 docker push** **或 docker pull** 命令中遇到这些错误消息。 get-login-password**已知原因包括：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.html) | 

## 相关资源
<a name="identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository-resources"></a>
+ 用于@@ [识别存储库（存储GitHub 库）之间重复的容器映像的自动化解决方案](https://github.com/aws-samples/automated-solution-to-identify-duplicate-container-images-between-repositories/)
+ [Amazon ECR 公开映像浏览馆](https://gallery.ecr.aws/)
+ [Amazon ECR 中的私有映像](https://docs.aws.amazon.com/AmazonECR/latest/userguide/images.html)（Amazon ECR 文档）
+ [AWS::CodePipeline::Pipeline 资源](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-pipeline.html)（CloudFormation 文档）
+ [OCI 映像格式规范](https://github.com/opencontainers/image-spec/blob/main/spec.md)

## 附加信息
<a name="identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository-additional"></a>

**Amazon ECR 公有存储库中映像的 Docker 检查输出**

```
[
    {
        "Id": "sha256:f7cee5e1af28ad4e147589c474d399b12d9b551ef4c3e11e02d982fce5eebc68",
        "RepoTags": [
            "<account-id>.dkr.ecr.us-east-1.amazonaws.com/test_ecr_repository:latest",
            "public.ecr.aws/amazonlinux/amazonlinux:2018.03"
        ],
        "RepoDigests": [
            "<account-id>.dkr.ecr.us-east-1.amazonaws.com/test_ecr_repository@sha256:52db9000073d93b9bdee6a7246a68c35a741aaade05a8f4febba0bf795cdac02",
            "public.ecr.aws/amazonlinux/amazonlinux@sha256:f972d24199508c52de7ad37a298bda35d8a1bd7df158149b381c03f6c6e363b5"
        ],
        "Parent": "",
        "Comment": "",
        "Created": "2023-02-23T06:20:11.575053226Z",
        "Container": "ec7f2fc7d2b6a382384061247ef603e7d647d65f5cd4fa397a3ccbba9278367c",
        "ContainerConfig": {
            "Hostname": "ec7f2fc7d2b6",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\"/bin/bash\"]"
            ],
            "Image": "sha256:c1bced1b5a65681e1e0e52d0a6ad17aaf76606149492ca0bf519a466ecb21e51",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },
        "DockerVersion": "20.10.17",
        "Author": "",
        "Config": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "Image": "sha256:c1bced1b5a65681e1e0e52d0a6ad17aaf76606149492ca0bf519a466ecb21e51",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": null
        },
        "Architecture": "amd64",
        "Os": "linux",
        "Size": 167436755,
        "VirtualSize": 167436755,
        "GraphDriver": {
            "Data": {
                "MergedDir": "/var/lib/docker/overlay2/c2c2351a82b26cbdf7782507500e5adb5c2b3a2875bdbba79788a4b27cd6a913/merged",
                "UpperDir": "/var/lib/docker/overlay2/c2c2351a82b26cbdf7782507500e5adb5c2b3a2875bdbba79788a4b27cd6a913/diff",
                "WorkDir": "/var/lib/docker/overlay2/c2c2351a82b26cbdf7782507500e5adb5c2b3a2875bdbba79788a4b27cd6a913/work"
            },
            "Name": "overlay2"
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:d5655967c2c4e8d68f8ec7cf753218938669e6c16ac1324303c073c736a2e2a2"
            ]
        },
        "Metadata": {
            "LastTagTime": "2023-03-02T10:28:47.142155987Z"
        }
    }
]
```

**Amazon ECR 私有存储库中映像的 Docker 检查输出**

```
[
    {
        "Id": "sha256:f7cee5e1af28ad4e147589c474d399b12d9b551ef4c3e11e02d982fce5eebc68",
        "RepoTags": [
            "<account-id>.dkr.ecr.us-east-1.amazonaws.com/test_ecr_repository:latest",
            "public.ecr.aws/amazonlinux/amazonlinux:2018.03"
        ],
        "RepoDigests": [
            "<account-id>.dkr.ecr.us-east-1.amazonaws.com/test_ecr_repository@sha256:52db9000073d93b9bdee6a7246a68c35a741aaade05a8f4febba0bf795cdac02",
            "public.ecr.aws/amazonlinux/amazonlinux@sha256:f972d24199508c52de7ad37a298bda35d8a1bd7df158149b381c03f6c6e363b5"
        ],
        "Parent": "",
        "Comment": "",
        "Created": "2023-02-23T06:20:11.575053226Z",
        "Container": "ec7f2fc7d2b6a382384061247ef603e7d647d65f5cd4fa397a3ccbba9278367c",
        "ContainerConfig": {
            "Hostname": "ec7f2fc7d2b6",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "#(nop) ",
                "CMD [\"/bin/bash\"]"
            ],
            "Image": "sha256:c1bced1b5a65681e1e0e52d0a6ad17aaf76606149492ca0bf519a466ecb21e51",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {}
        },
        "DockerVersion": "20.10.17",
        "Author": "",
        "Config": {
            "Hostname": "",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "Image": "sha256:c1bced1b5a65681e1e0e52d0a6ad17aaf76606149492ca0bf519a466ecb21e51",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": null
        },
        "Architecture": "amd64",
        "Os": "linux",
        "Size": 167436755,
        "VirtualSize": 167436755,
        "GraphDriver": {
            "Data": {
                "MergedDir": "/var/lib/docker/overlay2/c2c2351a82b26cbdf7782507500e5adb5c2b3a2875bdbba79788a4b27cd6a913/merged",
                "UpperDir": "/var/lib/docker/overlay2/c2c2351a82b26cbdf7782507500e5adb5c2b3a2875bdbba79788a4b27cd6a913/diff",
                "WorkDir": "/var/lib/docker/overlay2/c2c2351a82b26cbdf7782507500e5adb5c2b3a2875bdbba79788a4b27cd6a913/work"
            },
            "Name": "overlay2"
        },
        "RootFS": {
            "Type": "layers",
            "Layers": [
                "sha256:d5655967c2c4e8d68f8ec7cf753218938669e6c16ac1324303c073c736a2e2a2"
            ]
        },
        "Metadata": {
            "LastTagTime": "2023-03-02T10:28:47.142155987Z"
        }
    }
]
```

# 使用 Kubernetes 在亚马逊 EKS 工作节点上安装 SSM 代理 DaemonSet
<a name="install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset"></a>

*Mahendra Revanasiddappa，Amazon Web Services*

## Summary
<a name="install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset-summary"></a>

**注意，2021 年 9 月：**经过优化的最新亚马逊 EKS 会自动 AMIs 安装 SSM 代理。有关更多信息，请参阅 2021 年 6 月的[发行说明](https://github.com/awslabs/amazon-eks-ami/releases/tag/v20210621) AMIs。

在 Amazon Elastic Kubernetes Service(Amazon EKS) 中，由于安全指导方针，Worker 节点没有附加 Secure Shell (SSH) 密钥对。此模式显示了如何使用 Kubernetes DaemonSet 资源类型在所有工作节点上安装 AWS Systems Manager 代理（SSM 代理），而不是手动安装或替换节点的亚马逊系统映像 (AMI)。 DaemonSet 使用工作节点上的 cron 作业来安排 SSM 代理的安装。您也可以使用这种模式在 Worker 节点上安装其他软件包。

在对集群中的问题进行故障排除时，按需安装 SSM Agent 可让您与 Worker 节点建立 SSH 会话、收集日志或查看实例配置，而无需使用 SSH 密钥对。

## 先决条件和限制
<a name="install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset-prereqs"></a>

**先决条件**
+ 带有亚马逊弹性计算云 (Amazon EC2) 工作节点的现有 Amazon EKS 集群。
+ 容器实例应获得与 SSM 服务通信的许可。AWS Identity and Access Management (IAM) 托管角色**亚马逊**为 SSM 代理SSMManagedInstanceCore提供了在 EC2 实例上运行所需的权限。有关更多信息，请参阅 [AWS Systems Manager 文档](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)。

**限制**
+ 这种模式不适用于 AWS Fargate，因为 F DaemonSets argate 平台不支持。
+ 此模式仅适用于基于 Linux 的 Worker 节点。
+ P DaemonSet od 在特权模式下运行。如果 Amazon EKS 集群有阻止特权模式的容器组（pod），则不会安装 SSM Agent。

## 架构
<a name="install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset-architecture"></a>

下图阐明了该模式的架构。

![\[使用 Kubernetes DaemonSet 在亚马逊 EKS 工作节点上安装 SSM 代理。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/016d53f3-45c1-4913-b542-67124e1462b8/images/3a6dfd00-e54b-44d5-843a-4c26ce9826c9.png)


## 工具
<a name="install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset-tools"></a>

**工具**
+ [Kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html) 是命令行实用程序，用于与 Amazon EKS 集群交互。此模式用于`kubectl`在 Amazon EKS 集群 DaemonSet 上部署，该集群将在所有工作节点上安装 SSM 代理。
+ [Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) 让您在 AWS 上轻松运行 Kubernetes，而无需安装、操作和维护您自己的 Kubernetes 控制面板或节点。Kubernetes 是一个用于实现容器化应用程序的部署、扩缩和管理自动化的开源系统。
+ [AWS Systems Manager 会话管理器](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html)允许您通过交互式、一键式、基于浏览器的外壳或 AWS 命令行界面 (AWS CLIVMs) 来管理您的 EC2 实例、本地实例和虚拟机 ()。

**代码**

使用以下代码创建将在 Amazon EKS 集群上安装 SSM 代理的 DaemonSet 配置文件。按照[操作说明](#install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset-epics)部分中的说明操作。

```
cat << EOF > ssm_daemonset.yaml
apiVersion: apps/v1
kind: DaemonSet
metadata:
  labels:
    k8s-app: ssm-installer
  name: ssm-installer
  namespace: kube-system
spec:
  selector:
    matchLabels:
      k8s-app: ssm-installer
  template:
    metadata:
      labels:
        k8s-app: ssm-installer
    spec:
      containers:
      - name: sleeper
        image: busybox
        command: ['sh', '-c', 'echo I keep things running! && sleep 3600']
      initContainers:
      - image: amazonlinux
        imagePullPolicy: Always
        name: ssm
        command: ["/bin/bash"]
        args: ["-c","echo '* * * * * root yum install -y https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/linux_amd64/amazon-ssm-agent.rpm & rm -rf /etc/cron.d/ssmstart' > /etc/cron.d/ssmstart"]
        securityContext:
          allowPrivilegeEscalation: true
        volumeMounts:
        - mountPath: /etc/cron.d
          name: cronfile
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      volumes:
      - name: cronfile
        hostPath:
          path: /etc/cron.d
          type: Directory
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      terminationGracePeriodSeconds: 30
EOF
```

## 操作说明
<a name="install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset-epics"></a>

### 设置 kubectl
<a name="set-up-kubectl"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装和配置 kubectl 以访问 EKS 集群。 | 如果 `kubectl` 尚未安装并配置为访问 Amazon EKS 集群，请参阅 Amazon EKS 文档中的[安装 kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)。 | DevOps | 

### 部署 DaemonSet
<a name="deploy-the-daemonset"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 DaemonSet 配置文件。 | 使用此模式前面[代码](#install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset-tools)部分中的代码创建名为的 DaemonSet 配置文件`ssm_daemonset.yaml`，该文件将部署到 Amazon EKS 集群。启动的 pod DaemonSet 有一个主容器和一个`init`容器。主容器包含一个 `sleep` 命令。该 `init` 容器包括一个 `command` 部分，用于创建 cron 作业文件，以在 `/etc/cron.d/` 路径上安装 SSM Agent。cron 作业仅运行一次，其创建的文件会在作业完成后自动删除。容器初始化完成后，主容器将等待 60 分钟后再退出。60 分钟后，将启动新容器组（pod）。此容器组（pod）会安装 SSM Agent（如果缺失），或者将 SSM Agent 更新至最新版本。如果需要，您可以修改 `sleep` 命令，以每天重启容器组（pod）一次或更频繁地运行。  | DevOps | 
| 在 Amazon EKS 集群 DaemonSet 上部署。 | 要在 Amazon EKS 集群上部署您在上一步中创建的 DaemonSet 配置文件，请使用以下命令：<pre>kubectl apply -f ssm_daemonset.yaml </pre>此命令创建一个， DaemonSet 用于在工作节点上运行 pod 以安装 SSM 代理。 | DevOps | 

## 相关资源
<a name="install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset-resources"></a>
+ [安装 kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)(Amazon EKS 文档)
+ [设置 Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started.html)（AWS Systems Manager 文档）

# 使用在 Amazon EKS 工作节点上安装 SSM CloudWatch 代理和代理 preBootstrapCommands
<a name="install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands"></a>

*Akkamahadevi Hiremath，Amazon Web Services*

## Summary
<a name="install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands-summary"></a>

此模式提供了在亚马逊 EKS 集群创建期间在亚马逊网络服务 (AWS) 云中的亚马逊 Elastic Kubernetes Service（Amazon EKS）工作节点上安装 AWS Systems Manager 代理（SSM 代理）和亚马逊 CloudWatch 代理的代码示例和步骤。您可以使用`eksctl`[配置文件架构](https://eksctl.io/usage/schema/)中的`preBootstrapCommands`属性安装 SSM CloudWatch 代理和代理（Weaveworks 文档）。然后，您可以使用 SSM 代理连接到您的工作节点，而无需使用亚马逊弹性计算云 (Amazon EC2) 密钥对。此外，您还可以使用 CloudWatch 代理来监控 Amazon EKS 工作节点上的内存和磁盘利用率。

## 先决条件和限制
<a name="install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ [eksctl 命令行实用程序](https://docs.aws.amazon.com/eks/latest/userguide/eksctl.html)，已在 macOS、Linux 或 Windows 上安装与配置
+ [kubectl 命令行实用程序](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)，已在 macOS、Linux 或 Windows 上安装与配置

**限制**
+ 我们建议您避免向 `preBootstrapCommands` **** 属性中添加长时间运行的脚本，因为这会延迟节点在扩展活动期间加入 Amazon EKS 集群的时间。我们建议您改为创建[自定义亚马逊机器映像（AMI）](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.customenv.html)。
+ 此模式仅适用于亚马逊 EC2 Linux 实例。

## 架构
<a name="install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands-architecture"></a>

**技术堆栈**
+ Amazon CloudWatch
+ Amazon Elastic Kubernetes Service(Amazon EKS)
+ AWS Systems Manager Parameter Store

**目标架构**

下图显示了一个用户使用 SSM Agent 连接到 Amazon EKS Worker 节点的示例，该代理是使用 `preBootstrapCommands` 安装的。

![\[User connecting to Amazon EKS worker nodes via Systems Manager, with SSM Agent and CloudWatch agent on each node.\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/b37a3cdb-204f-4014-8317-3600a793dac7/images/9a5760af-23bb-4616-97b0-b401a9d080cf.png)


下图显示了如下工作流：

1. 用户使用带有`preBootstrapCommands`属性的`eksctl`配置文件创建 Amazon EKS 集群，该文件将安装 SSM CloudWatch 代理和代理。

1. 之后由于扩展活动而加入集群的任何新实例都将使用预安装的 SSM 代理和 CloudWatch 代理创建。

1. 用户使用 SSM 代理连接 EC2 到 Amazon，然后使用代理监控内存和磁盘利用率。 CloudWatch 

## 工具
<a name="install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands-tools"></a>
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可帮助您实时监控您的 AWS 资源和在 AWS 上运行的应用程序的指标。
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) 可帮助您在 AWS 上运行 Kubernetes，而无需安装或维护您自己的 Kubernetes 控制面板或节点。
+ [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) 提供安全的分层存储，用于配置数据管理和密钥管理。
+ [AWS Systems Manager 会话管理器](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html)可帮助您通过交互式、一键式、基于浏览器的外壳或 AWS 命令行界面 (AWS CLI) 来管理您的 EC2 实例、本地实例和虚拟机。
+ [eksctl](https://eksctl.io/usage/schema/) 是一种用于在 Amazon EKS 上创建和管理 Kubernetes 集群的命令行实用程序。
+ [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) 是命令行实用程序，用于与集群 API 服务器通信。

## 操作说明
<a name="install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands-epics"></a>

### 创建 Amazon EKS 集群。
<a name="create-an-amazon-eks-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 存储 CloudWatch 代理配置文件。 | 将 CloudWatch 代理配置文件存储在您要创建亚马逊 EK [S 集群的 AWS 区域的 AWS Systems Manager Parameter St](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) ore 中。为此，请在 AWS Systems Manager Parameter Store 中[创建参数](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-create-console.html)，并备注参数名称（例如`AmazonCloudwatch-linux`）。有关更多信息，请参阅此模式的 “[其他信息](#install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands-additional)” 部分中的* CloudWatch 代理配置文件代码示例*。 | DevOps 工程师 | 
| 创建 eksctl 配置文件与集群。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands.html) | AWS DevOps | 

### 验证 SSM 代理和 CloudWatch 代理是否正常工作
<a name="verify-that-the-ssm-agent-and-cloudwatch-agent-work"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 测试 SSM Agent。 | 使用 AWS Systems Manager 文档中的[启动会话](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html#start-ec2-console%20%20or%20https:%2F%2Fdocs.aws.amazon.com%2Fsystems-manager%2Flatest%2Fuserguide%2Fsession-manager-working-with-sessions-start.html%23sessions-start-cli)所涵盖的任何方法，利用 SSH 连接至您的 Amazon EKS 集群节点。 | AWS DevOps | 
| 测试代 CloudWatch 理。 | 使用 CloudWatch 控制台验证代 CloudWatch 理：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands.html) | AWS DevOps | 

## 相关资源
<a name="install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands-resources"></a>
+ 在@@ [您的服务器上安装和运行 CloudWatch 代理](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/install-CloudWatch-Agent-commandline-fleet.html)（Amazon CloudWatch 文档）
+ [创建 Systems Manager 参数（控制台）](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-create-console.html)(AWS Systems Manager 文档)
+ [创建 CloudWatch 代理配置文件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/create-cloudwatch-agent-configuration-file.html)（Amazon CloudWatch 文档）
+ [启动会话 (AWS CLI)](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html#sessions-start-cli)（AWS Systems Manager 文档）
+ [启动会话（亚马逊 EC2 控制台）（](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-sessions-start.html#start-ec2-console)AWS Systems Manager 文档）

## 附加信息
<a name="install-the-ssm-agent-and-cloudwatch-agent-on-amazon-eks-worker-nodes-using-prebootstrapcommands-additional"></a>

** CloudWatch 代理配置文件示例**

在以下示例中， CloudWatch 代理配置为监控 Amazon Linux 实例上的磁盘和内存利用率：

```
{
    "agent": {
        "metrics_collection_interval": 60,
        "run_as_user": "cwagent"
    },
    "metrics": {
        "append_dimensions": {
            "AutoScalingGroupName": "${aws:AutoScalingGroupName}",
            "ImageId": "${aws:ImageId}",
            "InstanceId": "${aws:InstanceId}",
            "InstanceType": "${aws:InstanceType}"
        },
        "metrics_collected": {
            "disk": {
                "measurement": [
                    "used_percent"
                ],
                "metrics_collection_interval": 60,
                "resources": [
                    "*"
                ]
            },
            "mem": {
                "measurement": [
                    "mem_used_percent"
                ],
                "metrics_collection_interval": 60
            }
        }
    }
}
```

**eksctl 配置文件示例**

```
apiVersion: eksctl.io/v1alpha5
kind: ClusterConfig
metadata:
  name: test
  region: us-east-2
  version: "1.24"
managedNodeGroups:
  - name: test
    minSize: 2
    maxSize: 4
    desiredCapacity: 2
    volumeSize: 20
    instanceType: t3.medium
    preBootstrapCommands:
    - sudo yum install amazon-ssm-agent -y
    - sudo systemctl enable amazon-ssm-agent
    - sudo systemctl start amazon-ssm-agent
    - sudo yum install amazon-cloudwatch-agent -y
    - sudo /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c ssm:AmazonCloudwatch-linux
    iam:
      attachPolicyARNs:
        - arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy
        - arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy
        - arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly
        - arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
```

**其他代码详细信息**
+ `preBootstrapCommands` 属性的最后一行，`AmazonCloudwatch-linux` 是在 AWS Systems Manager Parameter Store 中创建的参数名称。您必须在创建 Amazon EKS 集群的相同 AWS 区域的 Parameter Store 中纳入 `AmazonCloudwatch-linux`。您也可指定文件路径，但我们建议使用 Systems Manager，以便更轻松地实现自动化和重复使用。
+ 如果您在 `eksctl` 配置文件中使用 `preBootstrapCommands`，则会在 AWS 管理控制台中看到两个启动模板。第一个启动模板包含 `preBootstrapCommands` 中指定的命令。第二个模板包括 `preBootstrapCommands` 中指定的命令和默认 Amazon EKS 用户数据。此数据用于将节点加入集群。节点组的自动扩缩组使用此用户数据启动新实例。
+ 如果您在 `eksctl` 配置文件中使用 `iam` 属性，则必须列出默认 Amazon EKS 策略，以及随附 AWS Identity and Access Management (IAM) 策略中所需任何其他策略。在 “*创建 eksctl 配置文件和集群*” 步骤的代码片段中，`CloudWatchAgentServerPolicy`添加了其他策略以确保 CloudWatch 代理和 SSM 代理按预期运行。`AmazonSSMMangedInstanceCore``AmazonEKSWorkerNodePolicy`、`AmazonEKS_CNI_Policy`、`AmazonEC2ContainerRegistryReadOnly` 策略是 Amazon EKS 集群正常运行所需强制策略。

# 启用 Amazon EKS 自动模式时迁移 NGINX 入口控制器
<a name="migrate-nginx-ingress-controller-eks-auto-mode"></a>

*Olawale Olaleye 和 Shamanth Devagari，Amazon Web Services*

## Summary
<a name="migrate-nginx-ingress-controller-eks-auto-mode-summary"></a>

适用于 Amazon Elastic Kubernetes Service（Amazon EKS）的 [EKS 自动模式](https://docs.aws.amazon.com/eks/latest/userguide/automode.html)可以降低在 Kubernetes 集群上运行工作负载的运维开销。此模式还 AWS 允许您代表您设置和管理基础架构。在现有集群上启用 EKS 自动模式时，必须仔细规划 [NGINX 入口控制器](https://docs.nginx.com/nginx-ingress-controller/overview/about/)配置的迁移。这是因为无法直接转移网络负载均衡器。

当您在现有 Amazon EKS 集群中启用 EKS 自动模式时，您可以使用 blue/green 部署策略迁移 NGINX 入口控制器实例。

## 先决条件和限制
<a name="migrate-nginx-ingress-controller-eks-auto-mode-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 运行 Kubernetes 版本 1.29 或更高版本的 [Amazon EKS 集群](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html)
+ 运行[最低版本](https://docs.aws.amazon.com/eks/latest/userguide/auto-enable-existing.html#auto-addons-required)的 Amazon EKS 插件
+ 最新版本的 [kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html#kubectl-install-update)
+ 已有 [NGINX 入口控制器](https://kubernetes.github.io/ingress-nginx/deploy/#aws)实例
+ （可选）Amazon Route 53 中有[托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-working-with.html)，用于基于 DNS 的流量转移

## 架构
<a name="migrate-nginx-ingress-controller-eks-auto-mode-architecture"></a>

*蓝/绿部署是一种部署*策略，在这种策略中，您可以创建两个独立但相同的环境。 Blue/green 部署提供近乎零的停机时间发布和回滚功能。基本思路是在运行不同版本应用程序的两个相同环境之间转移流量。

下图显示了启用 EKS 自动模式时，从两个不同的 NGINX 入口控制器实例迁移网络负载均衡器的过程。您可以使用 blue/green 部署在两个网络负载均衡器之间转移流量。

![\[使用 blue/green 部署策略迁移 NGINX 入口控制器实例。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/57e8c14f-cb50-4027-8ef6-ce8ea3f2db25/images/211a029a-90d8-4c92-8200-19e54062f936.png)


原始命名空间是*蓝色*命名空间。在启用 EKS 自动模式之前，这是原始 NGINX 入口控制器服务和实例的运行位置。原始服务和实例连接到已在 Route 53 中配置 DNS 名称的网络负载均衡器。[AWS 负载均衡控制器](https://kubernetes-sigs.github.io/aws-load-balancer-controller/v2.11/)在目标虚拟私有云（VPC）中部署了此网络负载均衡器。

该图显示了为 blue/green 部署设置环境的以下工作流程：

1. 在不同的命名空间（*绿色*命名空间）中安装和配置另一个 NGINX 入口控制器实例。

1. 在 Route 53 中，为新的网络负载均衡器配置 DNS 名称。

## 工具
<a name="migrate-nginx-ingress-controller-eks-auto-mode-tools"></a>

**AWS 服务**
+ [亚马逊 Elastic Kubernetes Service（亚马逊](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。
+ [弹性负载均衡](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html)在多个目标上分配传入的应用程序或网络流量。例如，您可以跨亚马逊弹性计算云 (Amazon EC2) 实例、容器以及一个或多个可用区中的 IP 地址分配流量。
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一种可用性高、可扩展性强的 DNS Web 服务。
+ [Amazon Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。该虚拟网络类似于您在数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。

**其他工具**
+ [Helm](https://helm.sh/) 是 Kubernetes 的开源软件包管理器，可帮助您在 Kubernetes 集群上安装和管理应用程序。
+ [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/)：针对 Kubernetes 集群运行命令的命令行界面。
+ [NGINX 入口控制器](https://docs.nginx.com/nginx-ingress-controller/overview/about/)将 Kubernetes 应用程序和服务与请求处理、身份验证、自助服务自定义资源和调试连接起来。

## 操作说明
<a name="migrate-nginx-ingress-controller-eks-auto-mode-epics"></a>

### 查看现有环境
<a name="review-the-existing-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确认原 NGINX 入口控制器实例运行正常。 | 输入以下命令验证 `ingress-nginx` 命名空间中的资源是否运行正常。如果已在其他命名空间中部署 NGINX 入口控制器，请在此命令中更新命名空间名称。<pre>kubectl get all -n ingress-nginx</pre>在输出中，确认 NGINX 入口控制器容器组（pod）运行正常。下面是一个示例输出：<pre>NAME                                           READY   STATUS      RESTARTS      AGE<br />pod/ingress-nginx-admission-create-xqn9d       0/1     Completed   0             88m<br />pod/ingress-nginx-admission-patch-lhk4j        0/1     Completed   1             88m<br />pod/ingress-nginx-controller-68f68f859-xrz74   1/1     Running     2 (10m ago)   72m<br /><br />NAME                                         TYPE           CLUSTER-IP       EXTERNAL-IP                                                                     PORT(S)                      AGE<br />service/ingress-nginx-controller             LoadBalancer   10.100.67.255    k8s-ingressn-ingressn-abcdefg-12345.elb.eu-west-1.amazonaws.com   80:30330/TCP,443:31462/TCP   88m<br />service/ingress-nginx-controller-admission   ClusterIP      10.100.201.176   <none>                                                                          443/TCP                      88m<br /><br />NAME                                       READY   UP-TO-DATE   AVAILABLE   AGE<br />deployment.apps/ingress-nginx-controller   1/1     1            1           88m<br /><br />NAME                                                 DESIRED   CURRENT   READY   AGE<br />replicaset.apps/ingress-nginx-controller-68f68f859   1         1         1       72m<br />replicaset.apps/ingress-nginx-controller-d8c96cf68   0         0         0       88m<br /><br />NAME                                       STATUS     COMPLETIONS   DURATION   AGE<br />job.batch/ingress-nginx-admission-create   Complete   1/1           4s         88m<br />job.batch/ingress-nginx-admission-patch    Complete   1/1           5s         88m</pre> | DevOps 工程师 | 

### 部署示例 HTTPd 工作负载以使用 NGINX 入口控制器
<a name="deploy-a-sample-httpd-workload-to-use-the-nginx-ingress-controller"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Kubernetes 资源。 | 输入以下命令创建 Kubernetes 部署、服务和入口示例：<pre>kubectl create deployment demo --image=httpd --port=80</pre><pre>kubectl expose deployment demo</pre><pre> kubectl create ingress demo --class=nginx \<br />  --rule nginxautomode.local.dev/=demo:80</pre> | DevOps 工程师 | 
| 查看已部署的资源。 | 输入以下命令查看已部署资源的列表：<pre>kubectl get all,ingress</pre>在输出中，确认示例 HTTPd pod 处于运行状态。下面是一个示例输出：<pre>NAME                        READY   STATUS    RESTARTS   AGE<br />pod/demo-7d94f8cb4f-q68wc   1/1     Running   0          59m<br /><br />NAME                 TYPE        CLUSTER-IP      EXTERNAL-IP   PORT(S)   AGE<br />service/demo         ClusterIP   10.100.78.155   <none>        80/TCP    59m<br />service/kubernetes   ClusterIP   10.100.0.1      <none>        443/TCP   117m<br /><br />NAME                   READY   UP-TO-DATE   AVAILABLE   AGE<br />deployment.apps/demo   1/1     1            1           59m<br /><br />NAME                              DESIRED   CURRENT   READY   AGE<br />replicaset.apps/demo-7d94f8cb4f   1         1         1       59m<br /><br />NAME                             CLASS   HOSTS                                  ADDRESS                                                                         PORTS   AGE<br />ingress.networking.k8s.io/demo   nginx   nginxautomode.local.dev                k8s-ingressn-ingressn-abcdefg-12345.elb.eu-west-1.amazonaws.com                 80      56m</pre> | DevOps 工程师 | 
| 确认服务可供访问。 | 输入以下命令确认能够通过网络负载均衡器的 DNS 名称访问服务：<pre>curl -H "Host: nginxautomode.local.dev" http://k8s-ingressn-ingressn-abcdefg-12345.elb.eu-west-1.amazonaws.com</pre>预期的输出如下所示：<pre><html><body><h1>It works!</h1></body></html></pre> | DevOps 工程师 | 
| （可选）创建 DNS 记录。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-nginx-ingress-controller-eks-auto-mode.html) | DevOps 工程师，AWS DevOps | 

### 在现有集群上启用 EKS 自动模式
<a name="enable-eks-auto-mode-on-the-existing-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启用 EKS 自动模式。 | 按照[在现有集群上启用 EKS 自动模式](https://docs.aws.amazon.com/eks/latest/userguide/auto-enable-existing.html)中的说明进行操作（Amazon EKS 文档）。 | AWS DevOps | 

### 安装新的 NGINX 入口控制器
<a name="install-a-new-nginx-ingress-controller"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置新的 NGINX 入口控制器实例。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-nginx-ingress-controller-eks-auto-mode.html) | DevOps 工程师 | 
| 部署新的 NGINX 实例控制器实例。 | 输入以下命令应用已修改的清单文件：<pre>kubectl apply -f deploy.yaml</pre> | DevOps 工程师 | 
| 确认部署成功。 | 输入以下命令验证 `ingress-nginx-v2` 命名空间中的资源是否运行正常。<pre>kubectl get all -n ingress-nginx-v2</pre>在输出中，确认 NGINX 入口控制器容器组（pod）处于运行状态。下面是一个示例输出：<pre>NAME                                            READY   STATUS      RESTARTS   AGE<br />pod/ingress-nginx-admission-create-7shrj        0/1     Completed   0          24s<br />pod/ingress-nginx-admission-patch-vkxr5         0/1     Completed   1          24s<br />pod/ingress-nginx-controller-757bfcbc6d-4fw52   1/1     Running     0          24s<br /><br />NAME                                         TYPE           CLUSTER-IP       EXTERNAL-IP                                                                     PORT(S)                      AGE<br />service/ingress-nginx-controller             LoadBalancer   10.100.208.114   k8s-ingressn-ingressn-2e5e37fab6-848337cd9c9d520f.elb.eu-west-1.amazonaws.com   80:31469/TCP,443:30658/TCP   24s<br />service/ingress-nginx-controller-admission   ClusterIP      10.100.150.114   <none>                                                                          443/TCP                      24s<br /><br />NAME                                       READY   UP-TO-DATE   AVAILABLE   AGE<br />deployment.apps/ingress-nginx-controller   1/1     1            1           24s<br /><br />NAME                                                  DESIRED   CURRENT   READY   AGE<br />replicaset.apps/ingress-nginx-controller-757bfcbc6d   1         1         1       24s<br /><br />NAME                                       STATUS     COMPLETIONS   DURATION   AGE<br />job.batch/ingress-nginx-admission-create   Complete   1/1           4s         24s<br />job.batch/ingress-nginx-admission-patch    Complete   1/1           5s         24s</pre> | DevOps 工程师 | 
| 为示例 HTTPd 工作负载创建新的入口。 | 输入以下命令为现有示例 HTTPd 工作负载创建新的入口：<pre>kubectl create ingress demo-new --class=nginx-v2 \<br />  --rule nginxautomode.local.dev/=demo:80</pre> | DevOps 工程师 | 
| 确认新的入口工作正常。 | 输入以下命令确认新的入口是否工作正常：<pre>curl -H "Host: nginxautomode.local.dev" k8s-ingressn-ingressn-2e5e37fab6-848337cd9c9d520f.elb.eu-west-1.amazonaws.com</pre>预期的输出如下所示：<pre><html><body><h1>It works!</h1></body></html></pre> | DevOps 工程师 | 

### 割接
<a name="cut-over"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 割接至新的命名空间。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-nginx-ingress-controller-eks-auto-mode.html) | AWS DevOps， DevOps 工程师 | 
| 查看两个入口。 | 输入以下命令以查看为示例 HTTPd 工作负载创建的两个入口：<pre>kubectl get ingress</pre>下面是一个示例输出：<pre>NAME       CLASS      HOSTS                                  ADDRESS                                                                         PORTS   AGE<br />demo       nginx      nginxautomode.local.dev   k8s-ingressn-ingressn-abcdefg-12345.elb.eu-west-1.amazonaws.com                              80      95m<br />demo-new   nginx-v2   nginxautomode.local.dev   k8s-ingressn-ingressn-2e5e37fab6-848337cd9c9d520f.elb.eu-west-1.amazonaws.com                80      33s</pre> | DevOps 工程师 | 

## 相关资源
<a name="migrate-nginx-ingress-controller-eks-auto-mode-resources"></a>
+ [在现有集群上启用 EKS 自动模式](https://docs.aws.amazon.com/eks/latest/userguide/auto-enable-existing.html)（Amazon EKS 文档）
+ 对@@ [由 Kubernetes 服务控制器在 Amazon EKS 中创建的负载均衡器进行故障排除（re: Post 知识](https://repost.aws/knowledge-center/eks-load-balancers-troubleshooting)中心）AWS 
+ [NGINX 入口控制器](https://docs.nginx.com/nginx-ingress-controller/)（NGINX 文档）

# 将你的容器工作负载从 Azure 红帽 OpenShift (ARO) 迁移到 AWS 云端 Red Hat OpenShift 服务 (ROSA)
<a name="migrate-container-workloads-from-aro-to-rosa"></a>

*Naveen Ramasamy、Srikanth Rangavajhala 和 Gireesh Sreekantan，Amazon Web Services*

## Summary
<a name="migrate-container-workloads-from-aro-to-rosa-summary"></a>

此模式提供了将容器工作负载从 Azure 红帽 OpenShift (ARO) 迁移到 [AWS 云端 Red Hat OpenShift 服务 (ROSA)](https://aws.amazon.com/rosa/) 的 step-by-step说明。ROSA 是一项托管 Kubernetes 服务，由红帽与之合作提供。 AWS它可以帮助您使用 Kubernetes 平台部署、管理和扩展容器化应用程序，并受益于红帽在 Kubernetes 和基础设施方面的专业知识。 AWS 云 

要将容器工作负载从 ARO、其他云或本地迁移到 ROSA，我们需要将应用程序、配置和数据从一个平台转移到另一个平台。这种模式有助于确保平稳过渡，同时优化 AWS 云 服务、安全性和成本效益。它涵盖了将工作负载迁移到 ROSA 集群的两种方法： CI/CD 以及容器迁移工具包 (MTC)。

此模式涵盖了这两种方法。具体选择哪种方法，取决于迁移过程的复杂性和确定性。如果您完全控制应用程序的状态，并且可以通过管道保证设置的一致性，我们建议您使用该 CI/CD 方法。但如果您的应用程序状态涉及不确定性、不可预见的变更或复杂的生态系统，我们建议您使用 MTC 作为可靠且受控的路径，将应用程序及其数据迁移至新集群。有关这两种方法的详细比较，请参阅[其他信息](#migrate-container-workloads-from-aro-to-rosa-additional)部分。

迁移到 ROSA 的好处：
+ ROSA AWS 作为本机服务无缝集成。可通过轻松访问 AWS 管理控制台 并通过单 AWS 账户笔计费。它与其他产品完全兼容 AWS 服务 ，并提供双方 AWS 和红帽的协作支持。
+ ROSA 支持混合及多云部署 它使得应用程序能够在本地数据中心和多个云环境中一致运行。
+ ROSA 受益于 Red Hat 的安全理念，提供基于角色的访问控制（RBAC）、图像扫描和漏洞评估等功能，从而确保容器环境安全。
+ ROSA 旨在轻松扩展应用程序，并提供高可用性选项。它允许应用程序根据需要扩展，同时维持可靠性。
+ 与手动设置和管理方法相比，ROSA 可以自动执行和简化 Kubernetes 集群的部署。这加快了开发和部署过程。
+ ROSA 受益于 AWS 云 服务，并提供与数据库服务、存储解决方案和安全服务等 AWS 产品的无缝集成。

## 先决条件和限制
<a name="migrate-container-workloads-from-aro-to-rosa-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ 为 AWS 服务 此 ROSA 配置的权限依赖于提供功能。有关更多信息，请参阅 ROSA 文档中的[先决条件](https://docs.aws.amazon.com/rosa/latest/userguide/set-up.html)。
+ 已在 [ROSA 控制台](https://console.aws.amazon.com/rosa)上启用 ROSA。有关说明，请参阅 [ROSA 文档](https://docs.aws.amazon.com/rosa/latest/userguide/set-up.html#enable-rosa)。
+ 已安装并配置 ROSA 集群。有关更多信息，请参阅 ROSA 文档中的[开始使用 ROSA](https://docs.aws.amazon.com/rosa/latest/userguide/getting-started.html)。要了解设置 ROSA 集群的不同方法，请参阅 AWS 规范性指导指南 [ROSA 实现策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/red-hat-openshift-on-aws-implementation/)。
+ 建立从本地网络到 AWS 通过 [AWS Direct Connect](https://docs.aws.amazon.com/whitepapers/latest/aws-vpc-connectivity-options/aws-direct-connect.html)（首选）或 [AWS Virtual Private Network （Site-to-Site VPN）](https://docs.aws.amazon.com/vpc/latest/userguide/vpn-connections.html)的网络连接。
+ 亚马逊弹性计算云 (Amazon EC2) 实例或其他虚拟服务器，用于安装 OpenShift CLI (`oc`) 客户端`aws client`、ROSA 客户端和 Git 二进制文件等工具。

该 CI/CD 方法的其他先决条件：
+ 访问本地 Jenkins 服务器，拥有创建新管道、添加阶段、添加 OpenShift 集群和执行构建的权限。
+ 访问维护应用程序源代码的 Git 存储库，拥有创建新 Git 分支并向新分支执行提交的权限。

MTC 方法的其他先决条件：
+ Amazon Simple Storage Service（Amazon S3）存储桶，将用作复制存储库。
+ 对源 ARO 集群的管理访问权限。这是设置 MTC 连接所必需的。

**限制**
+ 有些 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="migrate-container-workloads-from-aro-to-rosa-architecture"></a>

ROSA 提供三种网络部署模式：公共、私有和[AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html)。 PrivateLink使红帽站点可靠性工程 (SRE) 团队能够使用连接到现有 VPC 中集群 PrivateLink 终端节点的私有子网来管理集群。

选择该 PrivateLink选项可提供最安全的配置。因此，我们建议将其用于敏感工作负载或严格的合规要求场景。有关公网和私有网络部署选项的信息，请参阅[红帽 OpenShift 文档](https://docs.openshift.com/rosa/architecture/rosa-architecture-models.html#rosa-hcp-architecture_rosa-architecture-models)。

**重要**  
您只能在安装时创建 PrivateLink 集群。安装 PrivateLink 后，您无法更改要使用的群集。

下图说明了用于 Direct Connect 连接到本地和 ARO 环境的 ROSA 集群的 PrivateLink 架构。

![\[使用 AWS Direct Connect 和 AWS 的 ROSA 集群 PrivateLink。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/527cedfb-ec21-42be-bf21-d4e4e4f9db51/images/eff9b017-6fc7-4874-b610-849a42071ef4.png)


**AWS 对 ROSA 的权限**

要获 AWS 得 ROSA 的权限，我们建议您将 AWS Security Token Service (AWS STS) 与短期动态令牌一起使用。此方法使用最低权限的预定义角色和策略来授予 ROSA 在中操作的最低权限 AWS 账户，并支持 ROSA 安装、控制平面和计算功能。

**CI/CD 管道重新部署**

CI/CD pipeline redeployment is the recommended method for users who have a mature CI/CD管道。选择此选项后，您可以使用任何[DevOps 部署策略](https://docs.aws.amazon.com/whitepapers/latest/introduction-devops-aws/deployment-strategies.html)将应用程序负载逐渐转移到 ROSA 上的部署。

**注意**  
这种模式假设了一个常见的用例，即你有一个本地 Git、Artif JFrog actory 和 Jenkins 管道。这种方法要求您建立从本地网络到 AWS 直通的网络连接 Direct Connect，并且必须先设置 ROSA 集群，然后再按照 [Epics](#migrate-container-workloads-from-aro-to-rosa-epics) 部分中的说明进行操作。有关详细信息，请参阅[先决条件](#migrate-container-workloads-from-aro-to-rosa-prereqs)部分。

下图显示了此方法的工作流：

![\[使用 CI/CD 方法将容器从 ARO 迁移到 ROSA。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/527cedfb-ec21-42be-bf21-d4e4e4f9db51/images/f658590e-fbd9-4297-a02c-0b516694d436.png)


**MTC 方法**

可以使用[容器迁移工具包（MTC）](https://docs.openshift.com/container-platform/4.13/migration_toolkit_for_containers/about-mtc.html)** **在不同的 Kubernetes 环境之间迁移容器化工作负载，例如从 ARO 迁移到 ROSA。MTC 通过自动处理若干关键任务，并提供全面的迁移生命周期管理框架，从而简化了迁移过程。

下图显示了此方法的工作流：

![\[使用 MTC 方法将容器从 ARO 迁移到 ROSA。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/527cedfb-ec21-42be-bf21-d4e4e4f9db51/images/979bbc7b-2e39-4dd1-b4f0-ea1032880a38.png)


## 工具
<a name="migrate-container-workloads-from-aro-to-rosa-tools"></a>

**AWS 服务**
+ [AWS DataSync](https://docs.aws.amazon.com/datasync/latest/userguide/what-is-datasync.html)是一项在线数据传输和发现服务，可帮助您在 AWS 存储服务之间移动文件或对象数据。
+ [AWS Direct Connect](https://docs.aws.amazon.com/directconnect/latest/UserGuide/Welcome.html)通过标准的以太网光纤电缆将您的内部网络链接到某个 Direct Connect 位置。通过此连接，您可以直接创建面向公众的虚拟接口， AWS 服务 同时绕过网络路径中的互联网服务提供商。
+ [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html)帮助您创建从您的虚拟私有云 (VPCs) 到 VPC 外部服务的单向私有连接。
+ [AWS 云端 Red Hat OpenShift 服务 (ROSA)](https://docs.aws.amazon.com/rosa/latest/userguide/what-is-rosa.html) 是一项托管服务，可帮助红帽 OpenShift 用户在上构建、扩展和管理容器化应用程序。 AWS
+ [AWS Security Token Service (AWS STS)](https://docs.aws.amazon.com/STS/latest/APIReference/welcome.html) 可帮助您为用户申请临时的有限权限证书。

**其他工具**
+ [容器迁移工具包（MTC）](https://docs.openshift.com/container-platform/4.13/migration_toolkit_for_containers/about-mtc.html)提供用于将容器化应用程序从 ARO 迁移到 ROSA 的控制台和 API。

## 最佳实践
<a name="migrate-container-workloads-from-aro-to-rosa-best-practices"></a>
+ 为了[提高弹性](https://docs.aws.amazon.com/ROSA/latest/userguide/disaster-recovery-resiliency.html)，如果您有安全合规性工作负载，请设置一个使用的 PrivateLink多可用区 ROSA 集群。有关更多信息，请参阅 [ROSA 文档](https://docs.aws.amazon.com/rosa/latest/userguide/getting-started-classic-private-link.html)。
**注意**  
PrivateLink 安装后无法进行配置。
+ 用于复制存储库的 S3 存储桶不应设置为公开状态。使用相应的 S3 存储桶策略来限制访问权限。
+ 如果选择 MTC 方法，请使用**阶段**迁移选项来缩短割接期间的停机时间。
+ 在预调配 ROSA 集群之前和之后，请检查您的服务配额。如有必要，可以根据要求申请增加配额。有关更多信息，请参阅[服务配额文档](https://docs.aws.amazon.com/servicequotas/latest/userguide/request-quota-increase.html)。
+ 查看 [ROSA 安全指南](https://docs.aws.amazon.com/ROSA/latest/userguide/security.html)并实施安全最佳实践。
+ 我们建议您在安装后移除默认集群管理员。有关更多信息，请参阅[红帽 OpenShift 文档](https://docs.openshift.com/container-platform/4.13/post_installation_configuration/cluster-tasks.html)。
+ 使用机器池自动缩放功能，缩减 ROSA 集群中未使用的 Worker 节点，从而优化成本。有关更多信息，请参阅 [ROSA 讲习会](https://catalog.workshops.aws/aws-openshift-workshop/en-US/5-nodes-storage/3-autoscale-machine-pool)。
+ 使用红帽 OpenShift 容器平台成本管理服务，更好地了解和跟踪云和容器的成本。有关更多信息，请参阅 [ROSA 讲习会](https://catalog.workshops.aws/aws-openshift-workshop/en-US/10-cost-management)。
+ 使用监控和审计 ROSA 集群基础架构服务和应用程序 AWS 服务。有关更多信息，请参阅 [ROSA 讲习会](https://catalog.workshops.aws/aws-openshift-workshop/en-US/8-observability)。

## 操作说明
<a name="migrate-container-workloads-from-aro-to-rosa-epics"></a>

### 选项 1：使用 CI/CD 管道
<a name="option-1-use-a-ci-cd-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将新的 ROSA 集群添加到 Jenkins。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-container-workloads-from-aro-to-rosa.html) | AWS 管理员、AWS 系统管理员、AWS DevOps | 
| 将 `oc` 客户端添加到您的 Jenkins 节点。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-container-workloads-from-aro-to-rosa.html) | AWS 管理员、AWS 系统管理员、AWS DevOps | 
| 创建新的 Git 分支。 | 在您的 Git 存储库中为 `rosa-dev` 创建一个新的分支。此分支将 ROSA 的代码或配置参数变更与您的现有管道分开。 | AWS DevOps | 
| 为 ROSA 标记图像。 | 在构建阶段，使用不同的标签来标识通过 ROSA 管道构建的图像。 | AWS 管理员、AWS 系统管理员、AWS DevOps | 
| 创建管道。 | 创建一个与现有管道相似的新 Jenkins 管道。对于此管道，请使用您之前创建的 `rosa-dev` Git 分支，并确保包含与现有管道相同的 Git 签出、代码扫描和构建阶段。 | AWS 管理员、AWS 系统管理员、AWS DevOps | 
| 添加 ROSA 部署阶段。 | 在新管道中，添加一个部署到 ROSA 集群的阶段，并引用您添加到 Jenkins 全局配置中的 ROSA 集群。 | AWS 管理员、AWS DevOps、AWS 系统管理员 | 
| 开始新的构建操作。 | 在 Jenkins 中，选择管道并选择**立即构建**，或者通过在 Git 中提交对 `rosa-dev` 分支的更改来开始新的构建操作。 | AWS 管理员、AWS DevOps、AWS 系统管理员 | 
| 验证部署。 | 使用 **oc** 命令或 [ROSA 控制台](https://console.aws.amazon.com/rosa)验证是否已在您的目标 ROSA 集群上部署应用程序。 | AWS 管理员、AWS DevOps、AWS 系统管理员 | 
| 将数据复制到目标集群。 | 对于有状态的工作负载，请使用 AWS DataSync 诸如 **rsync** 之类的开源实用程序将数据从源集群复制到目标集群，也可以使用 MTC 方法。有关详情，请参阅 [AWS DataSync 文档](https://docs.aws.amazon.com/datasync/latest/userguide/what-is-datasync.html)。 | AWS 管理员、AWS DevOps、AWS 系统管理员 | 
| 测试您的应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-container-workloads-from-aro-to-rosa.html) | AWS 管理员、AWS DevOps、AWS 系统管理员 | 
| 割接。 | 如果测试成功，请使用相应的 Amazon Route 53 策略将流量从 ARO 托管的应用程序转移到 ROSA 托管的应用程序。完成此步骤后，您的应用程序的工作负载将完全迁移到 ROSA 集群。 | AWS 管理员、AWS 系统管理员 | 

### 选项 2：使用 MTC
<a name="option-2-use-mtc"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装 MTC 操作程序。 | 在 ARO 和 ROSA 集群上安装 MTC 操作程序：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-container-workloads-from-aro-to-rosa.html) | AWS 管理员、AWS DevOps、AWS 系统管理员 | 
| 配置到复制存储库的网络流量。 | 如果您使用的是代理服务器，请将其配置为允许复制存储库与集群之间的网络流量。复制存储库是 MTC 用来迁移数据的中间存储对象。迁移期间，源集群和目标集群必须具有对复制存储库的网络访问权限。 | AWS 管理员、AWS DevOps、AWS 系统管理员 | 
| 将源集群添加到 MTC。 | 在 MTC Web 控制台上，添加 ARO 源集群。 | AWS 管理员、AWS DevOps、AWS 系统管理员 | 
| 将 Amazon S3 添加为复制存储库。 | 在 MTC Web 控制台上，将 Amazon S3 存储桶（参见[先决条件](#migrate-container-workloads-from-aro-to-rosa-prereqs)）添加为复制存储库。 | AWS 管理员、AWS DevOps、AWS 系统管理员 | 
| 制定迁移计划。 | 在 MTC Web 控制台上，创建迁移计划并将数据传输类型指定为**复制**。这将指示 MTC 将数据从源（ARO）集群复制到 S3 存储桶，然后从存储桶复制到目标（ROSA）集群。 | AWS 管理员、AWS DevOps、AWS 系统管理员 | 
| 运行迁移计划。 | 使用**分阶段**或**割接**选项运行迁移计划：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-container-workloads-from-aro-to-rosa.html) | AWS 管理员、AWS DevOps、AWS 系统管理员 | 

## 问题排查
<a name="migrate-container-workloads-from-aro-to-rosa-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 连接问题 | 当您将容器工作负载从 ARO 迁移到 ROSA 时，可能会遇到连接问题，应解决这些问题以确保迁移成功。为解决迁移过程中出现的连接问题（详见本表），必须进行周密规划、与网络和安全团队协调配合，并开展全面测试。实施分阶段迁移策略并在每个阶段验证连接性，将有助于最大限度地减少潜在的中断，并确保平稳从 ARO 迁移到 ROSA。 | 
| 网络配置差异 | ARO 和 ROSA 的网络配置可能有所不同，例如虚拟网络 (VNet) 设置、子网和网络策略。为确保服务间通信顺畅，请确认两个平台的网络设置保持一致。 | 
| 安全组和防火墙规则 | ROSA 和 ARO 的默认安全组和防火墙设置可能有所不同。请务必调整和更新这些规则，以允许必要的流量，在迁移过程中保持容器和服务的连通性。  | 
| IP 地址和 DNS 变更 | 迁移工作负载时，IP 地址和 DNS 名称可能发生变化。重新配置依赖静态 IPs 或特定 DNS 名称的应用程序。  | 
| 外部服务访问权限 | 如果您的应用程序依赖外部服务（例如数据库或） APIs，则可能需要更新其连接设置以确保它们可以与 ROSA 的新服务进行通信。 | 
| Azure Private Link 配置 | 如果在 ARO 中使用 Azure Private Link 或私有端点服务，则需在 ROSA 中配置等效功能，以确保资源间的私有连接。 | 
| Site-to-Site VPN 或 Direct Connect 设置  | 如果您的本地网络与 ARO 之间存在 Direct Connect 连接 Site-to-Site VPN 或连接，则需要与 ROSA 建立类似的连接，以便与本地资源进行不间断的通信。 | 
| 入口和负载均衡器设置 | ARO 与 ROSA 中的入口控制器和负载均衡器配置可能有所不同。重新配置这些设置可保持对服务的外部访问权限。 | 
| 证书和 TLS 处理 | 如果您的应用程序使用 SSL 证书或 TLS，请确保这些证书在 ROSA 中有效且配置正确。 | 
| 容器注册表访问权限 | 如果您的容器托管在外部容器注册表中，请为 ROSA 设置正确的身份验证和访问权限。 | 
| 监控和日志记录 | 更新监控和日志记录配置，以反映 ROSA 上的新基础设施，以便您可以继续有效地监控容器的运行状况和性能。 | 

## 相关资源
<a name="migrate-container-workloads-from-aro-to-rosa-resources"></a>

**AWS****参考文献**
+ [什么是 AWS 云端 Red Hat OpenShift 服务？](https://docs.aws.amazon.com/ROSA/latest/userguide/what-is-rosa.html) （ROSA 文档）
+ [开始使用 ROSA](https://docs.aws.amazon.com/ROSA/latest/userguide/getting-started.html)（ROSA 文档）
+ [AWS 云端 Red Hat OpenShift 服务 实施策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/red-hat-openshift-on-aws-implementation/)（AWS 规范性指导）
+ [AWS 云端 Red Hat OpenShift 服务 现在 GA](https://aws.amazon.com/blogs/aws/red-hat-openshift-service-on-aws-now-generally-availably/)（AWS 博客文章）
+ [ROSA 讲习会](https://catalog.workshops.aws/aws-openshift-workshop/en-US/0-introduction)
+ [ROSA 常见问题解答](https://aws.amazon.com/rosa/faqs/)
+ [ROSA 讲习会常见问题解答](https://www.rosaworkshop.io/rosa/14-faq/)
+ [ROSA 定价](https://aws.amazon.com/rosa/pricing/)

**红帽 OpenShift 文档**
+ [快速安装集群 AWS](https://docs.openshift.com/container-platform/4.13/installing/installing_aws/installing-aws-default.html)
+ [在受限网络 AWS 中安装集群](https://docs.openshift.com/container-platform/4.13/installing/installing_aws/installing-restricted-networks-aws-installer-provisioned.html)
+ [在现有 VPC AWS 上安装集群](https://docs.openshift.com/container-platform/4.13/installing/installing_aws/installing-aws-vpc.html)
+ [使用模板在用户配置的基础架构上 AWS 安装集群 CloudFormation ](https://docs.openshift.com/container-platform/4.13/installing/installing_aws/installing-aws-user-infra.html)
+ [在具有用户配置基础 AWS 架构的受限网络中安装集群](https://docs.openshift.com/container-platform/4.13/installing/installing_aws/installing-restricted-networks-aws.html)
+ [使用自定义功能安装 AWS 集群](https://docs.openshift.com/container-platform/4.13/installing/installing_aws/installing-aws-customizations.html)
+ [ OpenShift CLI 入门](https://docs.openshift.com/container-platform/4.13/cli_reference/openshift_cli/getting-started-cli.html)

## 附加信息
<a name="migrate-container-workloads-from-aro-to-rosa-additional"></a>

**在 MTC 和 CI/CD 管道重新部署选项之间进行选择**

将应用程序从一个 OpenShift 集群迁移到另一个集群需要仔细考虑。理想情况下，您希望通过使用 CI/CD 管道来重新部署应用程序并处理永久卷数据的迁移，从而实现平稳过渡。然而，实际上，集群上运行的应用程序容易受到随时间推移而出现的不可预见的变更影响。这些变更可能导致应用程序逐步偏离其原始部署状态。MTC 针对以下场景提供了解决方案：当命名空间的确切内容不确定时，需要将所有应用程序组件无缝迁移到新集群。

做出正确选择需要评估具体情况，并权衡每种方法的利弊。通过这样做，您可以确保迁移过程顺利无缝，并符合您的需求和优先级。以下是关于如何在两个选项之间进行取舍的补充指导原则。

**CI/CD 管道重新部署**

如果使用 CI/CD 管道可以放心地重新部署应用程序，则推荐使用管道方法。这样可以确保迁移过程可控且可预测，并与您现有的部署实践保持一致。选择此方法时，您可以使用[蓝绿部署](https://docs.aws.amazon.com/whitepapers/latest/overview-deployment-options/bluegreen-deployments.html)或金丝雀部署策略，将负载逐步转移到 ROSA 上的部署。在这种情况下，此模式假设 Jenkins 正在从本地环境协调应用程序部署。

优势：
+ 您无需对源 ARO 集群拥有管理员访问权限，也不需要将任何操作程序部署到源集群或目标集群上。
+ 这种方法可以帮助您使用 DevOps 策略逐步切换流量。

劣势：
+ 测试应用程序的功能需要投入更多精力。
+ 如果您的应用程序包含永久性数据，则需要额外的步骤才能使用 AWS DataSync 或其他工具来复制数据。

**MTC 迁移**

在现实世界中，运行中的应用程序可能会经历意外变化，导致其偏离初始部署状态。如果您不确定应用程序在源集群上的当前状态，请选择 MTC 选项。例如，如果您的应用程序生态系统涉及多种组件、配置和数据存储卷，我们建议您选择 MTC 来确保完成涵盖应用程序及其整个环境的完整迁移。

优势：
+ MTC 提供完整的工作负载备份和恢复功能。
+ 迁移工作负载时，它会把持久化数据从源端复制到目标端。
+ 不需要访问源代码存储库。

劣势：
+ 您需要管理权限才能在源集群和目标集群上安装 MTC 操作程序。
+ 该 DevOps 团队需要接受培训，才能使用 MTC 工具和执行迁移。

# 使用 Amazon ECS Anywhere 在亚马逊 WorkSpaces 上运行亚马逊 ECS 任务
<a name="run-amazon-ecs-tasks-on-amazon-workspaces-with-amazon-ecs-anywhere"></a>

*Akash Kumar，Amazon Web Services*

## Summary
<a name="run-amazon-ecs-tasks-on-amazon-workspaces-with-amazon-ecs-anywhere-summary"></a>

Amazon Elastic Container Service (Amazon ECS) Anywhere 支持在任何环境中部署 Amazon ECS 任务，包括Amazon Web Services (AWS) 托管基础设施和客户托管基础设施。您可以使用在云中运行且始终保持最新状态的完全由 AWS 托管的控制面板来执行此操作。 

企业经常使用 Amazon WorkSpaces 开发基于容器的应用程序。这需要亚马逊弹性计算云 (Amazon EC2) 或带有亚马逊 ECS 集群的 AWS Fargate 来测试和运行 ECS 任务。现在，通过使用 Amazon ECS Anywhere，您可以将亚马逊 WorkSpaces 作为外部实例直接添加到 ECS 集群，并且可以直接运行任务。这可以缩短您的开发时间，因为您可以在 Amazon 上使用本地的 ECS 集群测试容器 WorkSpaces。您还可以节省使用 EC2 或 Fargate 实例来测试容器应用程序的成本。

此模式展示了如何使用 Amazon ECS Anywhere 在亚马逊 WorkSpaces 上部署 ECS 任务。它设置 ECS 集群并使用 AWS Directory Service Simple AD 来启动 WorkSpaces。然后，示例 ECS 任务在中启动 NGINX。 WorkSpaces

## 先决条件和限制
<a name="run-amazon-ecs-tasks-on-amazon-workspaces-with-amazon-ecs-anywhere-prereqs"></a>
+ 一个有效的 Amazon Web Services account
+ AWS 命令行界面（AWS CLI）
+ [在您的计算机上配置的](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html) AWS 凭证

## 架构
<a name="run-amazon-ecs-tasks-on-amazon-workspaces-with-amazon-ecs-anywhere-architecture"></a>

**目标技术堆栈**
+ 虚拟私有云（VPC）
+ Amazon ECS 集群
+ Amazon WorkSpaces
+ 具有 Simple AD 的 AWS Directory Service

**目标架构 **

![\[ECS Anywhere 设置 ECS 群集并使用 Simple AD 启动 WorkSpaces。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/da8b2249-3423-485c-9fef-6f902025e969/images/fd354d14-f29b-4b9e-8f1a-c3cb7ed4d6bf.png)


 

该架构包括以下服务与资源：
+ 自定义 VPC 中具有公有子网和私有子网的 ECS 集群
+ 在 VPC 中使用 Simple AD 为用户提供访问亚马逊的权限 WorkSpaces
+ 亚马逊使用 Simple A WorkSpaces D 在 VPC 中进行了配置
+ AWS Systems Manager 已激活，可将亚马逊添加 WorkSpaces 为托管实例
+ 亚马逊使用 Amazon ECS 和 AWS Systems Manager 代理（SSM 代理） WorkSpaces 添加到 Systems Manager 和 ECS 集群中
+ 要在 ECS 集群中运行的 WorkSpaces ECS 任务示例

## 工具
<a name="run-amazon-ecs-tasks-on-amazon-workspaces-with-amazon-ecs-anywhere-tools"></a>
+ [AWS Directory Service Simple Active Directory（Simple AD）](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_simple_ad.html) 是由 Samba 4 Active Directory Compatible Server 提供支持的一个独立托管目录。Simple AD 提供了 AWS 托管 Microsoft AD 提供的部分功能，包括管理用户和安全连接亚马逊 EC2 实例的功能。
+ [Amazon Elastic Container Service（Amazon ECS）](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html)是一项快速、可扩展的容器管理服务，可帮助您运行、停止和管理集群上的容器。
+ [AWS Identity and Access Management (AWS IAM) ](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)通过控制验证和授权使用您 AWS 资源的用户，帮助您安全地管理对您 AWS 资源的访问。
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 可帮助您管理在 Amazon Web Services Cloud 中运行的应用程序和基础设施。它简化了应用程序和资源管理，缩短了检测和解决操作问题的时间，并帮助您大规模安全地管理 AWS 资源。
+ [亚马逊 WorkSpaces](https://docs.aws.amazon.com/workspaces/latest/adminguide/amazon-workspaces.html)可帮助您为用户配置基于云的虚拟 Microsoft Windows 或 Amazon Linux 桌面，即*WorkSpaces*。 WorkSpaces 无需购买和部署硬件或安装复杂的软件。

## 操作说明
<a name="run-amazon-ecs-tasks-on-amazon-workspaces-with-amazon-ecs-anywhere-epics"></a>

### 设置 ECS 集群
<a name="set-up-the-ecs-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建和配置 ECS 集群。 | 要创建 ECS 集群，按照 [AWS 文档](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create_cluster.html)中的说明进行操作，包括以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-amazon-ecs-tasks-on-amazon-workspaces-with-amazon-ecs-anywhere.html) | 云架构师 | 

### 启动 Amazon WorkSpaces
<a name="launch-amazon-workspaces"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 Simple AD 并启动亚马逊 WorkSpaces。 | 要为您新创建的 VPC 预置 Simple AD 目录并启动 Amazon WorkSpaces，请按照 [AWS 文档](https://docs.aws.amazon.com/workspaces/latest/adminguide/launch-workspace-simple-ad.html)中的说明进行操作。 | 云架构师 | 

### 为混合环境设置 AWS Systems Manager
<a name="set-up-aws-systems-manager-for-a-hybrid-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 下载随附脚本。 | 在本地计算机上，下载*附件*部分中的 `ssm-trust-policy.json` 和 `ssm-activation.json` 文件。 | 云架构师 | 
| 添加 IAM 角色。 | 根据业务需求添加环境变量。<pre>export AWS_DEFAULT_REGION=${AWS_REGION_ID}<br />export ROLE_NAME=${ECS_TASK_ROLE}<br />export CLUSTER_NAME=${ECS_CLUSTER_NAME}<br />export SERVICE_NAME=${ECS_CLUSTER_SERVICE_NAME}</pre>运行如下命令。<pre>aws iam create-role --role-name $ROLE_NAME --assume-role-policy-document file://ssm-trust-policy.json</pre> | 云架构师 | 
| 将 Amazon SSMManaged InstanceCore 策略添加到 IAM 角色中。 | 运行如下命令。<pre>aws iam attach-role-policy --role-name $ROLE_NAME --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore</pre> | 云架构师 | 
| 将 Amazon EC2 ContainerServicefor EC2 角色策略添加到 IAM 角色。 | 运行如下命令。<pre>aws iam attach-role-policy --role-name $ROLE_NAME --policy-arn arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role</pre> | 云架构师 | 
| 验证 IAM 角色。 | 要验证 IAM 角色，请运行以下命令。<pre>aws iam list-attached-role-policies --role-name $ROLE_NAME</pre> | 云架构师 | 
| 激活 Systems Manager。 | 运行如下命令。<pre>aws ssm create-activation --iam-role $ROLE_NAME | tee ssm-activation.json</pre> | 云架构师 | 

### 添加 WorkSpaces 到 ECS 集群
<a name="add-workspaces-to-the-ecs-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  Connect 到你的 WorkSpaces。 | 要连接和设置您的 WorkSpaces，请按照 [AWS 文档](https://docs.aws.amazon.com/workspaces/latest/userguide/workspaces-user-getting-started.html)中的说明进行操作。 | 应用程序开发人员 | 
| 下载 ecs-anywhere 安装脚本。 | 在命令提示符下，运行以下 命令。<pre>curl -o "ecs-anywhere-install.sh" "https://amazon-ecs-agent-packages-preview.s3.us-east-1.amazonaws.com/ecs-anywhere-install.sh" && sudo chmod +x ecs-anywhere-install.sh</pre> | 应用程序开发人员 | 
| 检查 Shell 脚本完整性。 | （可选）运行以下命令。<pre>curl -o "ecs-anywhere-install.sh.sha256" "https://amazon-ecs-agent-packages-preview.s3.us-east-1.amazonaws.com/ecs-anywhere-install.sh.sha256" && sha256sum -c ecs-anywhere-install.sh.sha256<br /><br /><br /></pre> | 应用程序开发人员 | 
| 在 Amazon Linux 上添加 EPEL 存储库。 | 若要添加企业 Linux (EPEL) 存储库，请运行命令 `sudo amazon-linux-extras install epel -y`。 | 应用程序开发人员 | 
| 安装 Amazon ECS Anywhere。 | 要运行安装脚本，请使用以下命令。<pre>sudo ./ecs-anywhere-install.sh --cluster $CLUSTER_NAME --activation-id $ACTIVATION_ID --activation-code $ACTIVATION_CODE --region $AWS_REGION<br /><br /><br /></pre> |  | 
| 查看 ECS 集群的实例信息。 | 要检查 Systems Manager 和 ECS 集群实例信息并验证 WorkSpaces 已添加到集群上，请在本地计算机上运行以下命令。<pre>aws ssm describe-instance-information" && "aws ecs list-container-instances --cluster $CLUSTER_NAME</pre> | 应用程序开发人员 | 

### 为添加 ECS 任务 WorkSpaces
<a name="add-an-ecs-task-for-the-workspaces"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建任务执行 IAM 角色。 | 从*附件*部分下载 `task-execution-assume-role.json` 和 `external-task-definition.json`。 在本地计算机上运行以下命令。<pre>aws iam --region $AWS_DEFAULT_REGION create-role --role-name $ECS_TASK_EXECUTION_ROLE --assume-role-policy-document file://task-execution-assume-role.json</pre> | 云架构师 | 
| 将策略添加到该角执行色。 | 运行如下命令。<pre>aws iam --region $AWS_DEFAULT_REGION attach-role-policy --role-name $ECS_TASK_EXECUTION_ROLE --policy-arn arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy</pre> | 云架构师 | 
| 创建任务角色。 | 运行如下命令。<pre>aws iam --region $AWS_DEFAULT_REGION create-role --role-name $ECS_TASK_EXECUTION_ROLE --assume-role-policy-document file://task-execution-assume-role.json<br /><br /><br /></pre> | 云架构师 | 
| 将任务定义注册到集群。 | 在本地计算机上运行以下命令。<pre>aws ecs register-task-definition --cli-input-json file://external-task-definition.json</pre> | 云架构师 | 
| 运行任务。 | 在本地计算机上运行以下命令。<pre>aws ecs run-task --cluster $CLUSTER_NAME --launch-type EXTERNAL --task-definition nginx</pre> | 云架构师 | 
| 验证任务运行状态。 | 若要获取任务 ID，请运行以下命令。<pre>export TEST_TASKID=$(aws ecs list-tasks --cluster $CLUSTER_NAME | jq -r '.taskArns[0]')</pre>使用任务 ID 运行以下命令。<pre>aws ecs describe-tasks --cluster $CLUSTER_NAME --tasks ${TEST_TASKID}</pre> | 云架构师 | 
| 在上验证任务 WorkSpace。 | 要检查 NGINX 是否在上运行 WorkSpace，请运行命令。` curl http://localhost:8080` | 应用程序开发人员 | 

## 相关资源
<a name="run-amazon-ecs-tasks-on-amazon-workspaces-with-amazon-ecs-anywhere-resources"></a>
+ [ECS 集群](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html)
+ [设置混合环境](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-managedinstances.html)
+ [Amazon WorkSpaces](https://docs.aws.amazon.com/workspaces/latest/adminguide/amazon-workspaces.html)
+ [Simple AD](https://docs.aws.amazon.com/workspaces/latest/adminguide/launch-workspace-simple-ad.html)

## 附件
<a name="attachments-da8b2249-3423-485c-9fef-6f902025e969"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/da8b2249-3423-485c-9fef-6f902025e969/attachments/attachment.zip)

# 在亚马 EC2 逊 Linux 实例上运行 ASP.NET Core Web API Docker 容器
<a name="run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance"></a>

*Vijai Anand Ramalingam 和 Sreelaxmi Pai，Amazon Web Services*

## Summary
<a name="run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance-summary"></a>

这种模式适用于开始在 Amazon Web Services (AWS) Cloud 上对其应用程序进行容器化的人员。当您开始在云上容器化应用程序时，通常没有设置容器编排平台。这种模式可以帮助您在 AWS 上快速设置基础设施来测试您的容器化应用程序，而无需复杂的容器编排基础设施。

现代化进程第一步是改造应用程序。如果是旧版.NET 框架应用程序，则必须先将其运行时系统更改为 ASP.NET Core。然后执行以下操作：
+ 创建 Docker 容器镜像
+ 从该镜像运行 Docker 容器。
+ 在将应用程序部署到任何容器编排平台（例如 Amazon Elastic Container Service (Amazon ECS) 或 Amazon Elastic Kubernetes Service (Amazon EKS)）之前验证应用程序。 

此模式涵盖了在亚马逊弹性计算云 (Amazon EC2) Linux 实例上构建、运行和验证现代应用程序开发的各个方面。

## 先决条件和限制
<a name="run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance-prereqs"></a>

**先决条件**
+ 一个活动 [Amazon Web Services (AWS) 账户](https://aws.amazon.com/account/)。
+ 要在这种模式下创建 AWS 资源，需要具有足够的 IAM 访问权限的 [AWS Identity and Access Management (IAM) 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)。 
+ [Visual Studio Community 2022](https://visualstudio.microsoft.com/downloads/) 或更新版本已下载并安装
+ 已升级为 ASP.NET Core 框架项目
+ 存储 GitHub 库

**产品版本**
+ Visual Studio Community 2022 及以上版本

## 架构
<a name="run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance-architecture"></a>

**目标架构**

此模式使用 A [WS CloudFormation 模板](https://console.aws.amazon.com/cloudformation/home?region=us-east-2#/stacks/new?stackName=SSM-SSH-Demo&templateURL=https://aws-quickstart.s3.amazonaws.com/quickstart-examples/samples/session-manager-ssh/session-manager-example.yaml)创建高可用架构，如下图所示。Amazon EC2 Linux 实例在私有子网中启动。AWS Systems Manager 会话管理器用于访问私有 Amazon EC2 Linux 实例和测试 Docker 容器中运行的 API。

![\[访问亚马逊 EC2 Linux 实例并测试在 Docker 容器中运行的 API 的用户。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/512e61b2-10ba-43be-bbd8-2bdc597c3de3/images/9c5206f6-32b1-47be-9037-360c0bff713c.png)


1. 通过 Session Manager 访问 Linux 实例

## 工具
<a name="run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance-tools"></a>

**Amazon Web Services**
+ [AWS 命令行界面](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) - AWS 命令行界面（AWS CLI）是一种开源工具，它使您能够使用命令行 Shell 中的命令与 Amazon Web Services 交互。仅需最少的配置，即可使用 AWS CLI 开始运行命令，以便从终端程序中的命令提示符实现与基于浏览器的 AWS 管理控制台 所提供的功能等同的功能：
+ [AWS 管理控制台](https://docs.aws.amazon.com/awsconsolehelpdocs/latest/gsg/learn-whats-new.html) - AWS 管理控制台是一款 Web 应用程序，其中包含并引用了多种用于管理 AWS 资源的服务控制台。首次登录时，您会看到控制台主页。主页提供了对每个服务控制台的访问权限，并提供了访问执行 AWS 相关任务所需信息的单一位置。
+ [AWS Systems Manager 会话管理器](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html) – 会话管理器是一项完全托管的 AWS Systems Manager 功能。使用会话管理器，您可以管理您的亚马逊弹性计算云 (Amazon EC2) 实例。Session Manager 提供安全且可审计的节点管理，无需打开入站端口、维护堡垒主机或者管理 SSH 密钥。

**其他工具**
+ [Visual Studio 2022](https://visualstudio.microsoft.com/downloads/) – Visual Studio 2022 是一种集成式开发环境（IDE）。
+ [Docker](https://www.docker.com/) - Docker 是一组平台即服务（PaaS）产品，它们使用操作系统级别的虚拟化技术在容器中交付软件。

**代码**

```
FROM mcr.microsoft.com/dotnet/aspnet:5.0 AS base
 WORKDIR /app
EXPOSE 80
EXPOSE 443
 
FROM mcr.microsoft.com/dotnet/sdk:5.0 AS build
WORKDIR /src
COPY ["DemoNetCoreWebAPI/DemoNetCoreWebAPI.csproj", "DemoNetCoreWebAPI/"]
RUN dotnet restore "DemoNetCoreWebAPI/DemoNetCoreWebAPI.csproj"
COPY . .
WORKDIR "/src/DemoNetCoreWebAPI"
RUN dotnet build "DemoNetCoreWebAPI.csproj" -c Release -o /app/build
 
FROM build AS publish
RUN dotnet publish "DemoNetCoreWebAPI.csproj" -c Release -o /app/publish
 
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "DemoNetCoreWebAPI.dll"]
```

## 操作说明
<a name="run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance-epics"></a>

### 开发ASP.NET Core web API
<a name="develop-the-asp-net-core-web-api"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 Visual Studio 创建 ASP.NET Core web API | 要创建示例 ASP.NET Core web API，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance.html) | 应用程序开发人员 | 
| 创建 Dockerfile。 | 要创建新文件，请执行以下操作之一：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance.html)要将更改推送到您的 GitHub 存储库，请运行以下命令。<pre>git add --all<br />git commit -m "Dockerfile added"<br />git push</pre> | 应用程序开发人员 | 

### 设置亚马逊 EC2 Linux 实例
<a name="set-up-the-amazon-ec2-linux-instance"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置基础设施。 | 启动 A [WS CloudFormation 模板](https://console.aws.amazon.com/cloudformation/home?region=us-east-2#/stacks/new?stackName=SSM-SSH-Demo&templateURL=https://aws-quickstart.s3.amazonaws.com/quickstart-examples/samples/session-manager-ssh/session-manager-example.yaml)以创建基础设施，其中包括以下内容： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance.html)要详细了解如何使用会话管理器访问私有 Amazon EC2 实例，无需堡垒主机，请参阅[迈向无堡垒世界博](https://aws.amazon.com/blogs/infrastructure-and-automation/toward-a-bastion-less-world/)客文章。 | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 登录亚马逊 EC2 Linux 实例。 | 要连接到私有子网中的 Amazon EC2 Linux 实例，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance.html) | 应用程序开发人员 | 
| 安装并运行 Docker | 要在亚马逊 EC2 Linux 实例中安装并启动 Docker，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 安装 Git 并克隆存储库。 | 要在 Amazon EC2 Linux 实例上安装 Git 并从中克隆存储库 GitHub，请执行以下操作。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 运行 Docker 容器。 | 要构建 Docker 镜像并在亚马逊 EC2 Linux 实例中运行容器，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 

### 测试 web API
<a name="test-the-web-api"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 curl 命令测试 Web API。 | 使用以下命令可运行 RSA 测试。<pre>curl -X GET "http://localhost/WeatherForecast" -H  "accept: text/plain"</pre>验证 API 响应。本地运行 Swagger 时，可以从 Swagger 获取每个端点的 curl 命令。 | 应用程序开发人员 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除资源 | 删除堆栈，以移除所有资源。这确保您不会为未使用的任何服务付费。 | AWS 管理员，AWS DevOps | 

## 相关资源
<a name="run-an-asp-net-core-web-api-docker-container-on-an-amazon-ec2-linux-instance-resources"></a>
+ [使用 PuTTY 从 Windows 连接到 Linux 实例](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/putty.html)
+ [使用 ASP.NET Core 创建 Web API](https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-5.0&tabs=visual-studio)
+ [走向没有堡垒的世界](https://aws.amazon.com/blogs/infrastructure-and-automation/toward-a-bastion-less-world/)

# 使用带 AWS Fargate 的 Amazon EFS on Amazon EKS，运行带持久数据存储的有状态工作负载
<a name="run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate"></a>

*Ricardo Morais、Rodrigo Bersa 和 Lucio Pereira，Amazon Web Services*

## Summary
<a name="run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-summary"></a>

此模式为使用 AWS Fargate 预调配计算资源来启用 Amazon Elastic File System（Amazon EFS）作为在 Amazon Elastic Kubernetes Service（Amazon EKS）上运行的容器的存储设备的提供了指导。

此模式中描述的设置遵循安全最佳实践，默认提供静态安全性和传输安全性。若要加密您的 Amazon EFS 文件系统，请使用 AWS Key Management Service (AWS KMS) 密钥，但您也可以指定密钥别名来调度 KMS 密钥创建过程。

您可以按照此模式中的步骤为 proof-of-concept (PoC) 应用程序创建命名空间和 Fargate 配置文件，安装用于将 Kubernetes 集群与 Amazon EFS 集成的亚马逊 EFS 容器存储接口 (CSI) 驱动程序，配置存储类并部署 PoC 应用程序。这些步骤会生成 Amazon EFS 文件系统，该文件系统在多个 Kubernetes 工作负载之间共享，在 Fargate 上运行。此模式附带自动执行这些步骤的脚本。

如果您希望在容器化应用程序中实现数据持久化，并且希望避免在扩展操作期间丢失数据，可以使用此模式。例如：
+ **DevOps 工具** — 常见的场景是开发持续集成和持续交付（CI/CD) strategy. In this case, you can use Amazon EFS as a shared file system to store configurations among different instances of the CI/CD tool or to store a cache (for example, an Apache Maven repository) for pipeline stages among different instances of the CI/CD工具。
+ **Web 服务器** – 常见的场景为使用 Apache 作为 HTTP web 服务器。您可以将 Amazon EFS 用作共享文件系统，以存储在 Web 服务器的不同实例之间共享的静态文件。在此示例场景中，直接修改文件系统，而不是将静态文件融入 Docker 映像中。

## 先决条件和限制
<a name="run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 运行 Kubernetes 版本 1.17 或更高版本的现有 Amazon EKS 集群（已测试至版本 1.27）
+ 现有 Amazon EFS 文件系统，用于绑定 Kubernetes StorageClass 并动态配置文件系统
+ 集群管理权限
+ 配置为指向所需 Amazon EKS 集群的上下文

**限制**
+ 配合使用 Amazon EKS 与 Fargate 时需要考虑某些限制。例如，不支持使用某些 Kubernetes 结构，例如 DaemonSets 和特权容器。有关 Fargate 限制的更多信息，请参阅 Amazon EKS 文档中的 [AWS Fargate 注意事项](https://docs.aws.amazon.com/eks/latest/userguide/fargate.html#fargate-considerations)。
+ 此模式代码支持运行 Linux 或 macOS 的工作站。

**产品版本**
+ AWS 命令行界面（AWS CLI）版本 2 或更高版本
+ Amazon EFS CSI 驱动程序版本 1.0 或更高版本（已测试至版本 2.4.8）
+ eksctl 0.24.0 版本或更高版本（已测试至版本 0.158.0）
+ jq 版本 1.6 或更高版本
+ kubectl 版本 1.17 或更高版本（已测试至版本 1.27）
+ Kubernetes 版本 1.17 或更高版本（已测试至版本 1.27）

## 架构
<a name="run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-architecture"></a>

![\[使用 Amazon EFS 运行带持久化数据存储的有状态工作负载的架构图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/2487e285-269b-415b-a270-877f973e3aaf/images/ec8de63c-3307-4010-9e03-2bd7b9881fff.png)


目标架构由以下基础设施组成：
+ 虚拟私有云（VPC）
+ 两个可用区
+ 具有可访问互联网的 NAT 网关的公有子网
+ 具有 Amazon EKS 集群和 Amazon EFS 挂载目标（也称为*挂载点*）的私有子网
+ VPC 级别的 Amazon EFS

以下是 Amazon EKS 集群的环境基础设施：
+ 在命名空间层级适配 Kubernetes 构造的 AWS Fargate 配置文件
+ 包含以下组件的 Kubernetes 命名空间：
  + 跨可用区分布的两个应用程序容器组（pod）
  + 在集群层级与持久卷绑定的持久卷声明（PVC）
+ 绑定到命名空间中的 PVC 且指向集群外部私有子网中的 Amazon EFS 挂载目标的集群范围 PV

## 工具
<a name="run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-tools"></a>

**AWS 服务**
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一款开源工具，可用于从命令行与 AWS 服务进行交互。
+ [Amazon Elastic File System（Amazon EFS）](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html)可帮助您在 AWS 云端创建和配置共享文件系统。在此模式中，提供了可用于 Amazon EKS 的简单、可扩展、完全托管和共享的文件系统。
+ [Amazon Elastic Kubernetes Service（Amazon EKS）](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html)可帮助您在 AWS 上运行 Kubernetes，无需安装或操作您自己的集群。
+ [AWS Fargate](https://docs.aws.amazon.com/eks/latest/userguide/fargate.html) 是 Amazon EKS 的无服务器计算引擎。其为 Kubernetes 应用程序创建和管理计算资源。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可帮助您创建和控制加密密钥，以帮助保护您的数据。

**其他工具**
+ [Docker](https://www.docker.com/) 是一组平台即服务（PaaS）产品，它们利用操作系统级的虚拟化技术在容器中提供软件。
+ [eksctl](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html) 是一款命令行实用程序，用于在 Amazon EKS 上创建和管理 Kubernetes 集群。
+ [kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)：针对 Kubernetes 集群运行命令的命令行界面。
+ [jq](https://stedolan.github.io/jq/download/) 是一个用于解析 JSON 的命令行工具。

**代码**

此模式的代码在[使用 AWS Fargate 存储库的 Amazon EFS GitHub 持久性配置](https://github.com/aws-samples/eks-efs-share-within-fargate)中提供。这些脚本按操作说明整理，存放于 `epic01` 至 `epic06` 文件夹中，与此模式的[操作说明](#run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-epics)部分中的顺序相对应。

## 最佳实践
<a name="run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-best-practices"></a>

目标架构包括以下服务和组件，并遵循 [AWS Well-Architected Framework ](https://aws.amazon.com/architecture/well-architected/)最佳实践：
+ Amazon EFS 提供了一个简单、可扩展、完全托管的弹性 NFS 文件系统。这用作在容器组（pod）（分布在所选 Amazon EKS 集群的私有子网中）中运行的 PoC 应用程序的所有复制的共享文件系统。
+ 每个私有子网的 Amazon EFS 挂载目标。其为集群的虚拟私有云（VPC）中的每个可用区域提供冗余。
+ 运行 Kubernetes 工作负载的 Amazon EKS。您必须预置 Amazon EKS 集群，然后才能使用此模式，如[先决条件](#run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-prereqs)部分所述。
+ 为存储在 Amazon EFS 文件系统中的内容提供静态加密的 AWS KMS。
+ Fargate 管理容器的计算资源，因此您可以专注于业务需求而不是基础设施负担。Fargate 配置文件是为所有私有子网创建的。其为集群的虚拟私有云（VPC）中的每个可用区域提供冗余。
+ 用于验证内容是否可以由应用程序的不同实例共享、使用和编写的 Kubernetes 容器组（pod）。

## 操作说明
<a name="run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-epics"></a>

### 预调配 Amazon EKS 集群（可选）
<a name="provision-an-amazon-eks-cluster-optional"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个 Amazon EKS 集群。 | 如果您已部署集群，请跳至下一操作说明。在现有 AWS 账户中创建 Amazon EKS 集群。在[GitHub 目录](https://github.com/aws-samples/eks-efs-share-within-fargate/tree/master/bootstrap)中，使用其中一种模式使用 Terraform 或 eksctl 部署 Amazon EKS 集群。有关更多信息，请参阅 Amazon EKS 文档中的[创建 Amazon EKS 集群](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html)。在 Terraform 模式中，还提供了以下操作的示例：将 Fargate 配置文件关联到 Amazon EKS 集群、创建 Amazon EFS 文件系统，以及在 Amazon EKS 集群中部署 Amazon EFS CSI 驱动程序。 | AWS 管理员、Terraform 或 eksctl 管理员、Kubernetes 管理员 | 
| 导出环境变量。 | 运行 env.sh 脚本。该脚本会提供后续步骤所需的信息。<pre>source ./scripts/env.sh<br />Inform the AWS Account ID:<br /><13-digit-account-id><br />Inform your AWS Region:<br /><aws-Region-code><br />Inform your Amazon EKS Cluster Name:<br /><amazon-eks-cluster-name><br />Inform the Amazon EFS Creation Token:<br /><self-genereated-uuid></pre>如果尚未注明，则可通过以下 CLI 命令获取上述所需的全部信息。<pre># ACCOUNT ID<br />aws sts get-caller-identity --query "Account" --output text</pre><pre># REGION CODE<br />aws configure get region</pre><pre># CLUSTER EKS NAME<br />aws eks list-clusters --query "clusters" --output text</pre><pre># GENERATE EFS TOKEN<br />uuidgen</pre> | AWS 系统管理员 | 

### 创建 Kubernetes 命名空间和关联 Fargate 配置文件
<a name="create-a-kubernetes-namespace-and-a-linked-fargate-profile"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为应用程序工作负载创建 Kubernetes 命名空间和 Fargate 配置文件。 | 创建命名空间以接收与 Amazon EFS 交互的应用程序工作负载。运行 `create-k8s-ns-and-linked-fargate-profile.sh` 脚本。您可以选择使用自定义的命名空间名称或默认提供的命名空间 `poc-efs-eks-fargate`。**使用自定义的应用程序命名空间名称：**<pre>export $APP_NAMESPACE=<CUSTOM_NAME><br />./scripts/epic01/create-k8s-ns-and-linked-fargate-profile.sh \<br />-c "$CLUSTER_NAME" -n "$APP_NAMESPACE"</pre>**不使用自定义的应用程序命名空间名称：**<pre>./scripts/epic01/create-k8s-ns-and-linked-fargate-profile.sh \<br />    -c "$CLUSTER_NAME"</pre>其中，`$CLUSTER_NAME` 是 Amazon EKS 集群的名称。`-n <NAMESPACE>` 参数是可选的；如果未指定该参数，系统将提供默认生成的命名空间名称。 | 拥有授予权限的 Kubernetes 用户 | 

### 创建 Amazon EFS 文件系统
<a name="create-an-amazon-efs-file-system"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 生成唯一令牌。 | Amazon EFS 需要一个创建令牌，以确保幂等操作（使用相同的创建令牌调用该操作没有效果）。若要满足此要求，您必须通过可用技术生成唯一令牌。例如，您可以生成通用唯一标识符（UUID），以用作创建令牌。 | AWS 系统管理员 | 
| 创建 Amazon EFS 文件系统。 | 创建用于接收应用程序工作负载读取和写入数据文件的文件系统。您可以创建加密或非加密文件系统。（根据最佳实践标准，此模式的代码将创建加密系统，以默认启用静态加密。） 您可以使用唯一对称的 AWS KMS 密钥对文件系统进行加密。如果未指定自定义密钥，则使用 AWS 托管式密钥。为 Amazon EFS 生成唯一令牌后，使用 create-efs.sh 脚本创建加密或非加密 Amazon EFS 文件系统。**使用静态加密，无 KMS 密钥：**<pre>./scripts/epic02/create-efs.sh \<br />    -c "$CLUSTER_NAME" \<br />    -t "$EFS_CREATION_TOKEN"</pre>其中，`$CLUSTER_NAME` 是 Amazon EKS 集群的名称，`$EFS_CREATION_TOKEN` 是文件系统的唯一创建令牌。**使用静态加密，有 KMS 密钥：**<pre>./scripts/epic02/create-efs.sh \<br />    -c "$CLUSTER_NAME" \<br />    -t "$EFS_CREATION_TOKEN" \<br />    -k "$KMS_KEY_ALIAS"</pre>其中，`$CLUSTER_NAME` 是 Amazon EKS 集群的名称，`$EFS_CREATION_TOKEN` 是文件系统的唯一创建令牌，`$KMS_KEY_ALIAS` 是 KMS 密钥的别名。**不使用加密：**<pre>./scripts/epic02/create-efs.sh -d \<br />    -c "$CLUSTER_NAME" \<br />    -t "$EFS_CREATION_TOKEN"</pre>其中，`$CLUSTER_NAME` 是 Amazon EKS 集群的名称，`$EFS_CREATION_TOKEN` 是文件系统的唯一创建令牌，`–d` 禁用静态加密。 | AWS 系统管理员 | 
| 创建安全组。 | 创建允许 Amazon EKS 集群访问 Amazon EFS 文件系统的安全组。 | AWS 系统管理员 | 
| 更新安全组的入站规则 | 更新安全组的入站规则，以允许对传入流量进行以下设置：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate.html) | AWS 系统管理员 | 
| 为每个私有子网添加挂载目标。 | 对于 Kubernetes 集群的每个私有子网，请为文件系统和安全组创建挂载目标。 | AWS 系统管理员 | 

### 将 Amazon EFS 组件安装至 Kubernetes 集群
<a name="install-amazon-efs-components-into-the-kubernetes-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 Amazon EFS CSI 驱动程序。 | 将 Amazon EFS CSI 驱动程序部署至集群。驱动程序会根据应用程序创建的持久卷声明预调配存储。运行 `create-k8s-efs-csi-sc.sh` 脚本，以将 Amazon EFS CSI 驱动程序和存储类别部署到集群中。<pre>./scripts/epic03/create-k8s-efs-csi-sc.sh</pre>此脚本使用 `kubectl` 实用程序，因此请确保上下文已配置且指向所需的 Amazon EKS 集群。 | 拥有授予权限的 Kubernetes 用户 | 
| 部署存储类。 | 将 Amazon EFS 配置器 (efs.csi.aws.com) 的存储类部署至集群中。 | 拥有授予权限的 Kubernetes 用户 | 

### 将 PoC 应用程序安装至 Kubernetes 集群
<a name="install-the-poc-application-into-the-kubernetes-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署持久卷。 | 部署持久卷，并将其链接至创建的存储类和 Amazon EFS 文件系统的 ID。应用程序使用持久卷读取和写入内容。您可以在存储字段中为持久卷指定任何大小。Kubernetes 需要此字段，但由于 Amazon EFS 是弹性文件系统，因此其不会强制实施任何文件系统容量。您可以部署加密或不加密的持久卷。（根据最佳实践标准，Amazon EFS CSI 驱动程序默认启用加密。) 运行 `deploy-poc-app.sh` 脚本，以部署持久卷、持久卷声明和两个工作负载。**使用传输中加密：**<pre>./scripts/epic04/deploy-poc-app.sh \<br />    -t "$EFS_CREATION_TOKEN"</pre>其中，`$EFS_CREATION_TOKEN` 是文件系统的唯一创建令牌。**不使用传输中加密：**<pre>./scripts/epic04/deploy-poc-app.sh -d \<br />    -t "$EFS_CREATION_TOKEN"</pre>其中，`$EFS_CREATION_TOKEN` 是文件系统的唯一创建令牌，`–d` 禁用传输中加密。 | 拥有授予权限的 Kubernetes 用户 | 
| 部署应用程序请求的持久卷声明。 | 部署应用程序请求的持久卷声明，并将其链接到存储类别。使用与之前创建的持久卷相同的访问模式。您可以在存储字段中为持久卷声明指定任何大小。Kubernetes 需要此字段，但由于 Amazon EFS 是弹性文件系统，因此其不会强制实施任何文件系统容量。 | 拥有授予权限的 Kubernetes 用户 | 
| 部署工作负载 1。 | 部署可代表应用程序工作负载 1 的容器组（pod）。此工作负载会将内容写入文件 `/data/out1.txt`。 | 拥有授予权限的 Kubernetes 用户 | 
| 部署工作负载 2。 | 部署可代表应用程序工作负载 2 的容器组（pod）。此工作负载会将内容写入文件 `/data/out2.txt`。 | 拥有授予权限的 Kubernetes 用户 | 

### 验证文件系统的持久性、耐用性和可共享性
<a name="validate-file-system-persistence-durability-and-shareability"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 检查 `PersistentVolume` 的状态。 | 输入以下命令以检查 `PersistentVolume` 的状态。<pre>kubectl get pv</pre>有关示例输出，请参阅[其他信息](#run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-additional)部分。 | 拥有授予权限的 Kubernetes 用户 | 
| 检查 `PersistentVolumeClaim` 的状态。 | 输入以下命令以检查 `PersistentVolumeClaim` 的状态。<pre>kubectl -n poc-efs-eks-fargate get pvc</pre>有关示例输出，请参阅[其他信息](#run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-additional)部分。 | 拥有授予权限的 Kubernetes 用户 | 
| 验证工作负载 1 是否可写入文件系统。 | 输入以下命令以验证工作负载 1 是否正在向 `/data/out1.txt` 写入数据。<pre>kubectl exec -ti poc-app1 -n poc-efs-eks-fargate -- tail -f /data/out1.txt</pre>结果类似于以下内容：<pre>...<br />Thu Sep  3 15:25:07 UTC 2023 - PoC APP 1<br />Thu Sep  3 15:25:12 UTC 2023 - PoC APP 1<br />Thu Sep  3 15:25:17 UTC 2023 - PoC APP 1<br />...</pre> | 拥有授予权限的 Kubernetes 用户 | 
| 验证工作负载 2 是否可写入文件系统。 | 输入以下命令以验证工作负载 2 是否正在向 `/data/out2.txt` 写入数据。<pre>kubectl -n $APP_NAMESPACE exec -ti poc-app2 -- tail -f /data/out2.txt</pre>结果类似于以下内容：<pre>...<br />Thu Sep  3 15:26:48 UTC 2023 - PoC APP 2<br />Thu Sep  3 15:26:53 UTC 2023 - PoC APP 2<br />Thu Sep  3 15:26:58 UTC 2023 - PoC APP 2<br />...</pre> | 拥有授予权限的 Kubernetes 用户 | 
| 验证工作负载 1 是否可以读取由工作负载 2 写入的文件。 | 输入以下命令，以验证工作负载 1 是否能够读取由工作负载 2 写入的 `/data/out2.txt` 文件。<pre>kubectl exec -ti poc-app1 -n poc-efs-eks-fargate -- tail -n 3 /data/out2.txt</pre>结果类似于以下内容：<pre>...<br />Thu Sep  3 15:26:48 UTC 2023 - PoC APP 2<br />Thu Sep  3 15:26:53 UTC 2023 - PoC APP 2<br />Thu Sep  3 15:26:58 UTC 2023 - PoC APP 2<br />...</pre> | 拥有授予权限的 Kubernetes 用户 | 
| 验证工作负载 2 是否可以读取由工作负载 1 写入的文件。 | 输入以下命令，以验证工作负载 1 是否能够读取由工作负载 2 写入的 `/data/out1.txt` 文件。<pre>kubectl -n $APP_NAMESPACE exec -ti poc-app2 -- tail -n 3 /data/out1.txt</pre>结果类似于以下内容：<pre>...<br />Thu Sep  3 15:29:22 UTC 2023 - PoC APP 1<br />Thu Sep  3 15:29:27 UTC 2023 - PoC APP 1<br />Thu Sep  3 15:29:32 UTC 2023 - PoC APP 1<br />...</pre> | 拥有授予权限的 Kubernetes 用户 | 
| 验证移除应用程序组件后文件是否保留。 | 接下来，使用脚本移除应用程序组件（持久卷、持久卷声明和容器组（pod）），并验证文件 `/data/out1.txt` 和 `/data/out2.txt` 是否仍保留在文件系统中。使用以下命令运行 `validate-efs-content.sh` 脚本。<pre>./scripts/epic05/validate-efs-content.sh \<br />    -t "$EFS_CREATION_TOKEN"</pre>其中，`$EFS_CREATION_TOKEN` 是文件系统的唯一创建令牌。结果类似于以下内容：<pre>pod/poc-app-validation created<br />Waiting for pod get Running state...<br />Waiting for pod get Running state...<br />Waiting for pod get Running state...<br />Results from execution of 'find /data' on validation process pod:<br />/data<br />/data/out2.txt<br />/data/out1.txt</pre> | 拥有授予权限的 Kubernetes 用户、系统管理员 | 

### 监控操作
<a name="monitor-operations"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 监控应用程序日志。 | 作为第二天操作的一部分，请将应用程序日志发送到 Amazon CloudWatch 进行监控。 | AWS 系统管理员、拥有授予权限的 Kubernetes 用户 | 
| 使用 Container Insights 监控 Amazon EKS 和 Kubernetes 容器。 | 作为第二天操作的一部分，使用亚马逊容器洞察监控亚马逊 EKS 和 Kubernetes 系统。 CloudWatch 此工具从不同级别和维度的容器化应用程序收集、聚合以及汇总指标。有关更多信息，请参阅[相关资源](#run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-resources)部分。 | AWS 系统管理员、拥有授予权限的 Kubernetes 用户 | 
| 使用监控 Amazon EFS CloudWatch。 | 作为第二天操作的一部分，使用 Amazon 监控文件系统 CloudWatch，Amazon 会收集来自 Amazon EFS 的原始数据并将其处理为可读的近乎实时的指标。有关更多信息，请参阅[相关资源](#run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-resources)部分。 | AWS 系统管理员 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理所有已创建的模式资源。 | 完成本模式后，清理所有资源，以避免产生 AWS 费用。使用 PoC 应用程序后，请运行 `clean-up-resources.sh` 脚本，以删除所有资源。完成下列选项之一。**使用静态加密，有 KMS 密钥：**<pre>./scripts/epic06/clean-up-resources.sh \<br />    -c "$CLUSTER_NAME" \<br />    -t "$EFS_CREATION_TOKEN" \<br />    -k "$KMS_KEY_ALIAS"</pre>其中，`$CLUSTER_NAME` 是 Amazon EKS 集群的名称，`$EFS_CREATION_TOKEN` 是文件系统的创建令牌，`$KMS_KEY_ALIAS` 是 KMS 密钥的别名。**不使用静态加密：**<pre>./scripts/epic06/clean-up-resources.sh \<br />    -c "$CLUSTER_NAME" \<br />    -t "$EFS_CREATION_TOKEN"</pre>其中，`$CLUSTER_NAME` 是 Amazon EKS 集群的名称，`$EFS_CREATION_TOKEN` 是文件系统的创建令牌。 | 拥有授予权限的 Kubernetes 用户、系统管理员 | 

## 相关资源
<a name="run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-resources"></a>

**参考**
+ [适用于 Amazon EKS 的 AWS Fargate 现在支持 Amazon EFS](https://aws.amazon.com/blogs/aws/new-aws-fargate-for-amazon-eks-now-supports-amazon-efs/)（公告）
+ [如何在 AWS Fargate 上使用 Amazon EKS 捕获应用程序日志](https://aws.amazon.com/blogs/containers/how-to-capture-application-logs-when-using-amazon-eks-on-aws-fargate/)（博客文章）
+ [使用容器见解](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ContainerInsights.html)（Amazon CloudWatch 文档）
+ [在亚马逊 EKS 和 Kubernetes 上设置容器见解（亚马逊文档）](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/deploy-container-insights-EKS.html) CloudWatch 
+ [亚马逊 EKS 和 Kubernetes 容器洞察指标（亚马逊文档）](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Container-Insights-metrics-EKS.html) CloudWatch 
+ 使用@@ [亚马逊监控亚马逊 EFS CloudWatch（亚马](https://docs.aws.amazon.com/efs/latest/ug/monitoring-cloudwatch.html)逊 EFS 文档）

**GitHub 教程和示例**
+ [静态预置](https://github.com/kubernetes-sigs/aws-efs-csi-driver/blob/master/examples/kubernetes/static_provisioning/README.md)
+ [传输中加密](https://github.com/kubernetes-sigs/aws-efs-csi-driver/blob/master/examples/kubernetes/encryption_in_transit/README.md)
+ [通过多个容器组（pod）访问文件系统](https://github.com/kubernetes-sigs/aws-efs-csi-driver/blob/master/examples/kubernetes/multiple_pods/README.md)
+ [在 Amazon EFS 中使用 StatefulSets](https://github.com/kubernetes-sigs/aws-efs-csi-driver/blob/master/examples/kubernetes/statefulset/README.md)
+ [安装子路径](https://github.com/kubernetes-sigs/aws-efs-csi-driver/blob/master/examples/kubernetes/volume_path/README.md)
+ [使用 Amazon EFS 接入点](https://github.com/kubernetes-sigs/aws-efs-csi-driver/blob/master/examples/kubernetes/access_points/README.md)
+ [适用于 Terraform 的 Amazon EKS 蓝图](https://aws-ia.github.io/terraform-aws-eks-blueprints/)

**必要工具**
+ [正在安装 AWS CLI 版本 2](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)
+ [正在安装 eksctl](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html)
+ [正在安装 kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)
+ [正在安装 jq](https://stedolan.github.io/jq/download/)

## 附加信息
<a name="run-stateful-workloads-with-persistent-data-storage-by-using-amazon-efs-on-amazon-eks-with-aws-fargate-additional"></a>

以下是 `kubectl get pv` 命令的示例输出。

```
NAME         CAPACITY   ACCESS MODES   RECLAIM POLICY   STATUS   CLAIM                             STORAGECLASS   REASON   AGE
poc-app-pv   1Mi        RWX            Retain           Bound    poc-efs-eks-fargate/poc-app-pvc   efs-sc                  3m56s
```

以下是 `kubectl -n poc-efs-eks-fargate get pvc` 命令的示例输出。

```
NAME          STATUS   VOLUME       CAPACITY   ACCESS MODES   STORAGECLASS   AGE
poc-app-pvc   Bound    poc-app-pv   1Mi        RWX            efs-sc         4m34s
```

# 使用 Amazon EKS 容器组身份和 KEDA 在 Amazon EKS 中设置事件驱动的自动扩缩
<a name="event-driven-auto-scaling-with-eks-pod-identity-and-keda"></a>

*Dipen Desai、Abhay Diwan、Kamal Joshi 和 Mahendra Revanasiddappa，Amazon Web Services*

## Summary
<a name="event-driven-auto-scaling-with-eks-pod-identity-and-keda-summary"></a>

诸如 [Amazon Elastic Kubernetes Service（Amazon EKS）](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html)之类的编排平台简化了基于容器的应用程序的生命周期管理。这有助于组织专注于构建、保护、操作和维护基于容器的应用程序。随着事件驱动的部署变得越来越普遍，组织也越来越频繁地根据各种事件源扩展 Kubernetes 部署。将这种方法与自动扩缩相结合后，通过提供按需计算资源和针对应用程序逻辑量身定制的高效扩缩，即可实现成本的大幅节省。

[KEDA](https://keda.sh/) 是一款基于 Kubernetes 的事件驱动型自动扩缩器。KEDA 可帮助您根据需要处理的事件数量来扩缩 Kubernetes 中的任何容器。它是轻量级的，并且可以与任何 Kubernetes 集群集成。这款扩缩器还可与标准的 Kubernetes 组件，例如[水平容器组（pod）自动扩缩（HPA](https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/)），搭配使用。KEDA 还提供 [TriggerAuthentication](https://keda.sh/docs/2.14/concepts/authentication/#re-use-credentials-and-delegate-auth-with-triggerauthentication)，这是一项可帮助您委托身份验证的功能。它允许您描述与 ScaledObject 和部署容器分开的身份验证参数。

AWS 提供支持各种 Kubernetes 部署选项的 AWS Identity and Access Management (IAM) 角色，包括亚马逊 EKS、Amazon EKS Anywhere、 AWS 云端 Red Hat OpenShift 服务 (ROSA) 和亚马逊弹性计算云 (亚马逊) 上的自行管理的 Kubernetes 集群。 EC2这些角色使用 IAM 结构（例如 OpenID Connect (OIDC) 身份提供商和 IAM 信任策略）在不同的环境中运行，无需直接依赖 Amazon EKS 服务或。 APIs有关更多信息，请参阅 Amazon EKS 文档中的[服务账户的 IAM 角色](https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html)。

[Amazon EKS 容器组身份](https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html)可简化 Kubernetes 服务账户在不需要 OIDC 提供商的情况下代入 IAM 角色的流程。因此，能够管理应用程序凭证。您可以将 IAM 角色与 Kubernetes 服务账户关联，然后将您的 Pod 配置为使用服务账户，而不是创建 AWS 证书并将其分配给容器或使用 Amazon EC2 实例的角色。这可以帮助您跨多个集群使用 IAM 角色，并允许在 IAM 角色之间重复使用权限策略，从而简化策略管理。

通过使用 Amazon EKS 容器组身份实施 KEDA，企业可以实现高效的事件驱动型自动扩缩和简化的凭证管理。应用程序可根据需求进行扩缩，从而优化资源利用率以及降低成本。

此模式可以帮助您将 Amazon EKS 容器组身份与 KEDA 进行集成。它展示了如何使用 `keda-operator` 服务账户以及通过 `TriggerAuthentication` 委派身份验证。此模式还描述了如何建立 KEDA 运算符的 IAM 角色和应用程序的 IAM 角色之间的信任关系。这种信任关系允许 KEDA 监控事件队列中的消息并调整目标 Kubernetes 对象的扩缩。

## 先决条件和限制
<a name="event-driven-auto-scaling-with-eks-pod-identity-and-keda-prereqs"></a>

**先决条件**
+ AWS Command Line Interface [(AWS CLI) 版本 2.13.17 或更高版本，已安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ Python 3.11.5 或更高版本，[已安装](https://www.python.org/downloads/)
+ 适用于 Python (Boto3) 的 AWS SDK [版本 1.34.135 或更高版本，已安装](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)
+ Helm 版本 3.12.3 或更高版本，[已安装](https://helm.sh/docs/intro/install/)
+ kubectl 版本 1.25.1 或更高版本，[已安装](https://kubernetes.io/docs/tasks/tools/)。
+ Docker Engine 版本 26.1.1 或更高版本，[已安装](https://docs.docker.com/engine/install/)
+ Amazon EKS 集群版本 1.24 或更高版本，[已创建](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html)
+ 创建 Amazon EKS 容器组身份代理的先决条件，[已满足](https://docs.aws.amazon.com/eks/latest/userguide/pod-id-agent-setup.html#pod-id-agent-add-on-create)

**限制**
+ 您必须建立 `keda-operator` 角色和 `keda-identity` 角色之间的信任关系。此模式的[操作说明](#event-driven-auto-scaling-with-eks-pod-identity-and-keda-epics)部分中提供了说明。

## 架构
<a name="event-driven-auto-scaling-with-eks-pod-identity-and-keda-architecture"></a>

在此模式中，您可以创建以下 AWS 资源：
+ **Amazon Elastic Container Registry（Amazon ECR）存储库** – 在此模式中，此存储库名为 `keda-pod-identity-registry`。此私有存储库可用于存储示例应用程序的 Docker 映像。
+ **Amazon Simple Queue Service（Amazon SQS）队列** – 在此模式中，此队列名为 `event-messages-queue`。队列充当消息缓冲区，可用于收集和存储传入的消息。KEDA 监控队列指标，例如消息计数或队列长度，并根据这些指标自动扩缩应用程序。
+ **应用程序的 IAM 角色** – 在此模式中，此角色名为 `keda-identity`。`keda-operator` 角色会代入此角色。此角色允许访问 Amazon SQS 队列。
+ **KEDA 运算符的 IAM 角色** – 在此模式中，此角色名为 `keda-operator`。KEDA 操作员使用此角色进行所需的 AWS API 调用。此角色具有代入 `keda-identity` 角色的权限。由于 `keda-operator` 和 `keda-identity` 角色之间存有信任关系，`keda-operator` 角色具有 Amazon SQS 权限。

通过 `TriggerAuthentication` 和 `ScaledObject` Kubernetes 自定义资源，运算符会使用 `keda-identity` 角色与 Amazon SQS 队列连接。根据队列大小，KEDA 会自动扩缩应用程序部署。它会根据队列中未读消息的数量，每 5 条新增 1 条。在默认配置中，如果 Amazon SQS 队列中没有未读消息，则应用程序会缩减到 0 个容器组（pod）。KEDA 运算符按照您指定的时间间隔监控队列。

 

下图显示了您如何使用 Amazon EKS 容器组身份为 `keda-operator` 角色提供对 Amazon SQS 队列的安全访问权限。

![\[使用 KEDA 和 Amazon EKS 容器组身份，以自动扩缩基于 Kubernetes 的应用程序。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/56f7506d-e8d3-43e5-bec6-42267fedd0ae/images/05bdbd09-9eb8-4c0b-8c0d-efe38aecb683.png)


下图显示了如下工作流：

1. 您在 Amazon EKS 集群中安装 Amazon EKS 容器组身份代理。

1. 您在 Amazon EKS 集群的 KEDA 命名空间中部署 KEDA 运算符。

1. 您在目标中创建`keda-operator`和 `keda-identity` IAM 角色 AWS 账户。

1. 建立 IAM 角色之间的信任关系。

1. 您在 `security` 命名空间中部署应用程序。

1. KEDA 运算符将对 Amazon SQS 队列中的消息进行轮询。

1. KEDA 启动 HPA，而后者会根据队列大小自动扩缩应用程序。

## 工具
<a name="event-driven-auto-scaling-with-eks-pod-identity-and-keda-tools"></a>

**AWS 服务**
+ [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) 是一项安全、可扩展且可靠的托管容器映像注册表服务。
+ [亚马逊 Elastic Kubernetes Service（亚马逊](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。
+ [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) 提供了一个安全、持久且可用的托管队列，它可帮助您集成和分离分布式软件系统与组件。

**其他工具**
+ [KEDA](https://keda.sh/) 是一款基于 Kubernetes 的事件驱动型自动扩缩器。

**代码存储库**

此模式的代码可在使用 EK [S Pod Id GitHub entity 和 KEDA 存储库的事件驱动的自动缩放](https://github.com/aws-samples/event-driven-autoscaling-using-podidentity-and-keda/tree/main)中找到。

## 最佳实践
<a name="event-driven-auto-scaling-with-eks-pod-identity-and-keda-best-practices"></a>

我们建议您遵循以下最佳实践：
+ [Amazon SNS 最佳实践](https://docs.aws.amazon.com/eks/latest/best-practices/introduction.html)
+ [ IAM 安全最佳实操](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)
+ [亚马逊 SQS 最佳实践](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-best-practices.html)

## 操作说明
<a name="event-driven-auto-scaling-with-eks-pod-identity-and-keda-epics"></a>

### 创建 AWS 资源
<a name="create-aws-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 KEDA 运算符的 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | AWS 管理员 | 
| 为示例应用程序创建 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | AWS 管理员 | 
| 创建 Amazon SQS 队列。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | 常规 AWS | 
| 创建 Amazon ECR 存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | 常规 AWS | 

### 设置 Amazon EKS 集群
<a name="set-up-the-eks-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 Amazon EKS 容器组身份代理。 | 对于目标 Amazon EKS 集群，安装 Amazon EKS 容器组身份代理。按照 Amazon EKS 文档中[设置 Amazon EKS 容器组身份代理](https://docs.aws.amazon.com/eks/latest/userguide/pod-id-agent-setup.html#pod-id-agent-add-on-create)的说明进行操作。 | AWS DevOps | 
| 部署 KEDA。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | DevOps 工程师 | 
| 为 Kubernetes 服务账户分配 IAM 角色。 | 按照 Amazon EKS 文档中[向 Kubernetes 服务账户分配 IAM 角色](https://docs.aws.amazon.com/eks/latest/userguide/pod-id-association.html)中的说明进行操作。使用以下值：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | AWS DevOps | 
| 创建 命名空间。 | 输入以下命令，以在目标 Amazon EKS 集群中创建 `security` 命名空间：<pre>kubectl create ns security</pre> | DevOps 工程师 | 

### 部署示例应用程序。
<a name="deploy-the-sample-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆应用程序文件。 | 输入以下命令，[使用 EKS Pod Identity 和 KEDA 存储库从中克隆事件驱动的自动缩放](https://github.com/aws-samples/event-driven-autoscaling-using-podidentity-and-keda/tree/main)： GitHub<pre>git clone https://github.com/aws-samples/event-driven-autoscaling-using-podidentity-and-keda.git</pre> | DevOps 工程师 | 
| 构建 Docker 映像。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | DevOps 工程师 | 
| 将 Docker 映像推送到 Amazon ECR。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html)您可以导航到 Amazon ECR 存储库页面，然后选择**查看推送命令**，进而找到推送命令。 | DevOps 工程师 | 
| 部署示例应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | DevOps 工程师 | 
| 为应用程序服务账户分配 IAM 角色。 | 执行以下任一操作，将 `keda-identity` IAM 角色与示例应用程序的服务账户进行关联：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | DevOps 工程师 | 
| 部署 `ScaledObject` 和 `TriggerAuthentication`。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | DevOps 工程师 | 

### 测试自动扩缩
<a name="test-auto-scaling"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 向 Amazon SQS 队列发送消息。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | DevOps 工程师 | 
| 监控应用程序容器组（pod）。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | DevOps 工程师 | 

## 问题排查
<a name="event-driven-auto-scaling-with-eks-pod-identity-and-keda-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| KEDA 运算符无法扩缩应用程序。 | 输入以下命令，以检查 `keda-operator` IAM 角色的日志：<pre>kubectl logs -n keda -l app=keda-operator -c keda-operator</pre> 如果有 `HTTP 403` 响应码，则应用程序和 KEDA 扩缩器没有足够的权限来访问 Amazon SQS 队列。完成以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html)如果出现 `Assume-Role` 错误，则 [Amazon EKS 节点 IAM 角色](https://docs.aws.amazon.com/eks/latest/userguide/create-node-role.html)将无法代入为 `TriggerAuthentication` 定义的 IAM 角色。完成以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/event-driven-auto-scaling-with-eks-pod-identity-and-keda.html) | 

## 相关资源
<a name="event-driven-auto-scaling-with-eks-pod-identity-and-keda-resources"></a>
+ [设置 Amazon EKS 容器组身份代理](https://docs.aws.amazon.com/eks/latest/userguide/pod-id-agent-setup.html)（Amazon EKS 文档）
+ [部署 KEDA](https://keda.sh/docs/2.14/deploy/)（KEDA 文档）
+ [ScaledObject 规格](https://keda.sh/docs/2.16/reference/scaledobject-spec/)（KEDA 文档）
+ [使用进行身份验证 TriggerAuthentication](https://keda.sh/docs/2.14/concepts/authentication/)（KEDA 文档）

# 使用 PGO 简化 Amazon EKS 上的 PostgreSQL 部署
<a name="streamline-postgresql-deployments-amazon-eks-pgo"></a>

*Shalaka Dengale，Amazon Web Services*

## Summary
<a name="streamline-postgresql-deployments-amazon-eks-pgo-summary"></a>

此模式会将来自 Crunchy Data 的 Postgres Operator（PGO）与 Amazon Elastic Kubernetes Service（Amazon EKS）集成在一起，以便简化云原生环境中的 PostgreSQL 部署。PGO 能够以自动化、可扩展的方式来管理 Kubernetes 中的 PostgreSQL 数据库。将 PGO 与 Amazon EKS 结合使用时，它将成为一个强大的平台，用于高效地部署、管理和扩展 PostgreSQL 数据库。

这一集成提供了下面这些主要优势：
+ 自动部署：简化 PostgreSQL 集群的部署和管理。
+ 自定义资源定义 (CRDs)：****使用 Kubernetes 原语进行 PostgreSQL 管理。
+ 高可用性：支持自动失效转移和同步复制。
+ 自动备份和恢复：****简化备份和还原过程。
+ 水平扩展：****为 PostgreSQL 集群启用动态扩展。
+ 版本升级：帮助进行滚动升级，并最大限度地减少停机时间。
+ 安全性：实施加密、访问控制和身份验证机制。

## 先决条件和限制
<a name="streamline-postgresql-deployments-amazon-eks-pgo-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ [AWS 命令行界面（AWS CLI）版本 2](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)，已在 Linux、macOS 或 Windows 上安装并配置。
+ [AWS CLI CLI Config](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-quickstart.html)， AWS 用于从命令行连接资源。
+ [eksctl](https://github.com/eksctl-io/eksctl#installation)，已在 Linux、macOS 或 Windows 上安装并配置。
+ `kubectl`，已安装并配置为访问 Amazon EKS 集群上的资源。有关详情，请参阅 Amazon EKS 文档中的[设置 kubectl 和 eksctl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)。 
+ 您的计算机终端被配置为访问 Amazon EKS 集群。有关详情，请参阅 Amazon EKS 文档中的[将计算机配置为与您的集群通信](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-console.html#eks-configure-kubectl)。

**产品版本**
+ Kubernetes 版本 1.21 到 1.24 或更高版本（请参阅 [PGO 文档](https://access.crunchydata.com/documentation/postgres-operator/5.2.5/)）。
+ PostgreSQL 版本 10 或更高版本。此模式使用 PostgreSQL 版本 16。

**限制**
+ 有些 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="streamline-postgresql-deployments-amazon-eks-pgo-architecture"></a>

**目标技术堆栈**
+ Amazon EKS
+ Amazon Virtual Private Cloud (Amazon VPC)
+ Amazon Elastic Compute Cloud（Amazon EC2）

**目标架构**

![\[使用具有三个可用区和两个副本的 PGO 的架构 PgBouncer，以及 PGO 操作员。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/4c164012-7527-4ebe-b6a7-c129600328d6/images/26a5572b-405b-4634-b96a-91254c3ea2c1.png)


此模式将构建一个架构，其中包含一个具有三个节点的 Amazon EKS 集群。每个节点都在后端的一组 EC2 实例上运行。此 PostgreSQL 设置遵循主副本架构，这对于需要执行大量读取操作的使用案例特别有效。此架构包括以下组件：
+ **主数据库容器（pg-primary）**托管着主 PostgreSQL 实例，所有写入操作都将定向到此实例。
+ **辅助副本容器（pg-replica）**托管着 PostgreSQL 实例，这些实例将从主数据库复制数据并处理读取操作。
+ **PgBouncer**是 PGO 中包含的 PostgreSQL 数据库的轻量级连接池器。它位于客户端与 PostgreSQL 服务器之间，并充当各个数据库连接的媒介。
+ 在此 Kubernetes 环境中，**PGO** 可以自动部署和管理 PostgreSQL 集群。
+ **Patroni** 是一款开源工具，负责管理和自动执行 PostgreSQL 的高可用性配置。它包含在 PGO 中。当在 Kubernetes 中将 Patroni 与 PGO 结合使用时，它将发挥至关重要的作用，确保 PostgreSQL 集群的弹性和容错能力。有关详情，请参阅 [Patroni 文档](https://patroni.readthedocs.io/en/latest/)。

此工作流包含以下步骤：
+ **部署 PGO Operator**。您需要将 PGO Operator 部署到 Amazon EKS 上运行的 Kubernetes 集群上。可以使用 Kubernetes 清单或 Helm 图表来完成此操作。此模式使用 Kubernetes 清单。
+ **定义 PostgreSQL 实例**。当操作符运行时，您可以创建自定义资源 (CRs) 来指定 PostgreSQL 实例的所需状态。这包括存储、复制和高可用性设置等配置。
+ **Operator 管理**。您可以通过 Kubernetes API 对象与操作员进行交互，例如 CRs 创建、更新或删除 PostgreSQL 实例。
+ **监控和维护**。您可以监控 Amazon EKS 上运行的 PostgreSQL 实例的运行状况和性能。Operator 通常会提供用于进行监控的指标和日志记录功能。您可以根据需要执行例行维护任务，例如升级和修补。有关详情，请参阅 Amazon EKS 文档中的[监控集群性能和查看日志](https://docs.aws.amazon.com/eks/latest/userguide/eks-observe.html)。
+ **扩展和备份**：您可以使用 Operator 提供的功能来扩展 PostgreSQL 实例以及管理备份。

此模式不包含监控、维护和备份操作。

**自动化和扩展**
+ 您可以使用自动 CloudFormation 创建基础架构。有关详情，请参阅 Amazon EKS 文档中的[使用 CloudFormation创建 Amazon EKS 资源](https://docs.aws.amazon.com/eks/latest/userguide/creating-resources-with-cloudformation.html)。
+ 您可以使用 GitVersion 或 Jenkins 内部版本号来自动部署数据库实例。

## 工具
<a name="streamline-postgresql-deployments-amazon-eks-pgo-tools"></a>

**AWS 服务**
+ [亚马逊 Elastic Kubernetes Service（亚马逊](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。 
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您 AWS 服务 通过命令行外壳中的命令进行交互。

**其他工具**
+ [eksctl](https://eksctl.io/) 是一款简单的命令行工具，用于在 Amazon EKS 上创建集群。
+ [kubectl](https://kubernetes.io/docs/tasks/tools/install-kubectl/) 是一个命令行实用程序，用于对 Kubernetes 集群运行命令。
+ [PGO](https://github.com/CrunchyData/postgres-operator) 会自动管理和扩展 Kubernetes 中的 PostgreSQL 数据库。

## 最佳实践
<a name="streamline-postgresql-deployments-amazon-eks-pgo-best-practices"></a>

请遵循以下最佳实践，以便确保顺利、高效地进行部署：
+ **保护您的 EKS 集群**。为您的 EKS 集群实施安全最佳实践，例如为服务账户 AWS Identity and Access Management (IRSA)、网络策略和 VPC 安全组使用 (IRSA) 角色。限制对 EKS 集群 API 服务器的访问，并使用 TLS 对节点与 API 服务器之间的通信进行加密。
+ 确保 Amazon EKS 上运行的 PGO 版本与 Kubernetes **版本兼容**。有些 PGO 功能可能需要特定的 Kubernetes 版本，或者引入了兼容性限制。有关详情，请参阅 PGO 文档中的[组件和兼容性](https://access.crunchydata.com/documentation/postgres-operator/5.2.5/references/components/)。
+ 为 PGO 部署**规划资源分配**，包括 CPU、内存和存储。考虑 PGO 以及它管理的 PostgreSQL 实例的资源需求。监控资源使用情况，并根据需要来扩展资源。
+ **专为高可用性而设计**。设计您的 PGO 部署以便实现高可用性，从而最大限度地减少停机时间并确保可靠性。跨多个可用区部署 PGO 的多个副本，以便获得容错能力。
+ 为 PGO 管理的 PostgreSQL 数据库**实施备份和还原程序**。使用 PGO 提供的功能，或者使用与 Kubernetes 和 Amazon EKS 兼容的第三方备份解决方案。
+ 为 PGO 部署**设置监控和日志记录**，以便跟踪性能、运行状况和事件。使用 Prometheus 等工具来监控指标，并使用 Grafana 进行可视化。配置日志记录以便捕获 PGO 日志，从而进行问题排查和审核。
+ 正确**配置网络**，以便能够在 PGO、PostgreSQL 实例以及 Kubernetes 集群中的其他服务之间进行通信。使用 Amazon VPC 联网功能和 Kubernetes 联网插件（例如 Calico 或 [Amazon VPC CNI](https://github.com/aws/amazon-vpc-cni-k8s)）来实施网络策略和隔离流量。
+ 考虑性能、持久性和可扩展性等因素，为 PostgreSQL 数据库**选择合适的存储选项**。使用亚马逊 Elastic Block Store (Amazon EBS) 卷 AWS 或托管存储服务进行永久存储。有关详情，请参阅 Amazon EKS 文档中的[使用 Amazon EBS 存储 Kubernetes 卷](https://docs.aws.amazon.com/eks/latest/userguide/ebs-csi.html)。
+ **使用基础设施即代码 (IaC) 工具**，例如 CloudFormation 在 Amazon EKS 上自动部署和配置 PGO。将基础设施组件（包括 EKS 集群、网络和 PGO 资源）定义为代码，以便实现一致性、可重复性和版本控制。

## 操作说明
<a name="streamline-postgresql-deployments-amazon-eks-pgo-epics"></a>

### 创建一个 IAM 角色
<a name="create-an-iam-role"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-postgresql-deployments-amazon-eks-pgo.html) | AWS 管理员 | 

### 创建一个 Amazon EKS 集群。
<a name="create-an-eks-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个 Amazon EKS 集群。 | 如果您已部署一个集群，请跳过此步骤。否则，请使用 `eksctl` Terraform 或在当前 AWS 账户 集群中部署 Amazon EKS 集群。 CloudFormation此模式使用 `eksctl` 来部署集群。此模式将 Amazon EC2 用作 Amazon EKS 的一个节点组。如果要使用 AWS Fargate，请参阅 [eksctl](https://eksctl.io/usage/schema/#managedNodeGroups) 文档中的`managedNodeGroups`配置。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-postgresql-deployments-amazon-eks-pgo.html) | AWS 管理员、Terraform 或 eksctl 管理员、Kubernetes 管理员 | 
| 验证此集群的状态。 | 运行如下命令，查看此集群中的节点的当前状态：<pre>kubectl get nodes</pre>如果遇到错误，请参阅 Amazon EKS 文档中的[问题排查部分](https://docs.aws.amazon.com/eks/latest/userguide/troubleshooting.html)。 | AWS 管理员、Terraform 或 eksctl 管理员、Kubernetes 管理员 | 

### 创建 OIDC 身份提供程序
<a name="create-an-oidc-identity-provider"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启用 IAM OIDC 提供程序。 | Amazon EBS Container Storage Interface（CSI）驱动程序的一个先决条件是，您的集群必须具有一个现有的 IAM OpenID Connect（OIDC）提供程序。使用如下命令，启用 IAM OIDC 提供程序：<pre>eksctl utils associate-iam-oidc-provider --region={region} --cluster={YourClusterNameHere} --approve</pre>有关此步骤的详情，请参阅 [Amazon EKS 文档](https://docs.aws.amazon.com/eks/latest/userguide/ebs-csi.html)。 | AWS 管理员 | 
| 为 Amazon EBS CSI 驱动程序创建一个 IAM 角色。 | 使用如下 `eksctl` 命令，为 CSI 驱动程序创建 IAM 角色：<pre>eksctl create iamserviceaccount \<br />  --region {RegionName} \<br />  --name ebs-csi-controller-sa \<br />  --namespace kube-system \<br />  --cluster {YourClusterNameHere} \<br />  --attach-policy-arn arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy \<br />  --approve \<br />  --role-only \<br />  --role-name AmazonEKS_EBS_CSI_DriverRole</pre>如果使用加密的 Amazon EBS 驱动器，您必须进一步配置此策略。有关说明，请参阅 [Amazon EBS SCI 驱动程序文档](https://github.com/kubernetes-sigs/aws-ebs-csi-driver/blob/master/docs/install.md#installation-1)。 | AWS 管理员 | 
| 添加 Amazon EBS CSI 驱动程序。 | 使用如下 `eksctl` 命令，添加 Amazon EBS CSI 驱动程序：<pre>eksctl create addon \<br />  --name aws-ebs-csi-driver \<br />  --cluster <YourClusterName> service-account-role-arn arn:aws:iam::$(aws sts get-caller-identity \<br />  --query Account \<br />  --output text):role/AmazonEKS_EBS_CSI_DriverRole \<br />  --force</pre> | AWS 管理员 | 

### 安装 PGO
<a name="install-pgo"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆 PGO 存储库。 | 克隆 PGO 的 GitHub 存储库：<pre>git clone https://github.com/CrunchyData/postgres-operator-examples.git </pre> | AWS DevOps | 
| 提供用于创建服务账户的角色详细信息。 | 要授予 Amazon EKS 集群访问所需 AWS 资源的权限，请在`service_account.yaml`文件中指定您之前创建的 OIDC 角色的亚马逊资源名称 (ARN)。[GitHub](https://github.com/CrunchyData/postgres-operator/blob/main/config/rbac/cluster/service_account.yaml)<pre>cd postgres-operator-examples</pre><pre>---<br />metadata:<br />  annotations:<br />    eks.amazonaws.com/role-arn: arn:aws:iam::<accountId>:role/<role_name> # Update the OIDC role ARN created earlier</pre> | AWS 管理员、Kubernetes 管理员 | 
| 创建此命名空间和 PGO 先决条件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-postgresql-deployments-amazon-eks-pgo.html) | Kubernetes 管理员 | 
| 确认已创建容器组（pod）。 | 确认已创建此命名空间和默认配置：<pre>kubectl get pods -n postgres-operator</pre> | AWS 管理员、Kubernetes 管理员 | 
| 验证 PVCs。 | 使用以下命令验证永久卷声明 (PVCs)：<pre>kubectl describe pvc -n postgres-operator</pre> | AWS 管理员、Kubernetes 管理员 | 

### 创建并部署 Operator
<a name="create-and-deploy-an-operator"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个 Operator。 | 修改位于 `/kustomize/postgres/postgres.yaml` 的文件的内容，以便与以下内容相匹配：<pre>spec:<br />  instances:<br />    - name: pg-1<br />      replicas: 3<br />  patroni:<br />    dynamicConfiguration:<br />      postgresql:<br />      pg_hba:<br />        - "host all all 0.0.0.0/0 trust" # this line enabled logical replication with programmatic access<br />        - "host all postgres 127.0.0.1/32 md5"<br />      synchronous_mode: true<br />  users:<br />  - name: replicator<br />    databases:<br />      - testdb<br />    options: "REPLICATION"</pre>这些更新将执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-postgresql-deployments-amazon-eks-pgo.html) | AWS 管理员、数据库管理员、Kubernetes 管理员 | 
| 部署此 Operator。 | 部署此 PGO Operator，以便能够简化 Kubernetes 环境中的 PostgreSQL 数据库的管理和操作：<pre>kubectl apply -k kustomize/postgres</pre> | AWS 管理员、数据库管理员、Kubernetes 管理员 | 
| 验证部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-postgresql-deployments-amazon-eks-pgo.html)从命令输出中，记下主副本（`primary_pod_name`）和只读副本（`read_pod_name`）。您将在后续步骤中使用这些副本。 | AWS 管理员、数据库管理员、Kubernetes 管理员 | 

### 验证流式复制
<a name="verify-streaming-replication"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 向主副本写入数据。 | 使用以下命令，连接到 PostgreSQL 主副本，并向数据库写入数据：<pre>kubectl exec -it <primary_pod_name> bash -n postgres-operator</pre><pre>psql</pre><pre>CREATE TABLE customers (firstname text, customer_id serial, date_created timestamp);<br />\dt</pre> | AWS 管理员、Kubernetes 管理员 | 
| 确认只读副本具有相同的数据。 | 连接到 PostgreSQL 只读副本，并检查流式复制功能是否正常运行：<pre>kubectl exec -it {read_pod_name} bash -n postgres-operator</pre><pre>psql</pre><pre>\dt</pre>只读副本应当具有您在上一步中在主副本中创建的表。 | AWS 管理员、Kubernetes 管理员 | 

## 问题排查
<a name="streamline-postgresql-deployments-amazon-eks-pgo-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 容器组（pod）无法启动。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-postgresql-deployments-amazon-eks-pgo.html) | 
| 副本明显落后于主数据库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-postgresql-deployments-amazon-eks-pgo.html) | 
| 您无法了解 PostgreSQL 集群的性能和运行状况。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-postgresql-deployments-amazon-eks-pgo.html) | 
| 复制功能无法正常工作。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-postgresql-deployments-amazon-eks-pgo.html) | 

## 相关资源
<a name="streamline-postgresql-deployments-amazon-eks-pgo-resources"></a>
+ [Amazon Elastic Kubernetes Service](https://docs.aws.amazon.com/whitepapers/latest/overview-deployment-options/amazon-elastic-kubernetes-service.html)（*AWS 上的部署选项概述*白皮书）
+  [CloudFormation](https://docs.aws.amazon.com/whitepapers/latest/overview-deployment-options/aws-cloudformation.html)（*AWS 上的部署选项概述*白皮书）
+ [开始使用 Amazon EKS – eksctl](https://docs.aws.amazon.com/eks/latest/userguide/getting-started-eksctl.html)（《*Amazon EKS 用户指南*》）
+ [设置 kubectl 和 eksctl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)（《*Amazon EKS 用户指南*》）
+ [创建用于 OpenID Connect 联合身份验证的角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_oidc.html)（《*IAM 用户指南*》）
+ [配置 AWS CLI（*AWS CLI 用户指南*）的设置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ [Crunchy Postgres for Kubernetes 文档](https://access.crunchydata.com/documentation/postgres-operator/latest)
+ [Crunch & Learn：Crunchy Postgres for Kubernetes 5.0](https://www.youtube-nocookie.com/embed/IIf9WZO3K50)（视频）

# 使用应用程序负载均衡器简化 Amazon ECS 中双向 TLS 的应用程序身份验证
<a name="simplify-application-authentication-with-mutual-tls-in-amazon-ecs"></a>

*Olawale Olaleye 和 Shamanth Devagari，Amazon Web Services*

## Summary
<a name="simplify-application-authentication-with-mutual-tls-in-amazon-ecs-summary"></a>

此模式可帮助您使用[应用程序负载均衡器（ALB）](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/mutual-authentication.html)，通过 Amazon Elastic Container Service（Amazon ECS）中的双向 TLS 简化应用程序身份验证并减轻安全负担。使用 ALB，您可以对来自的 X.509 客户端证书进行身份验证。 AWS 私有证书颁发机构这种强大的组合有助于实现服务之间的安全通信，从而减少对应用程序中的复杂身份验证机制的需求。此外，该模式使用 Amazon Elastic Container Registry（Amazon ECR）存储容器映像。

此模式中的示例一开始使用公开映像浏览馆中的 Docker 映像创建示例工作负载；随后，将构建新的 Docker 镜像镜像并将其存储到 Amazon ECR 中。要获取来源，可以考虑基于 Git 的系统，例如 GitHub、或 Bitbucket GitLab，或者使用亚马逊简单存储服务 Amazon S3 (Amazon S3)。要构建 Docker 镜像，请考虑使用 AWS CodeBuild 作为后续镜像。

## 先决条件和限制
<a name="simplify-application-authentication-with-mutual-tls-in-amazon-ecs-prereqs"></a>

**先决条件**
+  AWS 账户 具有部署 AWS CloudFormation 堆栈访问权限的活跃用户。确保您拥有 AWS Identity and Access Management (IAM) [用户或角色的部署权限](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/control-access-with-iam.html) CloudFormation。
+ AWS Command Line Interface (AWS CLI) [已安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。使用或通过在`~/.aws/credentials`文件中设置环境变量，在本地计算机 AWS CLI 或环境中@@ [配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)您的 AWS 凭证。
+ [已安装](https://www.openssl.org/) OpenSSL。
+ [已安装](https://www.docker.com/get-started/) Docker。
+ 熟悉[工具](#simplify-application-authentication-with-mutual-tls-in-amazon-ecs-tools)中 AWS 服务 描述的内容。
+ 具备 Docker 和 NGINX 的相关知识。

**限制**
+ 应用程序负载均衡器的双向 TLS 仅支持 X.509v3 客户端证书，不支持 X.509v1 客户端证书。
+ 此模式的代码存储库中提供的 CloudFormation 模板不包括将 CodeBuild 项目配置为堆栈的一部分。
+ 有些 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)，然后选择相应服务的链接。

**产品版本**
+ Docker 版本 27.3.1 或更高版本
+ AWS CLI 版本 2.14.5 或更高版本

## 架构
<a name="simplify-application-authentication-with-mutual-tls-in-amazon-ecs-architecture"></a>

下图显示了此模式的架构组件。

![\[使用应用程序负载均衡器通过双向 TLS 进行身份验证的工作流\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a343fa4e-097f-416b-9c83-01a28eb57dc3/images/e1371297-b987-4487-9b13-8120933c921f.png)


 下图显示了如下工作流：

1. 创建 Git 存储库，并将应用程序代码提交至该存储库。

1. 在中创建私有证书颁发机构 (CA) AWS 私有 CA。

1. 创建 CodeBuild 项目。由提交更改触发，创建 Docker 映像并将构建的映像发布到 Amazon ECR。 CodeBuildproject 

1. 从 CA 复制证书链和证书正文，并将证书捆绑包上传至 Amazon S3。

1. 使用您上传到 Amazon S3 的 CA 捆绑包创建信任存储。将信任存储与应用程序负载均衡器（ALB）上的双向 TLS 侦听器关联。

1. 使用私有 CA 为容器工作负载颁发客户端证书。还可以使用创建私有 TLS 证书 AWS 私有 CA。

1. 将私有 TLS 证书导入 AWS Certificate Manager (ACM)，然后将其与 ALB 一起使用。

1. `ServiceTwo` 中的容器工作负载与 `ServiceOne` 中的容器工作负载通信时，会使用已颁发的客户端证书对 ALB 进行身份验证。

1. `ServiceOne` 中的容器工作负载与 `ServiceTwo` 中的容器工作负载通信时，会使用已颁发的客户端证书对 ALB 进行身份验证。

**自动化和扩展**

这种模式可以通过使用 SDK 中的 CloudFormation AWS Cloud Development Kit (AWS CDK) 、或 API 操作来配置 AWS 资源来实现完全自动化。

您可以使用 AWS CodePipeline 来实现持续集成和持续部署 (CI/CD) 管道，用于自动执行容器映像构建过程并将新版本部署到 Amazon ECS 集群服务。 CodeBuild 

## 工具
<a name="simplify-application-authentication-with-mutual-tls-in-amazon-ecs-tools"></a>

**AWS 服务 **
+ [AWS Certificate Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) 可帮助您创建、存储和续订 X.509 公有和私有 SSL/TLS X.509 证书和密钥，以保护您的 AWS 网站和应用程序。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在和的整个 AWS 账户 生命周期中对其进行管理 AWS 区域。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管式构建服务，可编译源代码、运行单元测试和生成部署就绪的构件。
+ [Amazon Elastic Container Registry（Amazon ECR）](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)是一项安全、可扩展且可靠的托管容器映像注册表服务。
+ [Amazon Elastic Container Service（Amazon ECS）](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html)是一项高度可扩展的快速容器管理服务，可助您轻松运行、停止和管理集群上的容器。您可以在由 AWS Fargate管理的无服务器基础架构上运行任务和服务。或者，为了更好地控制您的基础设施，您可以在您管理的亚马逊弹性计算云 (Amazon EC2) 实例集群上运行任务和服务。
+ [Amazon ECS Exec](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-exec.html) 允许您直接与容器交互，而无需首先与主机容器操作系统交互、打开入站端口或管理 SSH 密钥。您可以使用 ECS Exec 在 Amazon EC2 实例上或上运行的容器中运行命令或获取外壳程序。 AWS Fargate
+ [弹性负载均衡(ELB)](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) 将传入的应用程序或网络流量分配到多个目标。例如，您可以在一个或多个可用区内的 Amazon EC2 实例、容器和 IP 地址之间分配流量。ELB 会监控已注册目标的运行状况，并仅将流量传输到运行状况良好的目标。ELB 根据传入流量随时间的变化对负载均衡器进行扩展。它可以自动扩缩来处理大部分工作负载。
+ [AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/userguide/what-is-fargate.html)无需管理服务器或 Amazon EC2 实例，即可帮助您运行容器。Fargate 与 Amazon ECS 和 Amazon Elastic Kubernetes Service（Amazon EKS）兼容。您可以使用 Fargate 启动类型或 Fargate 容量提供程序来运行 Amazon ECS 任务和服务。为此，将应用程序打包到容器中、指定 CPU 和内存要求、定义联网和 IAM 策略并启动应用程序。每个 Fargate 任务都具有自己的隔离边界，不与其他任务共享底层内核、CPU 资源、内存资源或弹性网络接口。
+ [AWS 私有证书颁发机构](https://docs.aws.amazon.com/privateca/latest/userguide/PcaWelcome.html)允许创建私有证书颁发机构 (CA) 层次结构，包括根和下级结构 CAs，而无需运营本地 CA 的投资和维护成本。

**其他工具******
+ [Docker](https://www.docker.com/) 是一组平台即服务（PaaS）产品，它们利用操作系统级的虚拟化技术在容器中提供软件。
+ [GitHub[GitLab](https://docs.gitlab.com/ee/user/get_started/get_started_projects.html)](https://docs.github.com/en/repositories/creating-and-managing-repositories/quickstart-for-repositories)、和 [Bitbucket](https://support.atlassian.com/bitbucket-cloud/docs/tutorial-learn-bitbucket-with-git/) 是一些常用的基于 Git 的源代码控制系统，用于跟踪源代码更改。
+ [NGINX Open Source](https://nginx.org/en/docs/?_ga=2.187509224.1322712425.1699399865-405102969.1699399865) 是一款开源的负载均衡器、内容缓存服务器及 Web 服务器。本方案将其用作 Web 服务器。此模式将其用作 Web 服务器。
+ [OpenSSL](https://www.openssl.org/) 是一个开源库，提供各类服务供 TLS 和 CMS 的 OpenSSL 实现使用。

**代码存储库**

此模式的代码可在 Amazon-ECS 存储库中的 GitHub [mtls with-Application-Load-Balancer-Amazon-](https://github.com/aws-samples/mTLS-with-Application-Load-Balancer-in-Amazon-ECS) ECS 存储库中找到。

## 最佳实践
<a name="simplify-application-authentication-with-mutual-tls-in-amazon-ecs-best-practices"></a>
+ 使用 Amazon ECS Exec 在 Fargate 上运行的容器中运行命令或获取 Shell。您还可以使用 ECS Exec 来帮助收集用于调试的诊断信息。
+ 使用安全组和网络访问控制列表 (ACLs) 来控制服务之间的入站和出站流量。Fargate 任务会从您的虚拟私有云（VPC）中配置的子网接收一个 IP 地址。

## 操作说明
<a name="simplify-application-authentication-with-mutual-tls-in-amazon-ecs-epics"></a>

### 创建存储库
<a name="create-the-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 下载源代码。 | 要下载此模式的源代码，请复刻或克隆 GitHub [MTLS with-Amazon-](https://github.com/aws-samples/mTLS-with-Application-Load-Balancer-in-Amazon-ECS) ECS 存储库中的应用程序负载平衡器。 | DevOps 工程师 | 
| 创建 Git 存储库。 | 要创建包含 Dockerfile 和 `buildspec.yaml` 文件的 Git 存储库，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-application-authentication-with-mutual-tls-in-amazon-ecs.html)`git clone https://github.com/aws-samples/mTLS-with-Application-Load-Balancer-in-Amazon-ECS.git` | DevOps 工程师 | 

### 创建 CA 并生成证书
<a name="create-ca-and-generate-certificates"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在中创建私有 CA AWS 私有 CA。 | 要创建私有证书颁发机构（CA），请在终端中运行以下命令。将示例变量中的值替换为您自己的值。<pre>export AWS_DEFAULT_REGION="us-west-2"<br />export SERVICES_DOMAIN="www.example.com"<br /><br />export ROOT_CA_ARN=`aws acm-pca create-certificate-authority \<br />    --certificate-authority-type ROOT \<br />    --certificate-authority-configuration \<br />    "KeyAlgorithm=RSA_2048,<br />    SigningAlgorithm=SHA256WITHRSA,<br />    Subject={<br />        Country=US,<br />        State=WA,<br />        Locality=Seattle,<br />        Organization=Build on AWS,<br />        OrganizationalUnit=mTLS Amazon ECS and ALB Example,<br />        CommonName=${SERVICES_DOMAIN}}" \<br />        --query CertificateAuthorityArn --output text`</pre>有关更多详细信息，请参阅 AWS 文档[AWS 私有 CA中的创建私有 CA](https://docs.aws.amazon.com/privateca/latest/userguide/create-CA.html)。 | DevOps 工程师，AWS DevOps | 
| 创建并安装私有 CA 证书。 | 要为私有根 CA 创建并安装证书，请在终端中运行以下命令：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-application-authentication-with-mutual-tls-in-amazon-ecs.html) | AWS DevOps， DevOps 工程师 | 
| 申请托管证书。 | 要申请私有证书 AWS Certificate Manager 以用于您的私有 ALB，请使用以下命令：<pre>export TLS_CERTIFICATE_ARN=`aws acm request-certificate \<br />    --domain-name "*.${DOMAIN_DOMAIN}" \<br />    --certificate-authority-arn ${ROOT_CA_ARN} \<br />    --query CertificateArn --output text`</pre> | DevOps 工程师，AWS DevOps | 
| 使用私有 CA 颁发客户端证书。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-application-authentication-with-mutual-tls-in-amazon-ecs.html)`openssl req -out client_csr1.pem -new -newkey rsa:2048 -nodes -keyout client_private-key1.pem``openssl req -out client_csr2.pem -new -newkey rsa:2048 -nodes -keyout client_private-key2.pem`此命令会返回这两项服务的 CSR 和私钥。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-application-authentication-with-mutual-tls-in-amazon-ecs.html)<pre>SERVICE_ONE_CERT_ARN=`aws acm-pca issue-certificate \<br />    --certificate-authority-arn ${ROOT_CA_ARN} \<br />    --csr fileb://client_csr1.pem \<br />    --signing-algorithm "SHA256WITHRSA" \<br />    --validity Value=5,Type="YEARS" --query CertificateArn --output text` <br /><br />echo "SERVICE_ONE_CERT_ARN: ${SERVICE_ONE_CERT_ARN}"<br /><br />aws acm-pca get-certificate \<br />    --certificate-authority-arn ${ROOT_CA_ARN} \<br />    --certificate-arn ${SERVICE_ONE_CERT_ARN} \<br />     | jq -r '.Certificate' > client_cert1.cert<br /><br />SERVICE_TWO_CERT_ARN=`aws acm-pca issue-certificate \<br />    --certificate-authority-arn ${ROOT_CA_ARN} \<br />    --csr fileb://client_csr2.pem \<br />    --signing-algorithm "SHA256WITHRSA" \<br />    --validity Value=5,Type="YEARS" --query CertificateArn --output text` <br /><br />echo "SERVICE_TWO_CERT_ARN: ${SERVICE_TWO_CERT_ARN}"<br /><br />aws acm-pca get-certificate \<br />    --certificate-authority-arn ${ROOT_CA_ARN} \<br />    --certificate-arn ${SERVICE_TWO_CERT_ARN} \<br />     | jq -r '.Certificate' > client_cert2.cert</pre>有关更多信息，请参阅 AWS 文档中的[颁发私有终端实体证书](https://docs.aws.amazon.com/privateca/latest/userguide/PcaIssueCert.html)。 | DevOps 工程师，AWS DevOps | 

### 预置 Amazon Web Service
<a name="provision-aws-services"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 CloudFormation 模板 AWS 服务 进行配置。 | 要配置虚拟私有云 (VPC)、亚马逊 ECS 集群、亚马逊 ECS 服务、Application Load Balancer 和亚马逊弹性容器注册表 (Amazon ECR) Container Registry，请使用该模板。 CloudFormation  | DevOps 工程师 | 
| 获取变量。 | 请确认您拥有运行两项服务的 Amazon ECS 集群。要检索资源详细信息并将其存储为变量，请使用以下命令：<pre><br />export LoadBalancerDNS=$(aws cloudformation describe-stacks --stack-name ecs-mtls \<br />--output text \<br />--query 'Stacks[0].Outputs[?OutputKey==`LoadBalancerDNS`].OutputValue')<br /><br />export ECRRepositoryUri=$(aws cloudformation describe-stacks --stack-name ecs-mtls \<br />--output text \<br />--query 'Stacks[0].Outputs[?OutputKey==`ECRRepositoryUri`].OutputValue')<br /><br />export ECRRepositoryServiceOneUri=$(aws cloudformation describe-stacks --stack-name ecs-mtls \<br />--output text \<br />--query 'Stacks[0].Outputs[?OutputKey==`ECRRepositoryServiceOneUri`].OutputValue')<br /><br />export ECRRepositoryServiceTwoUri=$(aws cloudformation describe-stacks --stack-name ecs-mtls \<br />--output text \<br />--query 'Stacks[0].Outputs[?OutputKey==`ECRRepositoryServiceTwoUri`].OutputValue')<br /><br />export ClusterName=$(aws cloudformation describe-stacks --stack-name ecs-mtls \<br />--output text \<br />--query 'Stacks[0].Outputs[?OutputKey==`ClusterName`].OutputValue')<br /><br />export BucketName=$(aws cloudformation describe-stacks --stack-name ecs-mtls \<br />--output text \<br />--query 'Stacks[0].Outputs[?OutputKey==`BucketName`].OutputValue')<br /><br />export Service1ListenerArn=$(aws cloudformation describe-stacks --stack-name ecs-mtls \<br />--output text \<br />--query 'Stacks[0].Outputs[?OutputKey==`Service1ListenerArn`].OutputValue')<br /><br />export Service2ListenerArn=$(aws cloudformation describe-stacks --stack-name ecs-mtls \<br />--output text \<br />--query 'Stacks[0].Outputs[?OutputKey==`Service2ListenerArn`].OutputValue')</pre> | DevOps 工程师 | 
| 创建 CodeBuild 项目。 | 要使用 CodeBuild 项目为您的 Amazon ECS 服务创建 Docker 镜像，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-application-authentication-with-mutual-tls-in-amazon-ecs.html)有关更多详细信息，请参阅 AWS 文档[AWS CodeBuild中的创建构建项目](https://docs.aws.amazon.com/codebuild/latest/userguide/create-project.html)。 | AWS DevOps， DevOps 工程师 | 
| 构建 Docker 映像。 | 您可以使用 CodeBuild 来执行映像构建过程。 CodeBuild 需要权限才能与 Amazon ECR 交互和使用 Amazon S3。作为该过程的一部分，将构建 Docker 映像并将其推送至 Amazon ECR 注册表。有关模板和代码的详细信息，请参阅[其他信息](#simplify-application-authentication-with-mutual-tls-in-amazon-ecs-additional)。（可选）要在本地构建以进行测试，请使用以下命令：<pre># login to ECR<br />aws ecr get-login-password | docker login --username AWS --password-stdin $ECRRepositoryUri<br /><br /># build image for service one<br />cd /service1<br />aws s3 cp s3://$BucketName/serviceone/ service1/ --recursive<br />docker build -t $ECRRepositoryServiceOneUri .<br />docker push $ECRRepositoryServiceOneUri<br /><br /># build image for service two<br />cd ../service2<br />aws s3 cp s3://$BucketName/servicetwo/ service2/ --recursive<br />docker build -t $ECRRepositoryServiceTwoUri .<br />docker push $ECRRepositoryServiceTwoUri</pre> | DevOps 工程师 | 

### 启用双向 TLS
<a name="enable-mutual-tls"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将 CA 证书上传到 Amazon S3。 | 要将 CA 证书上传到 Amazon S3 存储桶，请使用以下示例命令：`aws s3 cp ca-cert.pem s3://$BucketName/acm-trust-store/ ` | AWS DevOps， DevOps 工程师 | 
| 创建信任存储。 | 要创建信任存储，请使用以下示例命令：<pre>TrustStoreArn=`aws elbv2 create-trust-store --name acm-pca-trust-certs \<br />    --ca-certificates-bundle-s3-bucket $BucketName \<br />    --ca-certificates-bundle-s3-key acm-trust-store/ca-cert.pem --query 'TrustStores[].TrustStoreArn' --output text`</pre> | AWS DevOps， DevOps 工程师 | 
| 上传客户端证书。 | 要将客户端证书上传到 Amazon S3 以用于 Docker 映像，请使用以下示例命令：<pre># for service one<br />aws s3 cp client_cert1.cert s3://$BucketName/serviceone/<br />aws s3 cp client_private-key1.pem s3://$BucketName/serviceone/<br /><br /># for service two<br />aws s3 cp client_cert2.cert s3://$BucketName/servicetwo/<br />aws s3 cp client_private-key2.pem s3://$BucketName/servicetwo/</pre> | AWS DevOps， DevOps 工程师 | 
| 修改侦听器。 | 要在 ALB 上启用双向 TLS，请使用以下命令修改 HTTPS 侦听器：<pre>aws elbv2 modify-listener \<br />    --listener-arn $Service1ListenerArn \<br />    --certificates CertificateArn=$TLS_CERTIFICATE_ARN_TWO \<br />    --ssl-policy ELBSecurityPolicy-2016-08 \<br />    --protocol HTTPS \<br />    --port 8080 \<br />    --mutual-authentication Mode=verify,TrustStoreArn=$TrustStoreArn,IgnoreClientCertificateExpiry=false<br /><br />aws elbv2 modify-listener \<br />    --listener-arn $Service2ListenerArn \<br />    --certificates CertificateArn=$TLS_CERTIFICATE_ARN_TWO \<br />    --ssl-policy ELBSecurityPolicy-2016-08 \<br />    --protocol HTTPS \<br />    --port 8090 \<br />    --mutual-authentication Mode=verify,TrustStoreArn=$TrustStoreArn,IgnoreClientCertificateExpiry=false<br /></pre>有关更多信息，请参阅 AWS 文档中的在 App [lication Load Balancer 上配置双向 TLS](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/configuring-mtls-with-elb.html)。 | AWS DevOps， DevOps 工程师 | 

### 更新服务
<a name="update-the-services"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新 Amazon ECS 任务定义。 | 要更新 Amazon ECS 任务定义，请修改新修订版中的 `image` 参数。要获取相应服务的值，请使用您在前面的步骤中构建的新 Docker 映像 URI 更新任务定义：`echo $ECRRepositoryServiceOneUri` 或 `echo $ECRRepositoryServiceTwoUri`<pre><br />    "containerDefinitions": [<br />        {<br />            "name": "nginx",<br />            "image": "public.ecr.aws/nginx/nginx:latest",   # <----- change to new Uri<br />            "cpu": 0,</pre>有关更多信息，请参阅 AWS 文档中的使用控制台[更新 Amazon ECS 任务定义](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/update-task-definition-console-v2.html)。 | AWS DevOps， DevOps 工程师 | 
| 更新 Amazon ECS 服务。 | 使用最新的任务定义来更新服务。此任务定义是新构建的 Docker 映像的“蓝图”，包含进行双向 TLS 身份验证所需的客户端证书。 要更新服务，请执行以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-application-authentication-with-mutual-tls-in-amazon-ecs.html)对其他服务重复上述步骤。 | AWS 管理员、AWS DevOps、 DevOps 工程师 | 

### 访问应用程序
<a name="access-the-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 复制应用程序 URL。 | 使用 Amazon ECS 控制台查看任务。当任务状态更新为**正在运行**时，选择该任务。在**任务**部分中，复制任务 ID。 | AWS 管理员，AWS DevOps | 
| 测试您的应用程序。 | 要测试您的应用程序，请使用 ECS Exec 访问任务。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-application-authentication-with-mutual-tls-in-amazon-ecs.html) | AWS 管理员，AWS DevOps | 

## 相关资源
<a name="simplify-application-authentication-with-mutual-tls-in-amazon-ecs-resources"></a>

**Amazon ECS 文档**
+ [使用控制台创建 Amazon ECS 任务定义](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-task-definition.html)
+ [创建容器镜像以在 Amazon ECS 上使用](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-container-image.html)
+ [Amazon ECS 集群](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html)
+ [适用于 Amazon ECS AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-container-image.html#create-container-image-next-steps)
+ [Amazon ECS 联网最佳实践](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/networking-best-practices.html)
+ [亚马逊 ECS 服务定义参数](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/service_definition_parameters.html)

**其他 AWS 资源**
+ [如何使用 AWS 私有 CA 在 Application Load Balancer 上配置 mTLS？](https://repost.aws/knowledge-center/elb-alb-configure-private-ca-mtls) (AWS re:Post)

## 附加信息
<a name="simplify-application-authentication-with-mutual-tls-in-amazon-ecs-additional"></a>

**编辑 Dockerfile**** **

以下代码显示了您在服务 1 的 Dockerfile 中编辑的命令：

```
FROM public.ecr.aws/nginx/nginx:latest
WORKDIR /usr/share/nginx/html
RUN echo "Returning response from Service 1: Ok" > /usr/share/nginx/html/index.html
ADD client_cert1.cert client_private-key1.pem /usr/local/share/ca-certificates/
RUN chmod -R 400 /usr/local/share/ca-certificates/
```

以下代码显示了您在服务 2 的 Dockerfile 中编辑的命令：

```
FROM public.ecr.aws/nginx/nginx:latest
WORKDIR /usr/share/nginx/html
RUN echo "Returning response from Service 2: Ok" > /usr/share/nginx/html/index.html
ADD client_cert2.cert client_private-key2.pem /usr/local/share/ca-certificates/
RUN chmod -R 400 /usr/local/share/ca-certificates/
```

如果您使用构建 Docker 镜像 CodeBuild，则该`buildspec`文件会使用 CodeBuild 内部版本号将镜像版本唯一标识为标签值。您可以根据自身需求更改 `buildspec` 文件，如下列 `buildspec ` 自定义代码所示：

```
version: 0.2

phases:
  pre_build:
    commands:
      - echo Logging in to Amazon ECR...
      - aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $ECR_REPOSITORY_URI
      - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7)
      - IMAGE_TAG=${COMMIT_HASH:=latest}
  build:
    commands:
        # change the S3 path depending on the service
      - aws s3 cp s3://$YOUR_S3_BUCKET_NAME/serviceone/ $CodeBuild_SRC_DIR/ --recursive 
      - echo Build started on `date`
      - echo Building the Docker image...
      - docker build -t $ECR_REPOSITORY_URI:latest .
      - docker tag $ECR_REPOSITORY_URI:latest $ECR_REPOSITORY_URI:$IMAGE_TAG
  post_build:
    commands:
      - echo Build completed on `date`
      - echo Pushing the Docker images...
      - docker push $ECR_REPOSITORY_URI:latest
      - docker push $ECR_REPOSITORY_URI:$IMAGE_TAG
      - echo Writing image definitions file...
      # for ECS deployment reference
      - printf '[{"name":"%s","imageUri":"%s"}]' $CONTAINER_NAME $ECR_REPOSITORY_URI:$IMAGE_TAG > imagedefinitions.json   

artifacts:
  files:
    - imagedefinitions.json
```

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

**Topics**
+ [自动删除 AWS CloudFormation 堆栈和相关资源](automate-deletion-cloudformation-stacks-associated-resources.md)
+ [使用和自动进行动态管道管理，以便在 Gitflow 环境中部署修补程序解决方案 AWS Service Catalog AWS CodePipeline](automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.md)
+ [使用 AWS CDK 自动为微服务构建 CI/CD 管道和 Amazon ECS 集群](automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.md)
+ [使用 GitHub Actions 和 Terraform 构建 Docker 镜像并将其推送到 Amazon ECR](build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform.md)
+ [对经过 Blu Age 现代化改造的大型机工作负载进行容器化](containerize-mainframe-workloads-that-have-been-modernized-by-blu-age.md)
+ [使用 Firelens 日志路由器为 Amazon ECS 创建自定义日志解析器](create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.md)
+ [通过 Terraform 在 Amazon Bedrock 上使用 CrewAI 框架部署代理式系统](deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.md)
+ [使用 Terraform 为容器化 Blu Age 应用程序部署环境](deploy-an-environment-for-containerized-blu-age-applications-by-using-terraform.md)
+ [使用 Amazon 中的推理管道将预处理逻辑部署到单个终端节点的 ML 模型中 SageMaker](deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker.md)
+ [将工作负载从 Azure DevOps 管道部署到私有的 Amazon EKS](deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.md)
+ [通过 K8sGPT 和 Amazon Bedrock 集成，实施人工智能驱动的 Kubernetes 诊断和问题排查](implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration.md)
+ [使用 AWS 代码服务和 AWS KMS 多区域密钥管理向多个账户和区域 blue/green 部署的微服务](manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.md)
+ [通过使用 AWS CDK 设置 Amazon ECS Anywhere 来管理本地容器应用程序](manage-on-premises-container-applications-by-setting-up-amazon-ecs-anywhere-with-the-aws-cdk.md)
+ [在 Amazon ECS 上从 Oracle 迁移 WebLogic 到 Apache Tomcat (ToMee)](migrate-from-oracle-weblogic-to-apache-tomcat-tomee-on-amazon-ecs.md)
+ [在 AWS 上实现 ASP.NET Web 表单应用程序的现代化](modernize-asp-net-web-forms-applications-on-aws.md)
+ [使用 AWS 和 AWS CloudFormation Config 监控亚马逊 ECR 存储库的通配符权限](monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config.md)
+ [使用 L CloudWatch ogs Insights 监控应用程序活动](monitor-application-activity-by-using-cloudwatch-logs-insights.md)
+ [使用 AWS CDK 在 Amazon ECS Anywhere 上为混合工作负载设置 CI/CD 管道和 GitLab](set-up-a-ci-cd-pipeline-for-hybrid-workloads-on-amazon-ecs-anywhere-by-using-aws-cdk-and-gitlab.md)
+ [使用证书管理器和 “让我们加 end-to-end密” 为 Amazon EKS 上的应用程序设置加密](set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt.md)
+ [使用 Flux 简化 Amazon EKS 多租户应用程序部署](simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.md)
+ [使用 SageMaker AI 和 Hydra 简化从本地开发到可扩展实验的机器学习工作流程](streamline-machine-learning-workflows-by-using-amazon-sagemaker.md)
+ [使用 AWS Lambda 以六边形架构构建 Python 项目](structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.md)
+ [使用 LocalStack 和 Terraform 测试来测试 AWS 基础架构](test-aws-infra-localstack-terraform.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)

# 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)
+ [在多存储库设置中自动部署 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)
+ [使用自动设置区域间对等互连 AWS Transit Gateway](automate-the-setup-of-inter-region-peering-with-aws-transit-gateway.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)
+ [将自定义属性发送至 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)

# Networking
<a name="networking-pattern-list"></a>

**Topics**
+ [使用自动设置区域间对等互连 AWS Transit Gateway](automate-the-setup-of-inter-region-peering-with-aws-transit-gateway.md)
+ [使用 AWS Transit Gateway 集中网络连接](centralize-network-connectivity-using-aws-transit-gateway.md)
+ [使用 Applicati EnterpriseOne on Load Balancer 为 Oracle WebLogic JD Edwards 配置 HTTPS 加密](configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer.md)
+ [通过私有网络连接到 Application Migration Service 数据和控制面板](connect-to-application-migration-service-data-and-control-planes-over-a-private-network.md)
+ [使用 AWS CloudFormation 自定义资源和 Amazon SNS 创建 Infoblox 对象](create-infoblox-objects-using-aws-cloudformation-custom-resources-and-amazon-sns.md)
+ [使用 Terraform 在上 AWS 面创建分层的多区域 IPAM 架构](multi-region-ipam-architecture.md)
+ [自定义 Amazon CloudWatch 提醒 AWS Network Firewall](customize-amazon-cloudwatch-alerts-for-aws-network-firewall.md)
+ [使用 Terraform 在 AWS Wavelength 区域中部署资源](deploy-resources-wavelength-zone-using-terraform.md)
+ [将 DNS 记录批量迁移至 Amazon Route 53 私有托管区](migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone.md)
+ [在 AWS 上从 F5 迁移到应用程序负载均衡器时修改 HTTP 标头](modify-http-headers-when-you-migrate-from-f5-to-an-application-load-balancer-on-aws.md)
+ [创建网络访问分析器在多个入站互联网访问中发现的报告 AWS 账户](create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.md)
+ [在多账户 AWS 环境中为混合网络设置 DNS 解析](set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment.md)
+ [验证 ELB 负载均衡器是否需 TLS 终止](verify-that-elb-load-balancers-require-tls-termination.md)
+ [使用 Splunk 查看 AWS Network Firewall 日志和指标](view-aws-network-firewall-logs-and-metrics-by-using-splunk.md)
+ [更多模式](networking-more-patterns-pattern-list.md)

# 使用自动设置区域间对等互连 AWS Transit Gateway
<a name="automate-the-setup-of-inter-region-peering-with-aws-transit-gateway"></a>

*Ram Kandaswamy，Amazon Web Services*

## Summary
<a name="automate-the-setup-of-inter-region-peering-with-aws-transit-gateway-summary"></a>

[AWS Transit Gateway](https://docs.aws.amazon.com/vpc/latest/tgw/what-is-transit-gateway.html)通过中央集线器连接虚拟私有云 (VPCs) 和本地网络。Transit Gateway 流量不会通过公共互联网，从而减少了威胁载体，例如常见漏洞利用和分布式拒绝服务攻击。DDo

如果您需要在两个或多个公交网关之间进行通信 AWS 区域，则可以使用区域间 Transit Gateway 对等互连在不同区域的公交网关之间建立对等连接。但是，使用 Transit Gateway 手动配置区域间对等互连可能既复杂又耗时。此模式为使用基础设施即代码 (IaC) 设置对等互连提供了指导。如果您必须重复配置多个区域以及 AWS 账户 多区域组织设置，则可以使用这种方法。

此模式在 Amazon CloudWatch Logs 中设置了一个包含 AWS Step Functions [工作流程](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-statemachines.html)、 AWS Lambda [函数](https://docs.aws.amazon.com/lambda/latest/dg/concepts-basics.html#gettingstarted-concepts-function)、 AWS Identity and Access Management (IAM) [角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)和[日志组](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html)的[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)堆栈。然后，您可以运行 Step Functions 工作流程，为您的公交网关创建区域间对等连接。

## 先决条件和限制
<a name="automate-the-setup-of-inter-region-peering-with-aws-transit-gateway-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ [具有代码生成功能的 IDE，例如 Kiro。](https://kiro.dev/#what-is-kiro)
+ 亚马逊简单存储服务 (Amazon S3) 存储桶以及向其上传对象的权限。
+ 在请求和接受区域中创建的公交网关。
+ VPCs 在请求和接受区域中创建。 VPCs 使用值为的`addToTransitGateway`密钥标记`true`。
+  VPCs 根据您的要求为您配置@@ [安全组](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html)。
+  VPCs 根据您的要求为您配置的@@ [网络访问控制列表 (ACLs)](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html)。

**限制**
+ 只有部分 AWS 区域 支持跨区域对等。有关支持区域间对等互连的区域的完整列表，请参阅。[AWS Transit Gateway FAQs](https://aws.amazon.com/transit-gateway/faqs/)

## 架构
<a name="automate-the-setup-of-inter-region-peering-with-aws-transit-gateway-architecture"></a>

 此模式中描述的代理人工智能开发方法包括以下步骤：

1. **定义自动化提示** — Kiro 会收到自然语言提示，其中详细说明了对等互连要求。

1. **生成自动化脚本** — Kiro 根据提供的提示生成 CloudFormation 和 Lambda 脚本。

1. **部署堆栈** — Kiro CloudFormation 用于部署所需的资源。

1. **设置对等 — Kiro 运行 Step** Functions 工作流程，该工作流程调用 Lambda 函数来创建对等连接和修改路由表。

下图显示了 Step Functions 的工作流程：

![\[Step Functions 工作流调用 Lambda 函数来修改中转网关对等互连的路由表。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/b678bb87-c7b9-4f7b-b26e-eaac650e5d1b/images/2f235f47-5d68-492c-b954-7dc170939cae.png)


 

工作流包含以下步骤：

1. Step Functions 工作流程为 Transit Gateway 对等互连调用 Lambda 函数。 

1. 工作流程等待一分钟。

1. 工作流程检索对等互连状态并将其发送到条件块。数据块负责循环。 

1. 如未满足成功条件，则对工作流进行编码以进入计时器阶段。 

1. 如果满足成功条件，Lambda 函数将修改路由表。

1. Step Functions 工作流程结束。

## 工具
<a name="automate-the-setup-of-inter-region-peering-with-aws-transit-gateway-tools"></a>
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在和的整个 AWS 账户 生命周期中对其进行管理 AWS 区域。 
+ [Amazon CloudWatch Lo](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) gs 可帮助您集中所有系统和应用程序的日志， AWS 服务 这样您就可以监控它们并安全地将其存档。
+ [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)[(](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)[IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)[)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [Kiro](https://kiro.dev/#what-is-kiro) 是一款代理人工智能开发工具，可帮助您通过规范驱动的开发来构建生产就绪型应用程序。 
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)是一项无服务器编排服务，可帮助您组合 AWS Lambda 功能和其他功能 AWS 服务 来构建关键业务应用程序。  

## 操作说明
<a name="automate-the-setup-of-inter-region-peering-with-aws-transit-gateway-epics"></a>

### 生成 Lambda 和 Step Functions 代码
<a name="generate-lam-and-sfn-code"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 用具体细节填充提示占位符 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-setup-of-inter-region-peering-with-aws-transit-gateway.html)或者，您可以将其添加为引用上述变量的内联提示，而无需附加文件作为上下文。 | 常规 AWS，网络管理员 | 
| 创建用于创建对等连接附件的 Lambda 函数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-setup-of-inter-region-peering-with-aws-transit-gateway.html) | 常规 AWS、网络管理员、Prompt 工程 | 
| 创建用于轮询对等连接状态的 Lambda 函数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-setup-of-inter-region-peering-with-aws-transit-gateway.html) | 常规 AWS、网络管理员、Prompt 工程 | 
| 创建一个 Lambda 函数，向两个区域添加静态路由。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-setup-of-inter-region-peering-with-aws-transit-gateway.html) | 常规 AWS，网络管理员 | 
| 创建 CloudFormation 模板。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-setup-of-inter-region-peering-with-aws-transit-gateway.html) | AWS DevOps、General AWS、Prompt 工程设计 | 

### 部署 AWS 资源
<a name="deploy-the-aws-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用提示部署 CloudFormation 堆栈。 | 输入以下提示：<pre>Using the outputs from Prompts 1-4, package and deploy the full stack. Steps:<br /><br />1. For each of the three Python files from Prompts 1-3, create a zip named after the file (e.g. peer-transit-gateway.zip that contains peer-transit-gateway.py).<br />2. Upload all three zips to S3_BUCKET.<br />3. Deploy the CloudFormation template from Prompt 4 to ACTIVE_REGION with S3BucketName=S3_BUCKET and CAPABILITY_NAMED_IAM.<br />4. Initiate the Step Function from the deployed stack.<br /><br />Zip file names must match the S3Key values in the template exactly.</pre> | AWS DevOps、云管理员、常规 AWS、Prompt 工程 | 
| 验证部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-setup-of-inter-region-peering-with-aws-transit-gateway.html) | 常规 AWS | 

## 相关资源
<a name="automate-the-setup-of-inter-region-peering-with-aws-transit-gateway-resources"></a>
+ [在 Step Functions 中启动状态机执行](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-state-machine-executions.html)
+ [Transit Gateway 对等连接](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-peering.html)
+ [AWS 区域 使用互 VPCs 连 AWS Transit Gateway](https://www.youtube.com/watch?v=cj1rQqLxXU8)（视频）

# 使用 AWS Transit Gateway 集中网络连接
<a name="centralize-network-connectivity-using-aws-transit-gateway"></a>

*Mydhili Palagummi 和 Nikhil Marrapu，Amazon Web Services*

## Summary
<a name="centralize-network-connectivity-using-aws-transit-gateway-summary"></a>

此模式描述了最简单的配置，在该配置中，AWS Transit Gateway 可用于将本地网络连接到 AWS 区域内多个 AWS 账户中的虚拟私有云 (VPCs)。使用此设置，您可以建立一个连接区域中多个 VPC 网络和本地网络的混合网络。这是通过使用运输网关和与本地网络的虚拟专用网络（VPN）连接来完成的。

## 先决条件和限制
<a name="centralize-network-connectivity-using-aws-transit-gateway-prereqs"></a>

**先决条件**
+ 托管网络服务的账户，作为 AWS Organizations 组织的会员账户管理
+ VPCs 在多个 AWS 账户中，没有重叠的无类域间路由 (CIDR) 块

**限制**

此模式不支持在特定网络 VPCs 或本地网络之间隔离流量。连接到运输网关的所有网络都将能够相互联系。若要隔离流量，您需要在公交网关上使用自定义路由表。此模式仅使用单个默认中转网关路由表（这是最简单的配置）来连接 VPCs 和本地网络。

## 架构
<a name="centralize-network-connectivity-using-aws-transit-gateway-architecture"></a>

**目标技术堆栈**
+ AWS Transit Gateway
+ AWS Site-to-Site VPN
+ VPC
+ AWS Resource Access Manager (AWS RAM)

 

**目标架构 **

![\[AWS Transit Gateway 将本地网络连接到一个区域 VPCs 内的多个 AWS 账户。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e23f5faf-e75e-42a3-80e3-142516a2db4e/images/1ecf7e04-bbf8-4304-88c8-6aceb7271d1e.jpeg)


## 工具
<a name="centralize-network-connectivity-using-aws-transit-gateway-tools"></a>

**Amazon Web Services**
+ [AWS Resource Access Manager（AWS RAM）](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html)可帮助您从 AWS Organizations 在 AWS 账户、组织单位或整个组织之间安全地共享资源。
+ [AWS Transit Gateway](https://docs.aws.amazon.com/vpc/latest/tgw/what-is-transit-gateway.html) 是一个连接虚拟私有云 (VPCs) 和本地网络的中心枢纽。

## 操作说明
<a name="centralize-network-connectivity-using-aws-transit-gateway-epics"></a>

### 在网络服务账户创建中转网关
<a name="create-a-transit-gateway-in-the-network-services-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建中转网关。 | 在您要托管网络服务的 AWS 账户中，在目标 AWS 区域创建传输网关。有关说明，请参阅[创建中转网关](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-transit-gateways.html#create-tgw)。注意以下几点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-network-connectivity-using-aws-transit-gateway.html) | 网络管理员 | 

### 将中转网关连接至本地网络
<a name="connect-the-transit-gateway-to-your-on-premises-network"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 VPN 连接设置客户网关设备。 | 客户网关设备连接在传输网关和您的本地网络之间的 Site-to-Site VPN 连接的本地端。有关更多信息，请参阅 AWS Site-to-Site VPN 文档中的[您的客户网关设备](https://docs.aws.amazon.com/vpn/latest/s2svpn/your-cgw.html)。识别或启动支持的本地客户设备，并记录其公共IP地址。VPN 配置将在本操作说明的稍后部分完成。 | 网络管理员 | 
| 在网络服务账户中，创建到中转网关的 VPN 连接。 | 要设置连接，请为运输网关创建 VPN 附件。有关说明，请参阅[公交网关 VPN 附件](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpn-attachments.html)。 | 网络管理员 | 
| 在本地网络中的客户网关设备上配置 VPN。 | 下载与传输网关关联的 Site-to-Site VPN 连接的配置文件，并在客户网关设备上配置 VPN 设置。有关说明，请参阅[下载配置文件](https://docs.aws.amazon.com/vpn/latest/s2svpn/SetUpVPNConnections.html#vpn-download-config)。 | 网络管理员 | 

### 在网络服务账户中与其他 AWS 账户或您的组织共享运输网关
<a name="share-the-transit-gateway-in-the-network-services-account-to-other-aws-accounts-or-your-organization"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 AWS Organizations 管理账户，开启共享。 | 若要与您的组织或某些组织单位共享公交网关，请在 AWS Organizations 中开启共享。否则，您将需要分别分别为每个账户共享运输网关。有关说明，请参阅[在 AWS Organizations 内启用资源共享](https://docs.aws.amazon.com/ram/latest/userguide/getting-started-sharing.html#getting-started-sharing-orgs)。 | AWS 系统管理员 | 
| 在网络服务账户中创建中转网关资源共享。 | 要允许组织 VPCs 内的其他 AWS 账户连接到公交网关，请在网络服务账户中使用 AWS RAM 控制台共享公交网关资源。有关说明，请参阅[创建资源共享](https://docs.aws.amazon.com/ram/latest/userguide/getting-started-sharing.html#getting-started-sharing-create)。 | AWS 系统管理员 | 

### Connect VPCs 连接到公交网关
<a name="connect-vpcs-to-the-transit-gateway"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在个人账户中创建 VPC 附件。 | 在共享过境网关的账户，创建中转网关 VPC 附件。有关说明，请参阅[创建到 VPC 的中转网关连接](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html#create-vpc-attachment)。 | 网络管理员 | 
| 接受 VPC 附件请求。 | 在网络服务账户中，接受运输网关 VPC 附件请求。有关说明，请参阅[接受共享附件](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-transit-gateways.html#tgw-accept-shared-attachment)。 | 网络管理员 | 

### 配置路由
<a name="configure-routing"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在个人账户中配置路由 VPCs。 | 在每个单独的账户 VPC 中，将路由添加到本地网络和其他 VPC 网络，使用 Transit Gateway 作为目标。有关说明，请参阅[在路由表中添加和删除路由](https://docs.aws.amazon.com/vpc/latest/userguide/WorkWithRouteTables.html#AddRemoveRoutes)。 | 网络管理员 | 
| 在中转网关路由表中配置路由。 | 应传播来自 VPCs 和 VPN 连接的路由，并应出现在传输网关的默认路由表中。如果需要，可在传输网关默认路由表中创建任何静态路由（例如，静态 VPN 连接的静态路由）。有关说明，请参阅[创建静态路由](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html#tgw-create-static-route)。 | 网络管理员 | 
| 添加安全组和网络访问控制列表 (ACL) 规则。 | 对于 VPC 中的 EC2 实例和其他资源，请确保安全组规则和网络 ACL 规则允许本地网络之间的 VPCs 流量。有关说明，请参阅[使用安全组控制资源流量](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#AddRemoveRules)和[在 ACL 中添加和删除规则](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html#Rules)。 | 网络管理员 | 

### 测试连接
<a name="test-connectivity"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 测试两者之间的连通性 VPCs。 | 确保网络 ACL 和安全组允许 Internet 控制消息协议 (ICMP) 流量，然后从 VPC 中的实例执行 ping 操作，也连接至中转网关的VPC。 | 网络管理员 | 
| 测试 VPCs 与本地网络之间的连接。 | 确保网络 ACL 规则、安全组规则和所有防火墙允许 ICMP 流量，然后在本地网络和中的 EC2 实例之间执行 ping 操作。 VPCs必须先从本地网络启动网络通信，才能使 VPN 连接处于 `UP` 状态。 | 网络管理员 | 

## 相关资源
<a name="centralize-network-connectivity-using-aws-transit-gateway-resources"></a>
+ [构建可扩展的安全多 VPC AWS 网络基础设施](https://d1.awsstatic.com/whitepapers/building-a-scalable-and-secure-multi-vpc-aws-network-infrastructure.pdf)（AWS 白皮书）
+ [使用共享资源](https://docs.aws.amazon.com/ram/latest/userguide/working-with.html)（AWS RAM 文档）
+ [使用中转网关](https://docs.aws.amazon.com/vpc/latest/tgw/working-with-transit-gateways.html)（AWS Transit Gateway 文档）

# 使用 Applicati EnterpriseOne on Load Balancer 为 Oracle WebLogic JD Edwards 配置 HTTPS 加密
<a name="configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer"></a>

*Thanigaivel Thirumalai，Amazon Web Services*

## Summary
<a name="configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer-summary"></a>

此模式说明了如何在 Oracle JD Edwards 中为 Oracle 工作负载 EnterpriseOne 上的 SSL 卸载配置 HTTPS 加密。 WebLogic 这种方法对用户浏览器和负载均衡器之间的流量进行加密，从而减轻 EnterpriseOne 服务器的加密负担。

许多用户使用 AWS App [lication Load Balancer 水平扩展 JA](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html) V EnterpriseOne A 虚拟机 (JVM) 层。负载均衡器充当客户端的单一联系点，并将传入流量分配给多个 JVMs客户端。或者，负载均衡器可以将流量分配到多个可用区并提高的可用性 EnterpriseOne。

此模式中描述的过程在浏览器和负载均衡器之间配置加密，而不是加密负载均衡器与之间的流量。 EnterpriseOne JVMs这种方法被称为 *SSL 分流*。将 SSL 解密过程从 EnterpriseOne Web 或应用程序服务器转移到 Application Load Balancer 可以减轻应用程序端的负担。负载均衡器终止 SSL 后，未加密的流量将路由到 AWS 上的应用程序。

[Oracle JD Edwards EnterpriseOne](https://www.oracle.com/applications/jd-edwards-enterpriseone/) 是一款企业资源规划 (ERP) 解决方案，适用于制造、构造、分销、维修或管理产品或实物资产的组织。JD Edwards EnterpriseOne 支持各种硬件、操作系统和数据库平台。

## 先决条件和限制
<a name="configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 有权进行 AWS 服务调用和管理 AWS 资源的 AWS Identity and Access Management（IAM）角色
+ SSL 证书

**产品版本**
+ 此模式已在 Oracle WebLogic 12c 中进行了测试，但您也可以使用其他版本。

## 架构
<a name="configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer-architecture"></a>

有多种方法可以执行 SSL 分流。此模式使用应用程序负载均衡器和 Oracle HTTP Server (OHS)，如下图所示。

![\[使用负载均衡器和 OHS 分流 SSL\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/c62b976b-31e4-42ca-b7e8-13f7c9d9a187/images/2ae2d0eb-b9f3-41f8-ad86-9af3aade7072.png)


下图显示了 JD Edwards EnterpriseOne、Application Load Balancer 和 Java 应用程序服务器 (JAS) JVM 布局。

![\[EnterpriseOne、负载均衡器和 JAS JVM 布局\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/c62b976b-31e4-42ca-b7e8-13f7c9d9a187/images/72ea35b0-2907-48b3-aeb7-0c5d9a3b831b.png)


## 工具
<a name="configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer-tools"></a>

**AWS 服务**
+ [应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/)将传入的应用程序流量分配到多个可用区域中的多个目标，例如亚马逊弹性计算云（Amazon EC2 实例）。
+ [AWS Certifice Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html) 可帮助您创建、存储和续订 X.509 公有和私有 SSL/TLS X.509 证书和密钥，以保护您的 AWS 网站和应用程序。
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一种可用性高、可扩展性强的 DNS Web 服务。

## 最佳实践
<a name="configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer-best-practices"></a>
+ 有关 ACM 最佳实践，请参阅 [ACM 文档](https://docs.aws.amazon.com/acm/latest/userguide/acm-bestpractices.html)。

## 操作说明
<a name="configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer-epics"></a>

### 设置 WebLogic 和 OHS
<a name="set-up-weblogic-and-ohs"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装与配置 Oracle 组件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer.html) | JDE CNC，管理员 WebLogic  | 
| 在域级别启用该 WebLogic 插件。 | 该 WebLogic 插件是负载平衡所必需的。要启用该插件，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer.html) | JDE CNC，管理员 WebLogic  | 
| 编辑 配置文件。 | 该`mod_wl_ohs.conf`文件将来自 OHS 的代理请求配置为。 WebLogic[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer.html)<pre><VirtualHost *:8000><br /><Location /jde><br />WLSRequest On<br />SetHandler weblogic-handler<br />WebLogicHost localhost<br />WebLogicPort 8000<br />WLProxySSL On<br />WLProxySSLPassThrough On<br /></Location><br /></VirtualHost></pre> | JDE CNC，管理员 WebLogic  | 
| 使用 Enterprise Manager 启动 OHS。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer.html) | JDE CNC，管理员 WebLogic  | 

### 配置应用程序负载均衡器。
<a name="configure-the-application-load-balancer"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置组。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer.html)有关详细说明，请参阅[弹性负载均衡文档](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-target-group.html)。 | AWS 管理员 | 
| 设置负载均衡器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer.html) | AWS 管理员 | 
| 添加一条 Route 53 (DNS) 记录。 | （可选）您可为子域名添加 Amazon Route 53 的 DNS 记录。这条记录将指向您的应用程序负载均衡器。有关说明，请参阅 [Route 53 文档](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html)。 | AWS 管理员 | 

## 问题排查
<a name="configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| HTTP 服务器未显示。 | 如果 **HTTP 服务器**未出现在 Enterprise Manager 控制台的**目标导航**列表，请执行以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer.html)创建实例并激活更改后，您将能够在**目标导航**面板看到 HTTP 服务器。 | 

## 相关资源
<a name="configure-https-encryption-for-oracle-jd-edwards-enterpriseone-on-oracle-weblogic-by-using-an-application-load-balancer-resources"></a>

**AWS 文档**
+ [应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html)
+ [使用公有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/AboutHZWorkingWith.html)
+ [使用私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html)

**Oracle 文档：**
+ [Oracle WebLogic 服务器代理插件概述](https://docs.oracle.com/middleware/1221/webtier/develop-plugin/overview.htm#PLGWL391)
+ [使用基础架构安装程序安装 WebLogic 服务器](https://www.oracle.com/webfolder/technetwork/tutorials/obe/fmw/wls/12c/12_2_1/02-01-004-InstallWLSInfrastructure/installweblogicinfrastructure.html)
+ [安装和配置 Oracle HTTP Server](https://docs.oracle.com/middleware/1221/core/install-ohs/toc.htm)

# 通过私有网络连接到 Application Migration Service 数据和控制面板
<a name="connect-to-application-migration-service-data-and-control-planes-over-a-private-network"></a>

*Dipin Jain 和 Mike Kuznetsov，Amazon Web Services*

## Summary
<a name="connect-to-application-migration-service-data-and-control-planes-over-a-private-network-summary"></a>

此模式说明了如何使用接口 VPC 终端节点连接到安全私有网络上的 AWS Application Migration Service 数据平面和控制平面。

应用程序迁移服务是一种高度自动化 lift-and-shift（重新托管）的解决方案，可简化、加快应用程序迁移并降低向其迁移的成本。 AWS它使公司能够重新托管大量物理、虚拟或云服务器，而不会出现兼容性问题、性能中断或长时间的割接窗口。Application Migration Service 可从 AWS 管理控制台获取。这样可以与其他 AWS 服务公司（例如 Amazon CloudWatch 和 AWS Identity and Access Management (IAM)）进行无缝集成。 AWS CloudTrail

您可以使用应用程序迁移服务中的服务 Site-to-Site VPN AWS Direct Connect或 VPC 对等互连，通过私有连接从源数据中心连接到数据平面，即连接到用作目标 VPC 中数据复制暂存区域的子网。您还可以使用由提供支持的[接口 VPC 终端节点](https://docs.aws.amazon.com/vpc/latest/privatelink/vpce-interface.html)通过私有网络 AWS PrivateLink 连接到应用程序迁移服务控制平面。 

## 先决条件和限制
<a name="connect-to-application-migration-service-data-and-control-planes-over-a-private-network-prereqs"></a>

**先决条件**
+ **暂存区域子网** — 在设置应用程序迁移服务之前，请创建一个子网，用作从源服务器复制到 AWS （即数据平面）的数据的暂存区域。首次访问 Application Migration Service 控制台时，必须在[复制设置模板](https://docs.aws.amazon.com/mgn/latest/ug/template-vs-server.html)中指定此子网。您可以在“复制设置”模板中为特定源服务器覆盖此子网。尽管您可以使用自己的现有子网 AWS 账户，但我们建议您为此目的创建一个新的专用子网。
+ **网络要求** — 由应用程序迁移服务在您的暂存区域子网中启动的复制服务器必须能够将数据发送到应用程序迁移服务 API 终端节点`https://mgn.<region>.amazonaws.com/`，其中`<region>`是 AWS 区域 您要复制到的代码（例如）。`https://mgn.us-east-1.amazonaws.com`下载应用程序迁移服务软件需要亚马逊简单存储服务 (Amazon S3) S URLs ervice 服务。
  +  AWS 复制代理安装程序应有权访问您在应用程序迁移服务中使用的亚马逊简单存储服务 (Amazon S3) 存储桶 URL。 AWS 区域 
  + 暂存区子网应有权访问 Amazon S3。
  + 安装了 AWS Replication Agent 的源服务器必须能够将数据发送到暂存区域子网中的复制服务器和位于的应用程序迁移服务 API 端点。`https://mgn.<region>.amazonaws.com/`

下表列出了所需端口。


| 
| 
| 来源 | 目标位置 | 端口 | 有关更多信息，请参阅 | 
| --- |--- |--- |--- |
| 源数据中心 | 亚马逊 S3 服务 URLs | 443（TCP） | [通过 TCP 端口 443 进行通信](https://docs.aws.amazon.com/mgn/latest/ug/Network-Requirements.html#TCP-443) | 
| 源数据中心 | Application Migration Service 的AWS 区域特定控制台地址 | 443（TCP） | [源服务器与 Application Migration Service 之间通过 TCP 端口 443 进行通信](https://docs.aws.amazon.com/mgn/latest/ug/Network-Requirements.html#Source-Manager-TCP-443) | 
| 源数据中心 | 暂存区子网 | 1500 (TCP) | [源服务器与暂存区子网之间通过 TCP 端口 1500 进行通信](https://docs.aws.amazon.com/mgn/latest/ug/Network-Requirements.html#Communication-TCP-1500) | 
| 暂存区子网 | Application Migration Service 的AWS 区域特定控制台地址 | 443（TCP） | [暂存区子网与 Application Migration Service 之间通过 TCP 端口 443 进行通信](https://docs.aws.amazon.com/mgn/latest/ug/Network-Requirements.html#Communication-TCP-443-Staging) | 
| 暂存区子网 | 亚马逊 S3 服务 URLs | 443（TCP） | [通过 TCP 端口 443 进行通信](https://docs.aws.amazon.com/mgn/latest/ug/Network-Requirements.html#TCP-443) | 
| 暂存区子网 | 子网的亚马逊弹性计算云 (Amazon EC2) 终端节点 AWS 区域 | 443（TCP） | [通过 TCP 端口 443 进行通信](https://docs.aws.amazon.com/mgn/latest/ug/Network-Requirements.html#TCP-443) | 

** 限制**

应用程序迁移服务目前并非在所有操作系统中 AWS 区域 都可用。
+ [支持的 AWS 区域](https://docs.aws.amazon.com/mgn/latest/ug/supported-regions.html)
+ [支持的操作系统](https://docs.aws.amazon.com/mgn/latest/ug/Supported-Operating-Systems.html)

## 架构
<a name="connect-to-application-migration-service-data-and-control-planes-over-a-private-network-architecture"></a>

下图展示了典型迁移的网络架构。有关此架构的更多信息，请参阅 [Application Migration Service 文档](https://docs.aws.amazon.com/mgn/latest/ug/Network-Settings-Video.html)和 [Application Migration Service 架构和网络架构视频](https://youtu.be/ao8geVzmmRo)。

![\[典型迁移的 Application Migration Service 的网络架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/21346c0f-0643-4f4f-b21f-fdfe24fc6a8f/images/546598b2-8026-4849-a441-eaa2bc2bf6bb.png)


以下详细视图显示了暂存区 VPC 中用于连接 Amazon S3 和 Application Migration Service 的接口 VPC 端点的配置。

![\[典型迁移的 Application Migration Service 的网络架构 - 详细视图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/21346c0f-0643-4f4f-b21f-fdfe24fc6a8f/images/bd0dfd42-4ab0-466f-b696-804dedcf4513.png)


## 工具
<a name="connect-to-application-migration-service-data-and-control-planes-over-a-private-network-tools"></a>
+ [AWS Application Migration Service](https://docs.aws.amazon.com/mgn/latest/ug/what-is-application-migration-service.html)简化、加快并降低在上重新托管应用程序的成本。 AWS
+ [接口 VPC 终端节点](https://docs.aws.amazon.com/vpc/latest/privatelink/vpce-interface.html)使您 AWS PrivateLink 无需互联网网关、NAT 设备、VPN 连接或 AWS Direct Connect 连接即可连接到由其提供支持的服务。VPC 中的实例无需公有 IP 地址便可与 服务中的资源通信。VPC 和其他服务之间的通信不会离开 Amazon 网络。

## 操作说明
<a name="connect-to-application-migration-service-data-and-control-planes-over-a-private-network-epics"></a>

### 为应用程序迁移服务、Amazon 和 Amazon EC2 S3 创建终端节点
<a name="create-endpoints-for-mgn-ec2-and-s3"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 Application Migration Service 配置接口端点。 | 源数据中心和暂存区 VPC 通过您在目标暂存区 VPC 中创建的接口端点以私有方式连接到 Application Migration Service 控制面板。要创建端点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/connect-to-application-migration-service-data-and-control-planes-over-a-private-network.html)有关更多信息，请参阅 [Amazon VPC 文档中的 AWS 服务 使用接口 VPC 终端节点访问](https://docs.aws.amazon.com/vpc/latest/privatelink/vpce-interface.html)和。 | 迁移主管 | 
| 为 Amazon 配置接口终端节点 EC2。 | 暂存区域 VPC 通过您在目标暂存区域 VPC 中创建的接口终端节点私下连接到 Amazon EC2 API。若要创建端点，请按照上一篇文章中提供的说明进行操作。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/connect-to-application-migration-service-data-and-control-planes-over-a-private-network.html) | 迁移主管 | 
| 配置 Amazon S3 的接口端点。 | 源数据中心和暂存区 VPC 通过您在目标暂存区 VPC 中创建的接口端点以私有方式连接到 Amazon S3 API。若要创建端点，请按照第一篇文章提供中的说明进行操作。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/connect-to-application-migration-service-data-and-control-planes-over-a-private-network.html)您使用接口端点是因为网关端点连接无法扩展到 VPC 之外。（有关详细信息，请参阅 [AWS PrivateLink 文档](https://docs.aws.amazon.com/vpc/latest/privatelink/vpce-gateway.html)。） | 迁移主管 | 
| 配置 Amazon S3 网关端点。 | 在配置阶段，复制服务器必须连接到 S3 存储桶才能下载 AWS 复制服务器的软件更新。但是，Amazon S3 接口端点不支持私有 DNS 名称*，*并且无法向复制服务器提供 Amazon S3 端点 DNS 名称。 要缓解此问题，请在暂存区子网所属的 VPC 中创建一个 Amazon S3 网关端点，并使用相关路由更新暂存子网的路由表。有关更多信息，请参阅 AWS PrivateLink 文档中的[创建网关终端节点](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-s3.html#create-gateway-endpoint-s3)。 | 云管理员 | 
| 配置本地 DNS 以解析端点的私有 DNS 名称。 | 应用程序迁移服务和 Amazon 的接口终端节点 EC2 具有可在 VPC 中解析的私有 DNS 名称。但是，您还需要配置本地服务器以解析这些接口端点的私有 DNS 名称。配置这些服务器有多种方法。在这种模式中，我们通过将本地 DNS 查询转发到暂存区域 VPC 中的 Amazon Route 53 Resolver 入站终端节点来测试此功能。有关更多信息，请参阅 Route 53 文档中的[解析 VPCs 与您的网络之间的 DNS 查询](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-overview-DSN-queries-to-vpc.html)。 | 迁移工程师 | 

### 通过私有链接连接到 Application Migration Service 控制面板
<a name="connect-to-the-mgn-control-plane-over-a-private-link"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用安装 AWS 复制代理 AWS PrivateLink。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/connect-to-application-migration-service-data-and-control-planes-over-a-private-network.html)以下是 Linux 的示例：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/connect-to-application-migration-service-data-and-control-planes-over-a-private-network.html)与应用程序迁移服务建立连接并安装 AWS 复制代理后，请按照[应用程序迁移服务文档](https://docs.aws.amazon.com/mgn/latest/ug/migration-workflow-gs.html)中的说明将源服务器迁移到目标 VPC 和子网。 | 迁移工程师 | 

## 相关资源
<a name="connect-to-application-migration-service-data-and-control-planes-over-a-private-network-resources"></a>

**Application Migration Service 文档**
+ [概念](https://docs.aws.amazon.com/mgn/latest/ug/CloudEndure-Concepts.html)
+ [迁移工作流](https://docs.aws.amazon.com/mgn/latest/ug/migration-workflow-gs.html)
+ [快速入门指南](https://docs.aws.amazon.com/mgn/latest/ug/quick-start-guide-gs.html)
+ [常见问题解答](https://docs.aws.amazon.com/mgn/latest/ug/FAQ.html)
+ [故障排查](https://docs.aws.amazon.com/mgn/latest/ug/troubleshooting.html)

**其他资源**
+ 使用 [VPC 接口终端节点在多账户架构中重新托管您的应用程序](https://docs.aws.amazon.com/prescriptive-guidance/latest/rehost-multi-account-architecture-interface-endpoints/)（AWS 规范性指导指南） AWS 
+ [AWS Application Migration Service — 技术简介](https://www.aws.training/Details/eLearning?id=71732)（AWS 培训和认证演练）
+ [AWS Application Migration Service 架构和网络架构](https://youtu.be/ao8geVzmmRo)（视频）

## 附加信息
<a name="connect-to-application-migration-service-data-and-control-planes-over-a-private-network-additional"></a>

对 **Linux 服务器上的*AWS *复制代理安装进行****故障排除**

如果您在 Amazon Linux 服务器上收到 **gcc** 错误，请配置软件包存储库并使用以下命令：

```
## sudo yum groupinstall "Development Tools"
```

# 使用 AWS CloudFormation 自定义资源和 Amazon SNS 创建 Infoblox 对象
<a name="create-infoblox-objects-using-aws-cloudformation-custom-resources-and-amazon-sns"></a>

*Tim Sutton，Amazon Web Services*

## Summary
<a name="create-infoblox-objects-using-aws-cloudformation-custom-resources-and-amazon-sns-summary"></a>

**注意**： AWS Cloud9 不再向新客户开放。的现有客户 AWS Cloud9 可以继续照常使用该服务。[了解详情](https://aws.amazon.com/blogs/devops/how-to-migrate-from-aws-cloud9-to-aws-ide-toolkits-or-aws-cloudshell/)

Infoblox 域名系统（DNS）、动态主机配置协议（DHCP）和 IP 地址管理（[Infoblox DDI](https://www.infoblox.com/products/ddi/)）使您能够集中并高效控制复杂的混合环境。借助 Infoblox DDI，除了使用相同的设备管理本地和 Amazon Web Services （AWS） 云上的 DNS 外，您还可以在一个权威 IP 地址管理器（IPAM）数据库中发现和记录所有网络资产。

此模式描述了如何使用 AWS CloudFormation 自定义资源通过调用 Infoblox WAPI 来创建 Infoblox 对象（例如 DNS 记录或 IPAM 对象）。有关 Infoblox WAPI 的详细信息，请参阅 Infoblox 文档中的 [WAPI 文档](https://www.infoblox.com/wp-content/uploads/infoblox-deployment-infoblox-rest-api.pdf)。

通过使用此模式的方法，除了删除创建记录和预置网络的手动流程外，您还可以获得 AWS 和本地环境的 DNS 记录和 IPAM 配置的统一视图。您可以将此模式的方法用于以下用例：
+ 在创建亚马逊弹性计算云 (Amazon EC2) 实例后添加 A 记录 
+ 创建应用程序负载均衡器后添加 CNAME 记录
+ 创建虚拟私有云（VPC）后添加网络对象
+ 提供下一个网络范围并使用该范围创建子网

您还可以扩展此模式并使用其他 Infoblox 设备功能，例如添加不同的 DNS 记录类型或配置 Infoblox vDiscovery。 

该模式使用的 hub-and-spoke设计是，中心需要连接到 AWS 云上或本地的 Infoblox 设备，并使用 AWS Lambda 调用 Infoblox API。分支位于 AWS Organizations 中同一组织中的相同或不同账户中，并使用 AWS CloudFormation 自定义资源调用 Lambda 函数。

## 先决条件和限制
<a name="create-infoblox-objects-using-aws-cloudformation-custom-resources-and-amazon-sns-prereqs"></a>

**先决条件**
+ 现有的 Infoblox 设备或网格，安装在 AWS Cloud和/或本地，并配置了可以管理 IPAM 和 DNS 操作的管理员用户。有关此内容的详细信息，请参阅 Infoblox 文档中的[关于管理员账户](https://docs.infoblox.com/display/nios86/About+Admin+Accounts)。 
+ 要在 Infoblox 设备上添加记录的现有 DNS 权威区域。有关此内容的更多信息，请参阅 [Infoblox 文档中的配置权威区域](https://docs.infoblox.com/display/nios86/Configuring+Authoritative+Zones)。 
+ AWS Organizations 中的两个活动 Amazon Web Services account。一个账户是中心账户，另一个账户是分支账户。
+ 中心账户和分支账户必须位于同一个 AWS 区域。 
+ 中心账户的 VPC 必须连接到 Infoblox 设备；例如，通过使用 AWS Transit Gateway 或 VPC 对等连接。
+ [AWS 无服务器应用程序模型 (AWS SAM) Model，在本地安装并使用 AWS](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html) Cloud9 或 AWS 进行配置。 CloudShell
+ `Infoblox-Hub.zip` 和 `ClientTest.yaml` 文件（附加），下载到包含 AWS SAM 的本地环境。

**限制**
+ AWS CloudFormation 自定义资源的服务令牌必须来自创建堆栈的同一区域。我们建议您在每个区域中使用中心账户，而不是在一个区域中创建 Amazon Simple Notification Service（Amazon SNS）主题，然后在另一个区域调用 Lambda 函数。

**产品版本**
+ Infoblox WAPI 版本 2.7

## 架构
<a name="create-infoblox-objects-using-aws-cloudformation-custom-resources-and-amazon-sns-architecture"></a>

下图演示了此模式的工作流程。 

![\[使用 AWS CloudFormation 自定义资源和 Amazon SNS 创建 Infoblox 对象。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/8d609d3f-6f5e-4084-849f-ca191db8055e/images/3594a064-e103-4211-84b7-da67c41ebb15.png)


该图显示了此模式解决方案的以下组件：

1. AWS CloudFormation 自定义资源允许您在创建、更新或删除堆栈时 AWS CloudFormation 运行的模板中编写自定义配置逻辑。当您创建堆栈时，AWS CloudFormation 会向由 EC2 实例上运行的应用程序监控的 SNS 主题发送`create`请求。

1. 来自 AWS CloudFormation 自定义资源的 Amazon SNS 通知通过特定的 AWS 密钥管理服务 (AWS KMS) 密钥进行加密，并且仅限组织中的账户访问 Organizations。SNS 主题启动调用 Infoblox WAPI API 的 Lambda 资源。

1. Amazon SNS 调用以下 Lambda 函数，这些函数将 Infoblox WAPI 网址、用户名和密码 AWS Secrets Manager 亚马逊资源名称 () 作为环境变量：ARNs 
   + `dnsapi.lambda_handler`— 从 AWS CloudFormation 自定义资源中接收`DNSName``DNSType`、和`DNSValue`值，并使用这些值创建 DNS A 记录和别名记录。
   + `ipaddr.lambda_handler`— 从 AWS CloudFormation 自定义资源接收`VPCCIDR``Type``SubnetPrefix`、、和`Network Name`值，并使用这些值将网络数据添加到 Infoblox IPAM 数据库中，或者为自定义资源提供下一个可用于创建新子网的可用网络。
   + `describeprefixes.lambda_handler` – 使用 `"com.amazonaws."+Region+".s3"` 筛选条件调用 `describe_managed_prefix_lists` AWS API 以检索所需 `prefix ID`。
**重要**  
这些 Lambda 函数是用 Python 编写的，彼此相似，但调用方式不同。 APIs

1. 您可以将 Infoblox 网格部署为物理、虚拟或基于云的网络设备。 它可以在本地部署，也可以使用一系列虚拟机管理程序作为虚拟设备部署，包括 VMware ESXi微软 Hyper-V、Linux KVM 和 Xen。您还可以使用亚马逊机器映像（AMI）在 Amazon Web Services Cloud 上部署 Infoblox 网格。

1. 该图显示了 Infoblox 网格的混合解决方案，该解决方案为 Amazon Web Services Cloud 和本地资源提供 DNS 和 IPAM。

**技术堆栈**
+ AWS CloudFormation
+ IAM
+ AWS KMS
+ AWS Lambda
+ AWS SAM
+ AWS Secrets Manager
+ Amazon SNS
+ Amazon VPC 

## 工具
<a name="create-infoblox-objects-using-aws-cloudformation-custom-resources-and-amazon-sns-tools"></a>
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可帮助您设置 AWS 资源，快速一致地配置这些资源，并在 AWS 账户和区域的整个生命周期中对其进行管理。
+ [AWS Identity and Access Management (AWS IAM) ](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)通过控制验证和授权使用您 AWS 资源的用户，帮助您安全地管理对您 AWS 资源的访问。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可帮助您创建和控制加密密钥，以帮助保护您的数据。
+ [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 账户整合到您所创建的组织中并进行集中管理。
+ [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) 帮助您将代码中的硬编码凭证（包括密码）替换为对 Secrets Manager 的 API 调用，以便以编程方式检索密钥。
+ [AWS Serverless Application Model（AWS SAM）](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/what-is-sam.html)是一个开源框架，帮助您在 Amazon Web Services Cloud 中构建无服务器应用程序。
+ [Amazon Simple Notiﬁcation Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可帮助您协调和管理发布者与客户端（包括 Web 服务器和电子邮件地址）之间的消息交换。
+ [Amazon Virtual Private Cloud (Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) 可帮助您将 AWS 资源启动到您定义的虚拟网络中。此虚拟网络类似于您在自己的数据中心内运行的传统网络，具有使用 AWS 可扩展基础设施的优势。

**代码**

您可以使用`ClientTest.yaml`示例 AWS CloudFormation 模板（附后）来测试 Infoblox 中心。您可以自定义 AWS CloudFormation 模板以包含下表中的自定义资源。


|  | 
| --- |
| 使用 Infoblox 分支自定义资源创建 A 记录 | 返回值： `infobloxref ` – Infoblox 参考资料示例资源：

```
ARECORDCustomResource:

  Type: "Custom::InfobloxAPI"

  Properties:

    ServiceToken: !Sub  arn:aws:sns:${AWS::Region}:${HubAccountID}:RunInfobloxDNSFunction

    DNSName: 'arecordtest.company.com'

    DNSType: 'ARecord' 

    DNSValue: '10.0.0.1'
``` | 
| --- |--- |
| 使用 Infoblox 分支自定义资源创建 CNAME 记录 | **返回值**： `infobloxref ` – Infoblox 参考资料**示例资源**：<pre>CNAMECustomResource:<br /><br />  Type: "Custom::InfobloxAPI"<br /><br />  Properties:<br /><br />    ServiceToken: !Sub arn:aws:sns:${AWS::Region}:${HubAccountID}:RunInfoblox    <br /><br />    DNSFunction<br /><br />    DNSName: 'cnametest.company.com'<br /><br />    DNSType: 'cname' <br /><br />    DNSValue: 'aws.amazon.com'</pre> | 
| 使用 Infoblox 分支自定义资源创建网络对象 | **返回值：**`infobloxref ` – Infoblox 参考资料`network` – 网络范围（与 `VPCCIDR` 相同）**示例资源：**<pre>VPCCustomResource:<br /><br />  Type: 'Custom::InfobloxAPI'<br /><br />  Properties:<br /><br />    ServiceToken: !Sub  arn:aws:sns:${AWS::Region}:${HubAccountID}:RunInfobloxNextSubnetFunction<br /><br />    VPCCIDR: !Ref VpcCIDR<br /><br />    Type: VPC<br /><br />    NetworkName: My-VPC</pre> | 
| 使用 Infoblox 分支自定义资源检索下一个可用子网 | **返回值：**`infobloxref` – Infoblox 参考资料`network ` – 子网的网络范围**示例资源：**<pre>Subnet1CustomResource:<br /><br />  Type: 'Custom::InfobloxAPI'<br /><br />  DependsOn: VPCCustomResource<br /><br />  Properties:<br /><br />    ServiceToken: !Sub  arn:aws:sns:${AWS::Region}:${HubAccountID}:RunInfobloxNextSubnetFunction<br /><br />    VPCCIDR: !Ref VpcCIDR<br /><br />    Type: Subnet<br /><br />    SubnetPrefix: !Ref SubnetPrefix<br /><br />NetworkName: My-Subnet</pre> | 

## 操作说明
<a name="create-infoblox-objects-using-aws-cloudformation-custom-resources-and-amazon-sns-epics"></a>

### 创建和配置中心账户的 VPC
<a name="create-and-configure-the-hub-accountrsquor-s-vpc"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建与 Infoblox 设备连接的 VPC。 | 登录您的中心账户的 AWS 管理控制台，并按照 AWS Quick Start 中的 [Amazon Web Services Cloud 上的 Amazon VPC 快速入门参考部署](https://aws-quickstart.github.io/quickstart-aws-vpc/)中的步骤创建 VPC。VPC 必须具有与 Infoblox 设备的 HTTPS 连接，我们建议您使用私有子网进行此连接。 | 网络管理员、系统管理员 | 
| （可选）为私有子网创建 VPC 端点。 | VPC 端点为您的私有子网提供与公共服务的连接。需要以下端点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-infoblox-objects-using-aws-cloudformation-custom-resources-and-amazon-sns.html)有关为私有子网创建端点的更多信息，请参阅 [Amazon VPC 文档中的 VPC 端点](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints.html)。 | 网络管理员、系统管理员 | 

### 部署 Infoblox 中心
<a name="deploy-the-infoblox-hub"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 构建 AWS SAM 模板。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-infoblox-objects-using-aws-cloudformation-custom-resources-and-amazon-sns.html) | 开发人员、系统管理员 | 
| 部署 AWS SAM 模板。 | 该`sam deploy`命令获取所需的参数并将其保存到`samconfig.toml`文件中，将 AWS CloudFormation 模板和 Lambda 函数存储在 S3 存储桶中，然后将 AWS CloudFormation 模板部署到您的中心账户。 以下示例代码演示如何部署 AWS SAM 模板：<pre>$ sam deploy --guided<br /><br />Configuring SAM deploy<br />======================<br />        Looking for config file [samconfig.toml] :  Found<br />        Reading default arguments  :  Success<br />        Setting default arguments for 'sam deploy'<br />        =========================================<br />        Stack Name [Infoblox-Hub]:<br />        AWS Region [eu-west-1]:<br />        Parameter InfobloxUsername:<br />        Parameter InfobloxPassword:<br />        Parameter InfobloxIPAddress [xxx.xxx.xx.xxx]:<br />        Parameter AWSOrganisationID [o-xxxxxxxxx]:<br />        Parameter VPCID [vpc-xxxxxxxxx]:<br />        Parameter VPCCIDR [xxx.xxx.xxx.xxx/16]:<br />        Parameter VPCSubnetID1 [subnet-xxx]:<br />        Parameter VPCSubnetID2 [subnet-xxx]:<br />        Parameter VPCSubnetID3 [subnet-xxx]:<br />        Parameter VPCSubnetID4 []: <br />        #Shows you resources changes to be deployed and require a 'Y' to initiate deploy<br />        Confirm changes before deploy [Y/n]: y<br />        #SAM needs permission to be able to create roles to connect to the resources in your template<br />Allow SAM CLI IAM role creation [Y/n]: n<br />Capabilities [['CAPABILITY_NAMED_IAM']]:<br />        Save arguments to configuration file [Y/n]: y<br />        SAM configuration file [samconfig.toml]:<br />        SAM configuration environment [default]: </pre>每次都必须使用 `--guided` 选项，因为 Infoblox 登录凭证未存储在 `samconfig.toml` 文件中。 | 开发人员、系统管理员 | 

## 相关资源
<a name="create-infoblox-objects-using-aws-cloudformation-custom-resources-and-amazon-sns-resources"></a>
+ [开始 WAPIs 使用 Postman](https://blogs.infoblox.com/community/getting-started-with-wapis-using-postman/)（Infoblox 博客）
+ [使用 BYOL 模型为 AWS 预置 vNIOS](https://docs.infoblox.com/display/NAIG/Provisioning+vNIOS+for+AWS+Using+the+BYOL+Model)（Infoblox 文档）
+ [quickstart-aws-vpc](https://github.com/aws-quickstart/quickstart-aws-vpc)（GitHub 存储库）
+ [describe\$1managed\$1prefix\$1lists](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.Client.describe_managed_prefix_lists)（适用于 Python 的 AWS SDK 文档）

## 附件
<a name="attachments-8d609d3f-6f5e-4084-849f-ca191db8055e"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/8d609d3f-6f5e-4084-849f-ca191db8055e/attachments/attachment.zip)

# 使用 Terraform 在上 AWS 面创建分层的多区域 IPAM 架构
<a name="multi-region-ipam-architecture"></a>

*Donny Schreiber，Amazon Web Services*

## Summary
<a name="multi-region-ipam-architecture-summary"></a>

*IP 地址管理（IPAM）*是网络管理的重要组成部分，随着组织不断扩大云基础设施规模，其复杂性也日益增加。若缺乏完善的 IP 地址管理（IPAM），组织将面临 IP 地址冲突、地址空间浪费、问题排查难度大等风险，进而导致系统中断和应用程序停机。此模式演示了如何使用 HashiCorp Terraform 为 AWS 企业环境实施全面的 IPAM 解决方案。[它可以帮助组织创建分层、多区域 IPAM 架构，从而促进组织 AWS 账户 内所有部门的 IP 地址集中管理。AWS](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html#organization-structure)

此模式可帮助您使用复杂的四层池层次结构实施 [Amazon VPC IP 地址管理器](https://docs.aws.amazon.com/vpc/latest/ipam/what-it-is-ipam.html)：顶层池、区域池、业务部门池和环境特定池。此结构在支持规范的 IP 地址治理的同时，允许将 IP 管理权限委派给组织内部相应的团队。该解决方案使用 AWS Resource Access Manager (AWS RAM) 在整个组织中无缝共享 IP 地址管理器池。 AWS RAM 集中和标准化 IPAM 规范，团队可以在所有托管账户中建立这些规范。

此模式可助您实现以下目标：
+ 自动跨 AWS 区域业务部门和环境分配 IP 地址。
+ 通过程序化验证强制实施组织网络策略。
+ 随着业务需求的演变高效扩展网络基础设施。
+ 通过集中管理 IP 地址空间来减少运营开销。
+ 通过自助式 CIDR 范围分配，加快云原生工作负载部署。
+ 通过基于策略的控制和验证，防止地址冲突。

## 先决条件和限制
<a name="multi-region-ipam-architecture-prereqs"></a>

**先决条件**
+ 一个或多个 AWS 账户，作为一个组织在中进行管理 AWS Organizations。
+ 一个网络中心或网络管理账户，将充当 IP 地址管理器委派管理员。
+ AWS Command Line Interface (AWS CLI)，[已安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)并[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。
+ [已安装](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) Terraform 版本 1.5.0 或更高版本。
+ AWS [Terraform 的提供者，已配置。](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)
+ 管理 [IP 地址管理器和](https://docs.aws.amazon.com/vpc/latest/ipam/iam-ipam.html)[虚拟私有云 (VPCs) 的权限，在 AWS Identity and Access Management (](https://docs.aws.amazon.com/vpc/latest/userguide/security-iam.html)IAM) 中配置。[AWS RAM](https://docs.aws.amazon.com/ram/latest/userguide/security-iam.html)

**限制**
+ IP 地址管理器受[服务配额](https://docs.aws.amazon.com/vpc/latest/ipam/quotas-ipam.html)限制。池的默认服务配额为每个范围 50 个。在 6 个区域、2 个业务部门和 4 个环境中运行此部署将创建 67 个池。因此，可能需要增加配额。
+ 分配资源后修改或删除 IP 地址管理器池可能导致依赖性问题。必须先[释放分配](https://docs.aws.amazon.com/vpc/latest/ipam/release-alloc-ipam.html)，然后才能删除池。
+ 在 IP 地址管理器中，[资源监控](https://docs.aws.amazon.com/vpc/latest/ipam/monitor-cidr-compliance-ipam.html)可能存在轻微延迟，无法即时反映资源变更。此延迟约为 20 分钟。
+ IP 地址管理器无法在不同范围自动强制执行 IP 地址唯一性。
+ 自定义标签必须遵循 [AWS 标记最佳实践](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/tagging-best-practices.html)。例如，每个键必须唯一，并且不能以 `aws:` 开头。
+ 将 IP 地址管理器与组织外部的账户集成时，有一些要留意的[注意事项和限制](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam-outside-org-considerations.html)

## 架构
<a name="multi-region-ipam-architecture-architecture"></a>

**目标架构**

*IP 地址管理器配置和池层次结构*

下图显示了目标架构的逻辑构造。*范围*是 IP 地址管理器中最高级别的容器。每个范围代表单个网络的 IP 地址空间。*池*是范围内连续 IP 地址范围（或 CIDR 范围）的集合。通过池，您可以根据路由和安全需求分类管理 IP 地址。此图展示了四个层级的池：顶层池、区域池、业务部门池和环境池。

![\[网络账户中单个 AWS 区域内的一个私有范围和四个层级的池。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/780e344e-37f7-4b70-8d7c-94ec67a29305/images/1e23b2a7-a274-4a19-9097-61d8a31dfbf8.png)


此解决方案建立了 IP 地址管理器池的清晰层次结构：

1. 顶层池涵盖整个组织的 IP 地址空间，例如 `10.176.0.0/12`。

1. 区域池用于特定区域的分配，例如 `10.176.0.0/15` 对应 `us-east-1`。

1. 业务部门池是每个业务部门池中特定域的分配。 AWS 区域例如，`us-east-1` 区域的金融业务部门可能有 `10.176.0.0/16`。

1. 环境池是针对特定用途为不同环境分配的资源。例如，位于 `us-east-1` 区域的金融业务部门可能有用于生产环境的 `10.176.0.0/18`。

此部署拓扑按地理位置分配 IP 地址管理器资源，同时保持集中控制。以下是其特性：
+ IP 地址管理器部署在单个主服务器中 AWS 区域。
+ 其他区域注册为[运营区域](https://docs.aws.amazon.com/vpc/latest/ipam/mod-ipam-region.html)，IP 地址管理器可以在其中管理资源。
+ 每个运营区域都会从顶层池获得一个专用的地址池。
+ 所有运营区域的资源均通过主区域的 IP 地址管理器集中管理。
+ 每个区域池都与所属区域关联一个区域设置属性，旨在帮助您正确分配资源。

*高级 CIDR 范围验证*

此解决方案旨在防止部署无效的配置。当您通过 Terraform 部署池时，将在 Terraform 规划阶段验证以下事项：
+ 验证所有环境 CIDR 范围是否包含在其上级业务部门 CIDR 范围内
+ 验证所有业务部门 CIDR 范围是否包含在其上级区域 CIDR 范围内
+ 验证所有区域 CIDR 范围是否包含在顶层 CIDR 范围内
+ 检查同一层次结构级别中是否有重叠的 CIDR 范围
+ 验证环境与其对应业务部门的映射是否正确

*CIDR 范围分配*

下图显示了开发人员或管理员如何从池级别创建新的 IP 地址 VPCs 和分配 IP 地址的示例。

![\[网络账户中单个 AWS 区域内的一个私有范围和四个层级的池。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/780e344e-37f7-4b70-8d7c-94ec67a29305/images/7c3de2e3-e71b-4fc0-abcd-7e88cfab5c87.png)


下图显示了如下工作流：

1. 通过 AWS 管理控制台 AWS CLI、或通过基础设施即代码 (IaC)，开发人员或管理员请求`AY3`环境池中下一个可用的 CIDR 范围。

1. IP 地址管理器将该池中的下一个可用 CIDR 范围分配给 `AY3-4` VPC。此 CIDR 范围已无法再使用。

**自动化和扩展**

此解决方案专为提升可扩展性而设计，如下所示：
+ **区域扩展** – 通过使用其他区域池条目扩展 Terraform 配置，从而添加新区域。
+ **业务部门增长** – 通过将新业务部门添加至业务部门配置图来支持其发展。
+ **环境灵活性** – 根据组织需求配置不同的环境类型，例如开发或生产。
+ **多账户支持** — 通过 AWS RAM共享组织内所有账户的资源池。
+ **自动 VPC 预调配** – 与 VPC 预调配工作流集成，自动分配 CIDR 范围。

分层结构还允许不同的授权和控制等级，例如：
+ 网络管理员可以管理顶层池和区域池。
+ 业务部门 IT 团队可能已下放对各自池的控制权。
+ 应用程序团队可能使用其指定环境池中的 IP 地址。

**注意**  
您还可以将此解决方案与 [AWS Control Tower Account Factory for Terraform（AFT）](https://docs.aws.amazon.com/controltower/latest/userguide/aft-overview.html)集成。有关更多信息，请参阅此模式[其他信息](#multi-region-ipam-architecture-additional)部分的*与 AFT 集成*。

## 工具
<a name="multi-region-ipam-architecture-tools"></a>

**AWS 服务**
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可帮助您实时监控您的 AWS 资源和运行的应用程序 AWS 的指标。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您 AWS 服务 通过命令行外壳中的命令进行交互。
+ [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)是一项账户管理服务，可帮助您将多个账户整合 AWS 账户 到一个由您创建和集中管理的组织中。
+ [AWS Resource Access Manager (AWS RAM)](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html) 可帮助您安全地共享资源， AWS 账户 从而减少运营开销并提供可见性和可审计性。
+ [Amazon Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。该虚拟网络类似于您在数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。[IP 地址管理器](https://docs.aws.amazon.com/vpc/latest/ipam/what-it-is-ipam.html)是 Amazon VPC 的一项功能，它可以帮助您规划、跟踪和监控 AWS 工作负载的 IP 地址。

**其他工具**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款基础设施即代码（IaC）工具，可帮助您使用代码来预调配和管理云基础设施和资源。

**代码存储库**

此模式的代码可在存储库上的 “[分层 IPAM 的 Terraform 实现示例](https://github.com/aws-samples/sample-amazon-vpc-ipam-terraform)” 中找到。 AWS** GitHub**存储库结构包括：
+ **根模块** – 部署编排和输入变量。
+ **IPAM 模块** – 此模式中描述的架构的核心实现。
+ **标签模块** – 所有资源的标准化标记。

## 最佳实践
<a name="multi-region-ipam-architecture-best-practices"></a>

考虑下面有关网络规划的最佳实践：
+ **先计划** – 在部署之前，先彻底规划 IP 地址空间。有关更多信息，请参阅[计划 IP 地址预调配](https://docs.aws.amazon.com/vpc/latest/ipam/planning-ipam.html)。
+ **避免重叠的 CIDR 范围** – 确保每个层级的 CIDR 范围不重叠。
+ **预留缓冲空间** – 始终分配比当前需求更大的 CIDR 范围，以适应未来增长。
+ **记录 IP 地址分配** – 保留您的 IP 地址分配策略文档。

考虑采用下面的部署最佳实践：
+ **从非生产环境开始** – 先在非生产环境中部署。
+ **使用 Terraform 状态管理** – 实施远程状态存储和锁定。有关更多信息，请参阅 Terraform 文档中的[状态存储和锁定](https://developer.hashicorp.com/terraform/language/state/backends)。
+ **实施版本控制** – 对所有 Terraform 代码进行版本控制。
+ **实施 CI/CD 集成**-使用持续集成和持续交付 (CI/CD) 管道进行可重复部署。

考虑采用下面的操作最佳实践：
+ **启用自动导入** – 将 IP 地址管理器池配置为自动发现和导入现有资源。按照[编辑 IPAM 池](https://docs.aws.amazon.com/vpc/latest/ipam/mod-pool-ipam.html)中的说明打开自动导入。
+ **监控 IP 地址利用率** – 为 IP 地址利用率阈值设置警报。有关更多信息，请参阅使用 A [mazon 监控 IPAM](https://docs.aws.amazon.com/vpc/latest/ipam/cloudwatch-ipam.html)。 CloudWatch
+ **定期审计** – 定期审计 IP 地址的使用情况及合规性。有关更多信息，请参阅[在 IPAM 中跟踪 IP 地址使用情况](https://docs.aws.amazon.com/vpc/latest/ipam/tracking-ip-addresses-ipam.html)。
+ **清理未使用的分配** – 在资源停用时释放 IP 地址分配。有关更多信息，请参阅[ CIDRs 从池中取消置备](https://docs.aws.amazon.com/vpc/latest/ipam/depro-pool-cidr-ipam.html)。

考虑采用下面的安全最佳实践：
+ **实施最低权限** – 使用具备最低所需权限的 IAM 角色。有关更多信息，请参阅 [IAM 中的安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)和 [IPAM 中的身份与访问管理](https://docs.aws.amazon.com/vpc/latest/ipam/iam-ipam.html)。
+ **使用服务控制策略**-实施服务控制策略 (SCPs) 以强制在组织中使用 IP 地址管理器。有关更多信息，请参阅使用[强制使用 IPAM 创建 VPC](https://docs.aws.amazon.com/vpc/latest/ipam/scp-ipam.html)。 SCPs
+ **控制资源共享** — 谨慎管理 IP 地址管理器资源共享的范围 AWS RAM。有关更多信息，请参阅[使用共享 IPAM 池](https://docs.aws.amazon.com/vpc/latest/ipam/share-pool-ipam.html)。 AWS RAM
+ **强制标记** – 对与 IP 地址管理器相关的所有资源实施强制性标记。有关更多信息，请参阅[其他信息](#multi-region-ipam-architecture-additional)部分中的*标记策略*。

## 操作说明
<a name="multi-region-ipam-architecture-epics"></a>

### 为 IP 地址管理器设置委派管理员账户
<a name="set-up-a-delegated-administrator-account-for-ip-address-manager"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启用 AWS Organizations 功能。 | 确保 AWS Organizations 已启用所有功能。有关说明，请参阅 AWS Organizations 文档 AWS Organizations中的[为组织启用所有功能](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html)。 | AWS 管理员 | 
| 在中启用资源共享 AWS RAM。 | 使用输入以下命令为您的组织启用 AWS RAM 资源共享： AWS CLI<pre>aws ram enable-sharing-with-aws-organization</pre>有关更多信息，请参阅 AWS RAM 文档[AWS Organizations中的启用资源共享](https://docs.aws.amazon.com/ram/latest/userguide/getting-started-sharing.html#getting-started-sharing-orgs)。 | AWS 管理员 | 
| 指定 IP 地址管理器的管理员。 | 在组织的管理帐户中 AWS CLI，使用输入以下命令，其中`123456789012`是将管理 IP 地址管理器的帐户的 ID：<pre>aws ec2 enable-ipam-organization-admin-account \<br />    --delegated-admin-account-id 123456789012</pre>通常，网络或网络中心账户将充当 IP 地址管理器的委派管理员。有关更多信息，请参阅 IP 地址管理器文档[中的将 IPAM 与 AWS 组织中的账户](https://docs.aws.amazon.com/vpc/latest/ipam/enable-integ-ipam.html)集成。 | AWS 管理员 | 

### 部署基础设施
<a name="deploy-the-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 定义网络架构。 | 定义并记录您的网络架构，包括区域、业务部门和环境的 CIDR 范围。有关更多信息，请参阅 IP 地址管理器文档中的[计划 IP 地址预调配](https://docs.aws.amazon.com/vpc/latest/ipam/planning-ipam.html)。 | 网络工程师 | 
| 克隆存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-region-ipam-architecture.html) | DevOps 工程师 | 
| 配置变量。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-region-ipam-architecture.html) | 网络工程师，Terraform | 
| 部署 IP 地址管理器资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-region-ipam-architecture.html) | Terraform | 
| 验证部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-region-ipam-architecture.html) | AWS 总负责人，网络工程师 | 

### 创建 VPCs 和设置监控
<a name="create-vpcs-and-set-up-monitoring"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 VPC。 | 按照 Amazon VPC 文档[创建 VPC](https://docs.aws.amazon.com/vpc/latest/userguide/create-vpc.html) 中的步骤操作。在选择 VPC 的 CIDR 范围时，请从您的区域、业务单元和环境资源池中分配下一个可用范围。 | AWS 总负责人、网络管理员、网络工程师 | 
| 验证 CIDR 范围分配。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-region-ipam-architecture.html) | AWS 总负责人、网络管理员、网络工程师 | 
| 监控 IP 地址管理器。 | 配置与 IP 地址管理器资源分配相关的监控和警报。有关更多信息和说明，请参阅 IP 地址管理[器文档中的使用 Amazon 监控 IPAM CloudWatch](https://docs.aws.amazon.com/vpc/latest/ipam/cloudwatch-ipam.html) [和按资源监控 CIDR 使用情况](https://docs.aws.amazon.com/vpc/latest/ipam/monitor-cidr-compliance-ipam.html)。 | 常规 AWS | 
| 强制使用 IP 地址管理器。 | 在中创建服务控制策略 (SCP) AWS Organizations ，要求组织中的成员在创建 VPC 时使用 IP 地址管理器。有关说明，请参阅 IP 地址管理器文档 SCPs中的[强制使用 IPAM 创建 VPC](https://docs.aws.amazon.com/vpc/latest/ipam/scp-ipam.html)。 | 常规 AWS、AWS 管理员 | 

## 问题排查
<a name="multi-region-ipam-architecture-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| Terraform 因找不到 IP 地址管理器资源而失败 | 确保 IP 地址管理器管理员帐户已正确授权，并且您的 AWS 提供商已通过该帐户的身份验证。 | 
| CIDR 范围分配失败 | 检查请求的 CIDR 范围是否在 IP 地址管理器池的可用范围内，并且未与现有分配重叠。 | 
| AWS RAM 共享问题 | 确认您的 AWS 组织已启用资源共享。确认共享中使用了正确的委托人，即组织 Amazon 资源名称 (ARN)。 AWS RAM  | 
| 池层次结构验证错误 | 确保子池 CIDR 范围正确包含在其父池 CIDR 范围内，并且未与兄弟池重叠。 | 
| 超过 IP 地址管理器配额限制 | 请求增加 IP 地址管理器池的配额。有关更多信息，请参阅《服务配额用户指南》**中的 [Requesting a quota increase](https://docs.aws.amazon.com/servicequotas/latest/userguide/request-quota-increase.html)。 | 

## 相关资源
<a name="multi-region-ipam-architecture-resources"></a>

**AWS 服务 文档**
+ [Amazon VPC IP 地址管理器文档](https://docs.aws.amazon.com/vpc/latest/ipam/what-it-is-ipam.html)
+ [AWS Resource Access Manager 文档](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html)
+ [AWS Organizations 文档](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)

**AWS 博客文章**
+ [使用 Amazon VPC IP 地址管理器管理跨 VPCs 区域的 IP 池](https://aws.amazon.com/blogs/networking-and-content-delivery/managing-ip-pools-across-vpcs-and-regions-using-amazon-vpc-ip-address-manager/)
+ [使用 Amazon VPC IP 地址管理器规模化管理和审计网络地址](https://aws.amazon.com/blogs/aws/network-address-management-and-auditing-at-scale-with-amazon-vpc-ip-address-manager/)

**视频和教程**
+ [AWS re: Invent 2022：亚马逊 VPC 设计和 IPAM 的最佳实践 (0) NET31](https://www.youtube.com/watch?v=XrEHsy_8RYs)
+ [AWS re: Invent 2022：高级 VPC 设计和新功能 (01) NET4](https://www.youtube.com/watch?v=tbXTVpwx87o)

## 附加信息
<a name="multi-region-ipam-architecture-additional"></a>

**与 AFT 集成**

您可以将此解决方案与 AWS Control Tower Account Factory for Terraform (AFT) 集成，以确保新配置的账户自动接收正确的网络配置。通过在您的网络中心帐户中部署此 IPAM 解决方案，通过 AFT 创建的新帐户可以在创建时引用共享的 IP 地址管理器池。 VPCs

以下代码示例演示了使用 P AWS Systems Manager arameter Store 在账户自定义中集成 AFT：

```
# Get the IP Address Manager pool ID from Parameter Store
data "aws_ssm_parameter" "dev_ipam_pool_id" {
  name = "/org/network/ipam/finance/dev/pool-id"
}

# Create a VPC using the IP Address Manager pool
resource "aws_vpc" "this" {
  ipv4_ipam_pool_id   = data.aws_ssm_parameter.dev_ipam_pool_id.value
  ipv4_netmask_length = 24
  
  tags = {
    Name = "aft-account-vpc"
  }
}
```

**标记策略**

此解决方案实施了全面的标记策略，可促进资源管理。以下代码示例演示了如何使用此策略：

```
# Example tag configuration
module "tags" {
  source = "./modules/tags"
  
  # Required tags
  product_name  = "enterprise-network"
  feature_name  = "ipam"
  org_id        = "finance"
  business_unit = "network-operations"
  owner         = "network-team"
  environment   = "prod"
  repo          = "https://github.com/myorg/ipam-terraform"
  branch        = "main"
  cost_center   = "123456"
  dr_tier       = "tier1"
  
  # Optional tags
  optional_tags = {
    "project"    = "network-modernization"
    "stack_role" = "infrastructure"
  }
}
```

这些标签会自动应用于所有 IP 地址管理器资源。这有助于实现一致的治理、成本分摊和资源管理。

# 自定义 Amazon CloudWatch 提醒 AWS Network Firewall
<a name="customize-amazon-cloudwatch-alerts-for-aws-network-firewall"></a>

*Jason Owens，Amazon Web Services*

## Summary
<a name="customize-amazon-cloudwatch-alerts-for-aws-network-firewall-summary"></a>

该模式可帮助您自定义由生成的Amazon CloudWatch 提醒 AWS Network Firewall。您可以使用预定义的规则或创建自定义规则来确定警报的消息、元数据和严重性。然后，您可以根据这些提醒采取行动，或者由其他亚马逊服务（例如亚马逊）自动回复 EventBridge。

在此模式中，您将生成与 Suricata 兼容的防火墙规则。[Suricata](https://suricata.io/) 是一个开源威胁检测引擎。您首先创建简单的规则，然后对其进行测试以确认 CloudWatch 警报已生成并记录在案。成功测试规则后，您可以修改它们以定义自定义消息、元数据和严重性，然后再次测试以确认更新。

## 先决条件和限制
<a name="customize-amazon-cloudwatch-alerts-for-aws-network-firewall-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ AWS Command Line Interface (AWS CLI) 已在你的 Linux、macOS 或 Windows 工作站上安装和配置。有关更多信息，请参阅[安装或更新 AWS CLI的最新版本](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。
+ AWS Network Firewall 已安装并配置为使用 CloudWatch 日志。有关更多信息，请参阅[记录来自的网络流量 AWS Network Firewall](https://docs.aws.amazon.com/network-firewall/latest/developerguide/firewall-logging.html)。
+ 位于受网络防火墙保护的虚拟私有云 (VPC EC2) 私有子网中的亚马逊弹性计算云 (Amazon) 实例。

**产品版本**
+ 对于的版本 1 AWS CLI，请使用 1.18.180 或更高版本。对于的版本 2 AWS CLI，请使用 2.1.2 或更高版本。
+ Suricata 版本 5.0.2 中的 classification.config 文件。有关此配置文件的副本，请参阅[其他信息](#customize-amazon-cloudwatch-alerts-for-aws-network-firewall-additional)部分。

## 架构
<a name="customize-amazon-cloudwatch-alerts-for-aws-network-firewall-architecture"></a>

![\[EC2 实例请求会在 Network Firewall 中生成警报，网络防火墙会将警报转发到 CloudWatch\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/da6087a9-e942-4cfe-85e3-3b08de6f3ba5/images/778d85cd-bc87-4ed0-a161-d35eb5daa694.png)


架构图显示了以下工作流程：

1. 私有子网中的 Amazon EC2 实例使用 c [url](https://curl.se/) 或 [W](https://www.gnu.org/software/wget/) get 发出请求。

1. Network Firewall 处理流量并生成警报。

1. Network Firewall 将记录的警报发送到 CloudWatch 日志。

## 工具
<a name="customize-amazon-cloudwatch-alerts-for-aws-network-firewall-tools"></a>

**AWS 服务**
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可帮助您实时监控您的 AWS 资源和运行的应用程序 AWS 的指标。
+ [Amazon CloudWatch Lo](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) gs 可帮助您集中所有系统和应用程序的日志， AWS 服务 这样您就可以监控它们并安全地将其存档。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您 AWS 服务 通过命令行外壳中的命令进行交互。
+ [AWS Network Firewall](https://docs.aws.amazon.com/network-firewall/latest/developerguide/what-is-aws-network-firewall.html)是针对虚拟私有云 (VPCs) 中的状态托管网络防火墙以及入侵检测和防御服务 ()。 AWS 云 

**其他工具**
+ [curl](https://curl.se/) 是一个开源命令行工具和库。
+ [GNU Wget](https://www.gnu.org/software/wget/) 是一个免费的命令行工具。

## 操作说明
<a name="customize-amazon-cloudwatch-alerts-for-aws-network-firewall-epics"></a>

### 创建防火墙规则和规则组
<a name="create-the-firewall-rules-and-rule-group"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建规则。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/customize-amazon-cloudwatch-alerts-for-aws-network-firewall.html) | AWS 系统管理员、网络管理员 | 
| 创建规则组。 | 在中 AWS CLI，输入以下命令。这将创建规则组。<pre>❯ aws network-firewall create-rule-group \<br />        --rule-group-name custom --type STATEFUL \<br />        --capacity 10 --rules file://custom.rules \<br />        --tags Key=environment,Value=development</pre>下面是一个示例输出。记下 `RuleGroupArn`，在后面的步骤中需要用到它。<pre>{<br />    "UpdateToken": "4f998d72-973c-490a-bed2-fc3460547e23",<br />    "RuleGroupResponse": {<br />        "RuleGroupArn": "arn:aws:network-firewall:us-east-2:1234567890:stateful-rulegroup/custom",<br />        "RuleGroupName": "custom",<br />        "RuleGroupId": "238a8259-9eaf-48bb-90af-5e690cf8c48b",<br />        "Type": "STATEFUL",<br />        "Capacity": 10,<br />        "RuleGroupStatus": "ACTIVE",<br />        "Tags": [<br />            {<br />                "Key": "environment",<br />                "Value": "development"<br />            }<br />        ]<br />    }</pre> | AWS 系统管理员 | 

### 更新防火墙策略
<a name="update-the-firewall-policy"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 获取防火墙策略的 ARN。 | 在中 AWS CLI，输入以下命令。这将返回防火墙策略的 Amazon 资源名称（ARN）。记录 ARN 以供稍后在此模式中使用。<pre>❯ aws network-firewall describe-firewall \<br />    --firewall-name aws-network-firewall-anfw \<br />    --query 'Firewall.FirewallPolicyArn'</pre>以下是此命令返回的示例 ARN。<pre>"arn:aws:network-firewall:us-east-2:1234567890:firewall-policy/firewall-policy-anfw"</pre> | AWS 系统管理员 | 
| 更新防火墙策略。 | 在文本编辑器中，复制并粘贴以下代码。将 `<RuleGroupArn>` 替换为在上一个长篇故事中记录的值。将该文件保存为 `firewall-policy-anfw.json`。<pre>{<br />    "StatelessDefaultActions": [<br />        "aws:forward_to_sfe"<br />    ],<br />    "StatelessFragmentDefaultActions": [<br />        "aws:forward_to_sfe"<br />    ],<br />    "StatefulRuleGroupReferences": [<br />        {<br />            "ResourceArn": "<RuleGroupArn>"<br />        }<br />    ]<br />}</pre>在 AWS CLI中，输入以下命令。此命令需要[更新令牌](https://docs.aws.amazon.com/cli/latest/reference/network-firewall/update-firewall-policy.html)才能添加新规则。该令牌用于确认自您上次检索策略以来该策略未发生更改。<pre>UPDATETOKEN=(`aws network-firewall describe-firewall-policy \<br />              --firewall-policy-name firewall-policy-anfw \<br />              --output text --query UpdateToken`)<br /> <br /> aws network-firewall update-firewall-policy \<br /> --update-token $UPDATETOKEN \<br /> --firewall-policy-name firewall-policy-anfw \<br /> --firewall-policy file://firewall-policy-anfw.json</pre> | AWS 系统管理员 | 
| 确认策略更新。 | （可选）如果要确认已添加规则并查看策略格式，请在 AWS CLI中输入以下命令。<pre>❯ aws network-firewall describe-firewall-policy \<br />  --firewall-policy-name firewall-policy-anfw \<br />  --query FirewallPolicy</pre>下面是一个示例输出。<pre>{<br />    "StatelessDefaultActions": [<br />        "aws:forward_to_sfe"<br />    ],<br />    "StatelessFragmentDefaultActions": [<br />        "aws:forward_to_sfe"<br />    ],<br />    "StatefulRuleGroupReferences": [<br />        {<br />            "ResourceArn": "arn:aws:network-firewall:us-east-2:1234567890:stateful-rulegroup/custom"<br />        }<br />    ]<br />}</pre> | AWS 系统管理员 | 

### 测试警报功能
<a name="test-alert-functionality"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 生成用于测试的警报。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/customize-amazon-cloudwatch-alerts-for-aws-network-firewall.html) | AWS 系统管理员 | 
| 验证警报是否已记录。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/customize-amazon-cloudwatch-alerts-for-aws-network-firewall.html) | AWS 系统管理员 | 

### 更新防火墙规则和规则组
<a name="update-the-firewall-rules-and-rule-group"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新防火墙规则。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/customize-amazon-cloudwatch-alerts-for-aws-network-firewall.html) | AWS 系统管理员 | 
| 更新规则组。 | 在中 AWS CLI，运行以下命令。使用防火墙策略的 ARN。这些命令获取更新令牌，并使用规则更改更新规则组。<pre>❯ UPDATETOKEN=(`aws network-firewall \<br />                describe-rule-group \<br />--rule-group-arn arn:aws:network-firewall:us-east-2:123457890:stateful-rulegroup/custom \<br />--output text --query UpdateToken`)</pre><pre> ❯ aws network-firewall update-rule-group \<br />  --rule-group-arn arn:aws:network-firewall:us-east-2:1234567890:stateful-rulegroup/custom \<br />--rules file://custom.rules \<br />--update-token $UPDATETOKEN</pre>下面是一个示例输出。<pre>{<br />    "UpdateToken": "7536939f-6a1d-414c-96d1-bb28110996ed",<br />    "RuleGroupResponse": {<br />        "RuleGroupArn": "arn:aws:network-firewall:us-east-2:1234567890:stateful-rulegroup/custom",<br />        "RuleGroupName": "custom",<br />        "RuleGroupId": "238a8259-9eaf-48bb-90af-5e690cf8c48b",<br />        "Type": "STATEFUL",<br />        "Capacity": 10,<br />        "RuleGroupStatus": "ACTIVE",<br />        "Tags": [<br />            {<br />                "Key": "environment",<br />                "Value": "development"<br />            }<br />        ]<br />    }<br />}</pre> | AWS 系统管理员 | 

### 测试更新的警报功能
<a name="test-the-updated-alert-functionality"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 生成用于测试的警报。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/customize-amazon-cloudwatch-alerts-for-aws-network-firewall.html) | AWS 系统管理员 | 
| 验证警报是否已更改。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/customize-amazon-cloudwatch-alerts-for-aws-network-firewall.html) | AWS 系统管理员 | 

## 相关资源
<a name="customize-amazon-cloudwatch-alerts-for-aws-network-firewall-resources"></a>

**参考**
+ [从 AWS Network Firewall Slack 频道发送提醒](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/send-alerts-from-aws-network-firewall-to-a-slack-channel.html)（AWS 规范性指导）
+ [AWS 使用 Suricata 扩展威胁防御能力](https://aws.amazon.com/blogs/opensource/scaling-threat-prevention-on-aws-with-suricata/)（AWS 博客文章）
+  AWS Network Firewall（AWS 博客文章）[的部署模型](https://aws.amazon.com/blogs/networking-and-content-delivery/deployment-models-for-aws-network-firewall/)
+ [Suricata 元密钥](https://suricata.readthedocs.io/en/suricata-6.0.1/rules/meta.html)（Suricata 文档）

**教程和视频**
+ [AWS Network Firewall 工作坊](https://networkfirewall.workshop.aws/)

## 附加信息
<a name="customize-amazon-cloudwatch-alerts-for-aws-network-firewall-additional"></a>

以下是 Suricata 5.0.2 中的分类配置文件。创建防火墙规则时将使用这些分类。

```
# config classification:shortname,short description,priority
 
config classification: not-suspicious,Not Suspicious Traffic,3
config classification: unknown,Unknown Traffic,3
config classification: bad-unknown,Potentially Bad Traffic, 2
config classification: attempted-recon,Attempted Information Leak,2
config classification: successful-recon-limited,Information Leak,2
config classification: successful-recon-largescale,Large Scale Information Leak,2
config classification: attempted-dos,Attempted Denial of Service,2
config classification: successful-dos,Denial of Service,2
config classification: attempted-user,Attempted User Privilege Gain,1
config classification: unsuccessful-user,Unsuccessful User Privilege Gain,1
config classification: successful-user,Successful User Privilege Gain,1
config classification: attempted-admin,Attempted Administrator Privilege Gain,1
config classification: successful-admin,Successful Administrator Privilege Gain,1
 
# NEW CLASSIFICATIONS
config classification: rpc-portmap-decode,Decode of an RPC Query,2
config classification: shellcode-detect,Executable code was detected,1
config classification: string-detect,A suspicious string was detected,3
config classification: suspicious-filename-detect,A suspicious filename was detected,2
config classification: suspicious-login,An attempted login using a suspicious username was detected,2
config classification: system-call-detect,A system call was detected,2
config classification: tcp-connection,A TCP connection was detected,4
config classification: trojan-activity,A Network Trojan was detected, 1
config classification: unusual-client-port-connection,A client was using an unusual port,2
config classification: network-scan,Detection of a Network Scan,3
config classification: denial-of-service,Detection of a Denial of Service Attack,2
config classification: non-standard-protocol,Detection of a non-standard protocol or event,2
config classification: protocol-command-decode,Generic Protocol Command Decode,3
config classification: web-application-activity,access to a potentially vulnerable web application,2
config classification: web-application-attack,Web Application Attack,1
config classification: misc-activity,Misc activity,3
config classification: misc-attack,Misc Attack,2
config classification: icmp-event,Generic ICMP event,3
config classification: inappropriate-content,Inappropriate Content was Detected,1
config classification: policy-violation,Potential Corporate Privacy Violation,1
config classification: default-login-attempt,Attempt to login by a default username and password,2
 
# Update
config classification: targeted-activity,Targeted Malicious Activity was Detected,1
config classification: exploit-kit,Exploit Kit Activity Detected,1
config classification: external-ip-check,Device Retrieving External IP Address Detected,2
config classification: domain-c2,Domain Observed Used for C2 Detected,1
config classification: pup-activity,Possibly Unwanted Program Detected,2
config classification: credential-theft,Successful Credential Theft Detected,1
config classification: social-engineering,Possible Social Engineering Attempted,2
config classification: coin-mining,Crypto Currency Mining Activity Detected,2
config classification: command-and-control,Malware Command and Control Activity Detected,1
```

# 使用 Terraform 在 AWS Wavelength 区域中部署资源
<a name="deploy-resources-wavelength-zone-using-terraform"></a>

*Zahoor Chaudhrey 和 Luca Iannario，Amazon Web Services*

## Summary
<a name="deploy-resources-wavelength-zone-using-terraform-summary"></a>

[AWS Wavelength](https://docs.aws.amazon.com/wavelength/latest/developerguide/what-is-wavelength.html) 可帮助您构建专为多接入边缘计算（MEC）应用程序优化的基础设施。W@@ *avelength Zones* 是在通信服务提供商 (CSP) 的 5G 网络中嵌入 AWS 计算和存储服务的 AWS 基础设施部署。来自 5G 设备的应用程序流量无需离开电信网络即可到达在 Wavelength Zones 中运行的应用程序服务器。以下内容有助于通过 Wavelength 实现网络连接：
+ **虚拟私有云 (VPCs)** — VPCs AWS 账户 可以扩展到跨多个可用区，包括 Wavelength 区域。亚马逊弹性计算云 (Amazon EC2) 实例和相关服务作为您的区域 VPC 的一部分出现。 VPCs 在[亚马逊 Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)中创建和管理。
+ **运营商网关** — 运营商网关支持从 Wavelength 区域的子网连接到 CSP 网络、互联网或 AWS 区域 通过 CSP 的网络。运营商网关有两个作用。它允许来自特定位置的 CSP 网络的入站流量，并允许将出站流量发送到电信网络和互联网。

此模式及其关联的 Terraform 代码可帮助您在波长区域中启动资源，例如亚马逊 EC2 实例、亚马逊弹性区块存储 (Amazon EBS) Block Store 卷 VPCs、子网和运营商网关。

## 先决条件和限制
<a name="deploy-resources-wavelength-zone-using-terraform-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 一个集成式开发环境（IDE）
+ [选择加入](https://docs.aws.amazon.com/wavelength/latest/developerguide/get-started-wavelength.html#enable-zone-group)目标 Wavelength Zone
+ AWS Command Line Interface (AWS CLI)，[已安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)并[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ Terraform 版本 1.8.4 或更高版本，[已安装](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli)（Terraform 文档）
+ Terraform P AWS rovider 版本 5.32.1 或更高版本，[已配置](https://hashicorp.github.io/terraform-provider-aws/)（Terraform 文档）
+ Git，[已安装](https://github.com/git-guides/install-git) (GitHub)
+ 创建亚马逊 VPC、Wavelength 和亚马逊资源的@@ [权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html) EC2 

**限制**

并非所有区域都 AWS 区域 支持 Wavelength Zones。有关更多信息，请参阅 Wavelength 文档中的[可用 Wavelength Zones](https://docs.aws.amazon.com/wavelength/latest/developerguide/available-wavelength-zones.html)。

## 架构
<a name="deploy-resources-wavelength-zone-using-terraform-architecture"></a>

下图显示了如何在 Wavelength 区域中创建子网和 AWS 资源。 VPCs 在 Wavelength 区域中包含子网的可以连接到运营商网关。运营商网关允许您连接到以下资源：
+ 电信运营商网络上的 4G/LTE 和 5G 设备。
+ 针对精选 Wavelength Zone 合作伙伴的固定无线接入。有关更多信息，请参阅[多路访问 AWS Wavelength](https://docs.aws.amazon.com/wavelength/latest/developerguide/multi-access.html)。
+ 公有互联网资源的出站流量。

![\[运营商网关将 Wavelength Zone 中的 AWS 资源连接到 CSP 网络。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/8c507de1-208c-4563-bb58-52388ab2fa6d/images/a4cc0699-0cbc-4f15-ab14-3ae569ced7f4.png)


## 工具
<a name="deploy-resources-wavelength-zone-using-terraform-tools"></a>

**AWS 服务**
+ [Amazon Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。该虚拟网络类似于您在数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。
+ [AWS Wavelength](https://docs.aws.amazon.com/wavelength/latest/developerguide/what-is-wavelength.html)将 AWS 云 基础设施扩展到电信提供商的 5G 网络。这可以帮助您为移动设备和最终用户构建具有超低延迟的应用程序。

**其他工具**
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。

**代码存储库**

此模式的代码可在[使用 Terraform GitHub 创建 AWS Wavelength 基础架构存储库](https://github.com/aws-samples/terraform-wavelength-infrastructure)中找到。Terraform 代码部署了以下基础设施和资源：
+ 一个 VPC
+ Wavelength Zone
+ Wavelength Zone 中的公有子网
+ Wavelength Zone 中的运营商网关
+ Wavelength 区域中的亚马逊 EC2 实例

## 最佳实践
<a name="deploy-resources-wavelength-zone-using-terraform-best-practices"></a>
+ 部署前，请确认您使用的是最新版本的 Terraform 和 AWS CLI。
+ 使用持续集成和持续交付（CI/CD）管道部署 IaC。有关更多信息，请参阅博客上的 C [AWS I/CD Pipeline 中管理 Terraform 状态文件的最佳实践](https://aws.amazon.com/blogs/devops/best-practices-for-managing-terraform-state-files-in-aws-ci-cd-pipeline/)。 AWS 

## 操作说明
<a name="deploy-resources-wavelength-zone-using-terraform-epics"></a>

### 预调配基础设施
<a name="provision-the-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 输入以下命令，将 “[使用 Terraform 创建 AWS Wavelength 基础架构](https://github.com/aws-samples/terraform-wavelength-infrastructure)” 存储库克隆到您的环境中。`git clone git@github.com:aws-samples/terraform-wavelength-infrastructure.git` | DevOps 工程师 | 
| 更新变量。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-resources-wavelength-zone-using-terraform.html) | DevOps 工程师，Terraform | 
| 初始化配置。 | 输入以下命令，以初始化工作目录。<pre>terraform init</pre> | DevOps 工程师，Terraform | 
| 预览 Terraform 计划。 | 输入以下命令，将目标状态与 AWS 环境的当前状态进行比较。此命令会生成将要配置的资源的预览。<pre>terraform plan</pre> | DevOps 工程师，Terraform | 
| 验证并部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-resources-wavelength-zone-using-terraform.html) | DevOps 工程师，Terraform | 

### 验证并清理
<a name="validate-and-clean-up"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证基础设施部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-resources-wavelength-zone-using-terraform.html) | AWS DevOps， DevOps 工程师 | 
| （可选）清理 基础架构。 | 如果您需要删除 Terraform 预调配的所有资源，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-resources-wavelength-zone-using-terraform.html) | DevOps 工程师，Terraform | 

## 问题排查
<a name="deploy-resources-wavelength-zone-using-terraform-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 与中的 Amazon EC2 实例的连接 AWS 区域。 | 请参阅[排查 Linux 实例的连接问题](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html)或[排查 Windows 实例的连接问题](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/troubleshooting-windows-instances.html)。 | 
| 连接 Wavelength 区域中的亚马逊 EC2 实例。 | 参见[排除我在 Wavelength 区域启动的 EC2 实例的 SSH 或 RDP 连接](https://repost.aws/knowledge-center/ec2-wavelength-zone-connection-errors)问题。 | 
| Wavelength Zone 中的容量。 | 请参阅 [Wavelength Zone 的配额和注意事项](https://docs.aws.amazon.com/wavelength/latest/developerguide/wavelength-quotas.html)。 | 
| 从运营商网络到 AWS 区域的移动或运营商连接。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-resources-wavelength-zone-using-terraform.html) | 

## 相关资源
<a name="deploy-resources-wavelength-zone-using-terraform-resources"></a>
+ [什么是 AWS Wavelength？](https://docs.aws.amazon.com/wavelength/latest/developerguide/what-is-wavelength.html)
+ [如何 AWS Wavelength 运作](https://docs.aws.amazon.com/wavelength/latest/developerguide/how-wavelengths-work.html)
+ [韧性在 AWS Wavelength](https://docs.aws.amazon.com/wavelength/latest/developerguide/disaster-recovery-resiliency.html)

# 将 DNS 记录批量迁移至 Amazon Route 53 私有托管区
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone"></a>

*Ram Kandaswamy，Amazon Web Services*

## Summary
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-summary"></a>

网络工程师和云管理员需要一种高效且简单的方法将域名系统（DNS）记录添加到 Amazon Route 53 中的私有托管区。使用手动方法将 Microsoft Excel 工作表中的条目复制到 Route 53 控制台中的适当位置非常繁琐且容易出错。此模式描述了一种自动化方法，可减少添加多个记录所需时间和精力。它还提供了一组可重复的步骤来创建多个托管区域。

这种模式使用 Amazon Simple Storage Service（Amazon S3）存储记录。为了有效地处理数据，该模式使用 JSON 格式，因为它简单且能够支持 Python 字典（`dict` 数据类型）。

**注意**  
如果可以从系统生成区域文件，请考虑改用 [Route 53 导入功能](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating-import.html)。

## 先决条件和限制
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-prereqs"></a>

**先决条件**
+ 包含私有托管区记录的 Excel 工作表
+ 熟悉不同类型的 DNS 记录，例如 A 记录、域名授权指针 (NAPTR) 记录和 SRV 记录（请参阅[支持的 DNS 记录类型](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/ResourceRecordTypes.html)）
+ 熟悉 Python 语言及其库

**限制**
+ 该模式并未广泛覆盖所有用例场景。例如，[change\$1resource\$1record\$1sets](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/route53.html#Route53.Client.change_resource_record_sets) 调用并未使用 API 的所有可用属性。
+ 在 Excel 工作表中，假定每行中的值是唯一的。每个完全限定域名 (FQDN) 的多个值应出现在同一行。如果情况并非如此，您应该修改此模式中提供的代码以执行必要的串联。
+ 该模式使用适用于 Python 的 Amazon SDK (Boto3) 直接调用 Route 53 服务。您可以增强代码以使用`create_stack`和`update_stack`命令的 AWS CloudFormation 封装器，并使用 JSON 值填充模板资源。

## 架构
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-architecture"></a>

**技术堆栈**
+ Route 53 私有托管区，用于路由流量
+ Amazon S3，用于存储输出 JSON 文件 

![\[将 DNS 记录批量迁移至 Amazon Route 53 私有托管区的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a81c29ea-f0c5-4d4a-ba87-93111a0f1ee9/images/2ada844b-4147-4f9f-8883-d22605aa42d8.png)


工作流由以下步骤组成，如上图所示，并在*操作说明*部分中进行了讨论：

1. 将包含记录集信息的 Excel 工作表上传至 S3 存储桶。

1. 创建并运行 Python 脚本，将 Excel 数据转换为 JSON 格式。

1. 从 S3 存储桶读取记录并清理数据。

1. 在您的私有托管区中创建记录集。

## 工具
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-tools"></a>
+ [Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) — Amazon Route 53 是高度可用且可扩展的 DNS 网络服务，用于处理域注册、DNS 路由和运行状况检查。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一项对象存储服务。您可以通过 Amazon S3 随时在 Web 上的任何位置存储和检索的任意大小的数据。

## 操作说明
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-epics"></a>

### 为自动化操作准备数据
<a name="prepare-data-for-automation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个 Excel 文件作为记录。 | 使用从当前系统导出的记录创建一个 Excel 工作表，其中包含记录所需列，例如完全限定域名 (FQDN)、记录类型、生存时间 (TTL) 和值。对于 NAPTR 和 SRV 记录，该值是多个属性的组合，因此请使用 Excel `concat` 方法来组合这些属性。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone.html) | 数据工程师、Excel 技能 | 
| 验证工作环境。 | 在 IDE 中，创建一个 Python 文件以将 Excel 输入工作表转换为 JSON 格式。（你也可以使用亚马逊 SageMaker 笔记本来处理 Python 代码，而不是 IDE。）确认您使用的 Python 版本是 3.7 或更高版本。<pre> python3 --version</pre>安装 **pandas** 程序包。<pre> pip3 install pandas --user</pre> | 常规 AWS | 
| 将 Excel 工作表数据转换为 JSON。 | 创建一个包含以下代码的 Python 文件，以将 Excel 转换为 JSON。<pre>import pandas as pd<br />data=pd.read_excel('./Book1.xls')<br />data.to_json(path_or_buf='my.json',orient='records')</pre>其中 `Book1` 是 Excel 工作表的名称，`my.json` 是输出 JSON 文件的名称。 | 数据工程师，Python 技能 | 
| 将 JSON 文件上传到 S3 存储桶。 | 将 `my.json`文件上传到 S3 存储桶。有关更多信息，请参阅 Amazon S3 文档中的[创建存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)。 | 应用程序开发人员 | 
| FqdnName | RecordType | 值 | TTL | 
| something.example.org | A | 1.1.1.1 | 900 | 

### 插入记录
<a name="insert-records"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建私有托管区 | 使用 [create\$1hosted\$1zone API](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/route53.html#Route53.Client.create_hosted_zone) 及以下 Python 示例代码创建私有托管区。将 `hostedZoneName`、`vpcRegion` 和 `vpcId` 参数值替换为您自己的值。<pre>import boto3<br />import random<br />hostedZoneName ="xxx"<br />vpcRegion = "us-east-1"<br />vpcId="vpc-xxxx"<br />route53_client = boto3.client('route53')<br />response = route53_client.create_hosted_zone(<br />        Name= hostedZoneName,<br />        VPC={<br />            'VPCRegion: vpcRegion,<br />            'VPCId': vpcId<br />        },<br />        CallerReference=str(random.random()*100000),<br />        HostedZoneConfig={<br />            'Comment': "private hosted zone created by automation",<br />            'PrivateZone': True<br />        }<br />    )<br /> print(response)</pre>您也可以使用诸如 AWS 之类的基础设施即代码 (IaC) 工具， CloudFormation 将这些步骤替换为使用适当资源和属性的堆栈创建堆栈的模板。 | 云架构师、网络管理员、Python 技能 | 
| 从 Amazon S3 以字典形式检索详细信息。 | 使用以下代码从 S3 存储桶中读取数据并获取 Python 字典形式的 JSON 值。 <pre>fileobj = s3_client.get_object(<br />        Bucket=bucket_name,<br />        Key='my.json'<br />        )<br />    filedata = fileobj['Body'].read()<br />    contents = filedata.decode('utf-8')<br />    json_content=json.loads(contents)<br />    print(json_content)</pre>其中 `json_content` 包含 Python 字典。 | 应用程序开发人员，Python 技能 | 
| 清理空格和 Unicode 字符数据值。 | 作为确保数据正确性的安全措施，请使用以下代码对 `json_content` 中的值执行剥离操作。此代码删除每个字符串前面和末尾的空格字符。它还使用 `replace` 方法来删除硬的（不间断的）空格（`\xa0` 字符）。<pre>for item in json_content:<br />    fqn_name = unicodedata.normalize("NFKD",item["FqdnName"].replace("u'", "'").replace('\xa0', '').strip())<br />    rec_type = item["RecordType"].replace('\xa0', '').strip()<br />    res_rec = {<br />                 'Value': item["Value"].replace('\xa0', '').strip()<br />                }</pre> | 应用程序开发人员，Python 技能 | 
| 插入记录。 | 使用以下代码作为上一个 `for` 循环的一部分。<pre>change_response = route53_client.change_resource_record_sets(<br />            HostedZoneId="xxxxxxxx",<br />            ChangeBatch={<br />                'Comment': 'Created by automation',<br />                'Changes': [<br />                    {<br />                        'Action': 'UPSERT',<br />                        'ResourceRecordSet': {<br />                            'Name': fqn_name,<br />                            'Type': rec_type,<br />                            'TTL': item["TTL"],<br />                            'ResourceRecords': res_rec<br />                        }<br />                    }<br />                ]<br />            }<br />    )</pre>`xxxxxxx` 是本操作说明第一步所述的托管区 ID。 | 应用程序开发人员，Python 技能 | 

## 相关资源
<a name="migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone-resources"></a>

**参考**
+ [通过导入区域文件创建记录](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating-import.html)（Amazon Route 53 文档）
+ [create\$1hosted\$1zone 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/route53.html#Route53.Client.create_hosted_zone)（Boto3 文档）
+ [change\$1resource\$1record\$1sets 方法](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/route53.html#Route53.Client.change_resource_record_sets)（Boto3 文档）

**教程和视频**
+ [Python 教程](https://docs.python.org/3/tutorial/)（Python 文档）
+ [使用 Amazon Route 53 进行域名系统设计](https://www.youtube.com/watch?v=2y_RBjDkRgY)（YouTube 视频，*AWS 在线技术讲座*）

# 在 AWS 上从 F5 迁移到应用程序负载均衡器时修改 HTTP 标头
<a name="modify-http-headers-when-you-migrate-from-f5-to-an-application-load-balancer-on-aws"></a>

*Sachin Trivedi，Amazon Web Services*

## Summary
<a name="modify-http-headers-when-you-migrate-from-f5-to-an-application-load-balancer-on-aws-summary"></a>

当您将使用 F5 负载均衡器的应用程序迁移到 Amazon Web Services (AWS) 并希望在 AWS 上使用应用程序负载均衡器时，迁移用于标头修改的 F5 规则是一个常见问题。Application Load Balancer 不支持修改标头，但你可以使用亚马逊 CloudFront 作为内容分发网络 (CDN)，使用 Lambda @Edge 来修改标头。

此模式描述了所需的集成，并提供了使用 AWS CloudFront 和 Lambda @Edge 修改标头的示例代码。

## 先决条件和限制
<a name="modify-http-headers-when-you-migrate-from-f5-to-an-application-load-balancer-on-aws-prereqs"></a>

**先决条件**
+ 使用 F5 负载均衡器的本地应用程序，其配置使用 `if, else` 替换 HTTP 标头值。有关此配置的详细信息，请参阅 F5 产品文档中的 [HTTP::header](https://clouddocs.f5.com/api/irules/HTTP__header.html)。 

**限制**
+ 此模式适用于 F5 负载均衡器标头自定义。对于其他第三方负载均衡器，请查看负载均衡器文档以获取支持信息。
+ 用于 Lambda@Edge 的 Lambda 函数必须位于美国东部(弗吉尼亚州北部)区域。

## 架构
<a name="modify-http-headers-when-you-migrate-from-f5-to-an-application-load-balancer-on-aws-architecture"></a>

下图显示了 AWS 上的架构，包括 CDN 与其他 AWS 组件之间的集成流程。

![\[使用亚马逊 CloudFront 和 Lambda 修改标题的架构 @Edge\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/00abbe3c-2453-4291-9b24-b488dced4868/images/4ee9a19e-6da2-4c5a-a8bc-19d3918a166e.png)


## 工具
<a name="modify-http-headers-when-you-migrate-from-f5-to-an-application-load-balancer-on-aws-tools"></a>

**Amazon Web Services**
+ [应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html) - 应用程序负载均衡器是一项 AWS 完全托管的负载均衡服务，在开放系统互连 (OSI) 模型的第七层运行。它可以在多个目标之间平衡流量，并支持基于 HTTP 标头和方法、查询字符串以及基于主机或基于路径的路由的高级路由请求。
+ [亚马逊 CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) — Amazon CloudFront 是一项网络服务，可加快向用户分发静态和动态网页内容（例如.html、.css、.js 和图像文件）的速度。 CloudFront 通过名为边缘位置的全球数据中心网络提供内容，以降低延迟并提高性能。
+ [Lambda @Edge ─](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-the-edge.html) Lambda @Edge 是 AWS Lambda 的扩展，它允许你运行函数来自定义所交付的内容。 CloudFront 您可以在美国东部（弗吉尼亚北部）区域创作函数，然后将该函数与 CloudFront 发行版相关联，以便在不预配置或管理服务器的情况下自动在全球范围内复制您的代码。如此便可减少延迟并改善用户体验。

**代码**

以下示例代码提供了修改 CloudFront 响应标头的蓝图。按照*操作说明*部分中的说明部署代码。

```
exports.handler = async (event, context) => {
    const response = event.Records[0].cf.response;
    const headers = response.headers;


    const headerNameSrc = 'content-security-policy';
    const headerNameValue = '*.xyz.com';


    if (headers[headerNameSrc.toLowerCase()]) {
        headers[headerNameSrc.toLowerCase()] = [{
            key: headerNameSrc,
            value: headerNameValue,
        }];
        console.log(`Response header "${headerNameSrc}" was set to ` +
                    `"${headers[headerNameSrc.toLowerCase()][0].value}"`);
    }
    else {
            headers[headerNameSrc.toLowerCase()] = [{
            key: headerNameSrc,
            value: headerNameValue,
            }];
    }
    return response;
};
```

## 操作说明
<a name="modify-http-headers-when-you-migrate-from-f5-to-an-application-load-balancer-on-aws-epics"></a>

### 创建 CDN 分配
<a name="create-a-cdn-distribution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 CloudFront Web 分发。 | 在此步骤中，您将创建一个 CloudFront 分发，以告知您要从 CloudFront 哪里交付内容，以及有关如何跟踪和管理内容交付的详细信息。要使用控制台创建分配，请登录 AWS 管理控制台，打开[CloudFront 控制台](https://console.aws.amazon.com/cloudfront/v3/home)，然后按照[CloudFront 文档](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-creating-console.html)中的步骤操作。 | 云管理员 | 

### 创建并部署 Lambda@Edge 函数
<a name="create-and-deploy-the-lambda-edge-function"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建并部署 Lambda@Edge 函数。 | 您可以使用修改 CloudFront 响应标头的蓝图来创建 Lambda @Edge 函数。（其他蓝图可用于不同的用例；有关更多信息，请参阅文档中的 [ CloudFront Lambda @Edge 示例](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html)函数。） 若要创建 Lambda@Edge 函数：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/modify-http-headers-when-you-migrate-from-f5-to-an-application-load-balancer-on-aws.html) | AWS 管理员 | 
| 部署 Lambda@Edge 函数。 | 按照亚马逊 CloudFront 文档中*教程：创建简单的 Lambda @Edge 函数*的[第 4 步](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-how-it-works-tutorial.html#lambda-edge-how-it-works-tutorial-add-trigger)中的说明配置 CloudFront 触发器并部署该函数。 | AWS 管理员 | 

## 相关资源
<a name="modify-http-headers-when-you-migrate-from-f5-to-an-application-load-balancer-on-aws-resources"></a>

**CloudFront 文档**
+ [自定义源的请求和响应行为](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/RequestAndResponseBehaviorCustomOrigin.html) 
+ [使用分配](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-working-with.html) 
+ [Lambda@Edge 示例函数](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-examples.html) 
+ [使用 Lambda@Edge 在边缘进行自定义](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-at-the-edge.html)
+ [教程：创建简单的 Lambda@Edge 函数](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-edge-how-it-works-tutorial.html)

# 创建网络访问分析器在多个入站互联网访问中发现的报告 AWS 账户
<a name="create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts"></a>

*Mike Virgilio，Amazon Web Services*

## Summary
<a name="create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts-summary"></a>

无意中入站 Internet 访问 AWS 资源可能会给组织的数据外围带来风险。[网络访问分析器](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/what-is-network-access-analyzer.html)是一项 Amazon Virtual Private Cloud（Amazon VPC）功能，可帮助您识别对 Amazon Web Services（AWS）资源的意外网络访问。您可以使用网络访问分析器指定网络访问要求并识别不满足指定要求的潜在网络路径。您可以使用网络访问分析器执行以下操作：

1. 确定可通过互联网网关访问互联网的 AWS 资源。

1. 验证您的虚拟私有云 (VPCs) 是否进行了适当的分段，例如隔离生产和开发环境以及分离事务性工作负载。

Network Access Analyzer 分析 end-to-end网络可访问性条件，而不仅仅是分析单个组件。为了确定资源是否可以访问互联网，Network Access Analyzer 会评估互联网网关、VPC 路由表、网络访问控制列表 (ACLs)、弹性网络接口上的公有 IP 地址和安全组。如果这些组件中的任何一个阻止互联网访问，则网络访问分析器不会生成调查发现。例如，如果 Amazon Elastic Compute Cloud (Amazon EC2) 实例有一个开放的安全组，允许来自的流量，`0/0`但该实例位于无法从任何互联网网关路由的私有子网中，则网络访问分析器将不会生成结果。这提供了高保真结果，以便您可以识别真正可从互联网访问的资源。

运行网络访问分析器时，使用[网络访问作用域](https://docs.aws.amazon.com/vpc/latest/network-access-analyzer/what-is-network-access-analyzer.html#concepts)来指定网络访问要求。此解决方案可识别 互联网网关和弹性网络接口之间的网络路径。在这种模式下，您可以在组织 AWS 账户 中集中部署解决方案，由其管理 AWS Organizations，并分析组织中任何 AWS 区域帐户中的所有帐户。

该解决方案的设计考虑了以下内容：
+ 这些 AWS CloudFormation 模板减少了在这种模式下部署 AWS 资源所需的工作量。
+ 您可以在部署时调整 CloudFormation 模板和 **naa-script.sh** 脚本中的参数，以便根据您的环境对其进行自定义。
+ Bash 脚本自动并行预配和分析多个账户的网络访问范围。
+ Python 脚本处理结果，提取数据，然后合并结果。您可以选择以 CSV 格式或在 AWS Security Hub CSPM中查看网络访问分析器调查发现的合并报告。CSV 报告的示例可在此模式的[其他信息](#create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts-additional)部分找到。
+ 您可以修正结果，也可以通过将结果添加到 **naa-exclusions.csv** 文件来将其从将来的分析中排除。

## 先决条件和限制
<a name="create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts-prereqs"></a>

**先决条件**
+  AWS 账户 用于托管安全服务和工具，作为中组织的成员帐户进行管理 AWS Organizations。在此模式中，此账户称为安全账户。
+ 在安全账户中，必须具有具有出站互联网访问权限的私有子网。有关说明，请参阅 Amazon VPC 文档中的[创建子网](https://docs.aws.amazon.com/vpc/latest/userguide/create-subnets.html)。您可以使用 [NAT 网关](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)或[接口 VPC 端点](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html)建立互联网访问。
+ 对 AWS Organizations 管理账户或拥有委托管理员权限的账户的访问权限 CloudFormation。有关说明，请参阅 CloudFormation 文档[中的注册委托管理员](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-delegated-admin.html)。
+ 在 AWS Organizations 和之间启用可信访问 CloudFormation。有关说明，请参阅 CloudFormation 文档 AWS Organizations中的[使用启用可信访问](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-enable-trusted-access.html)。
+ 如果您要将调查结果上传到 Security Hub CSPM，则必须在账户和亚马逊 EC2 实例的配置位置 AWS 区域 中启用 Security Hub CSPM。有关更多信息，请参阅[设置 AWS Security Hub CSPM](https://docs.aws.amazon.com/securityhub/latest/userguide/securityhub-settingup.html)。

**限制**
+ 由于网络访问分析器功能的限制，当前不会分析跨账户网络路径。
+ 目标 AWS 账户 必须作为一个组织在中进行管理 AWS Organizations。**如果你不使用 AWS Organizations，你可以更新适用于你环境的 **naa-execrole.yaml** CloudFormation 模板和 naa-script.sh 脚本。**相反，您可以提供要在其中运行脚本的区域的列表。 AWS 账户 IDs 
+ 该 CloudFormation 模板旨在将 Amazon EC2 实例部署到具有出站互联网访问权限的私有子网中。 AWS Systems Manager 代理（SSM 代理）需要出站访问才能访问 Systems Manager 服务端点，并且您需要出站访问权限才能克隆代码存储库和安装依赖项。如果您想使用公有子网，则必须修改 **naa-resources.yaml** 模板以将弹性 [IP 地址](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html)与亚马逊实例相关联。 EC2 

## 架构
<a name="create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts-architecture"></a>

**目标架构**

*选项 1：访问 Amazon S3 存储桶中的结果*

![\[在 Amazon S3 存储桶中访问网络访问分析器调查发现报告的架构图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/eda6abba-632a-4e3d-92b9-31848fa6dead/images/d0b08437-e5b0-47a1-abdd-040c67b5da8f.png)


此图显示以下流程：

1. 如果您手动运行解决方案，则用户使用会话管理器对 Amazon EC2 实例进行身份验证，然后运行 **naa-script.sh** 脚本。此 Shell 脚本执行步骤 2-7。

   如果自动运行解决方案，则 **naa-script.sh** 脚本将按照在 cron 表达式中定义的计划自动启动。此 Shell 脚本执行步骤 2-7。有关详细信息，请参阅本节末尾的*自动化和扩缩*。

1. 亚马逊 EC2 实例从亚马逊 S3 存储桶下载最新**的 naa-exception.csv** 文件。稍后在 Python 脚本处理排除项时，将在此过程中使用此文件。

1. Amazon EC2 实例担任 `NAAEC2Role` AWS Identity and Access Management (IAM) 角色，该角色授予访问 Amazon S3 存储桶和在组织中其他账户中担任 `NAAExecRole` IAM 角色的权限。

1. Amazon EC2 实例在组织的管理账户中担任 `NAAExecRole` IAM 角色，并生成组织中的账户列表。

1. Amazon EC2 实例在组织的成员账户（架构图中称为*工作负载账户*）中担任 `NAAExecRole` IAM 角色，并在每个账户中执行安全评估。调查结果以 JSON 文件形式存储在亚马逊 EC2 实例上。

1. Amazon EC2 实例使用 Python 脚本来处理 JSON 文件、提取数据字段并创建 CSV 报告。

1. 亚马逊 EC2 实例将 CSV 文件上传到亚马逊 S3 存储桶。

1. Amazon EventBridge 规则会检测文件上传，并使用 Amazon SNS 主题发送一封电子邮件，通知用户报告已完成。

1. 用户从 Amazon S3 存储桶下载 CSV 文件。用户将结果导入 Excel 模板，并查看结果。

*选项 2：访问中的调查结果 AWS Security Hub CSPM*

![\[通过 AWS Security Hub 访问网络访问分析器调查发现的架构图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/eda6abba-632a-4e3d-92b9-31848fa6dead/images/9cb4f059-dfb6-4a33-9f8d-159fe5df0d64.png)


该图显示了以下过程：

1. 如果您手动运行解决方案，则用户使用会话管理器对 Amazon EC2 实例进行身份验证，然后运行 **naa-script.sh** 脚本。此 Shell 脚本执行步骤 2-7。

   如果自动运行解决方案，则 **naa-script.sh** 脚本将按照在 cron 表达式中定义的计划自动启动。此 Shell 脚本执行步骤 2-7。有关详细信息，请参阅本节末尾的*自动化和扩缩*。

1. 亚马逊 EC2 实例从亚马逊 S3 存储桶下载最新**的 naa-exception.csv** 文件。稍后在 Python 脚本处理排除项时，将在此过程中使用此文件。

1. Amazon EC2 实例担任 `NAAEC2Role` IAM 角色，该角色授予访问 Amazon S3 存储桶和在组织中其他账户中担任 `NAAExecRole` IAM 角色的权限。

1. Amazon EC2 实例在组织的管理账户中担任 `NAAExecRole` IAM 角色，并生成组织中的账户列表。

1. Amazon EC2 实例在组织的成员账户（架构图中称为*工作负载账户*）中担任 `NAAExecRole` IAM 角色，并在每个账户中执行安全评估。调查结果以 JSON 文件形式存储在亚马逊 EC2 实例上。

1. 亚马逊 EC2 实例使用 Python 脚本来处理 JSON 文件并提取数据字段以导入 Security Hub CSPM。

1. 亚马逊 EC2 实例将网络访问分析器的结果导入到 Security Hub CSPM。

1. Amazon EventBridge 规则会检测导入，并使用 Amazon SNS 主题发送一封电子邮件，通知用户该过程已完成。

1. 用户在 Security Hub CSPM 中查看调查结果。

**自动化和扩缩**

您可以计划此解决方案，以便按自定义计划自动运行 **naa-script.sh** 脚本。要设置自定义计划，请在 **naa-resources.yaml** CloudFormation 模板中修改参数。`CronScheduleExpression`例如，默认值 `0 0 * * 0` 在每个星期日的午夜运行解决方案。如果值为 `0 0 * 1-12 0`，则该解决方案将在每个月第一个星期日的午夜运行。有关使用 cron 表达式的更多信息，请参阅 Systems Manager 文档中的 [Cron 和 rate 表达式](https://docs.aws.amazon.com/systems-manager/latest/userguide/reference-cron-and-rate-expressions.html)。

如果要在部署 `NAA-Resources` 堆栈后调整计划，可以在 `/etc/cron.d/naa-schedule` 中手动编辑 cron 计划。

## 工具
<a name="create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts-tools"></a>

**AWS 服务**
+ [亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/ec2/) 在中提供可扩展的计算容量 AWS 云。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一项无服务器事件总线服务，可帮助您将应用程序与来自各种来源的实时数据连接起来。例如， AWS Lambda 函数、使用 API 目的地的 HTTP 调用端点或其他 AWS 账户目的地的事件总线。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)是一项账户管理服务，可帮助您将多个账户整合 AWS 账户 到一个由您创建和集中管理的组织中。
+ [AWS Security Hub CSPM](https://docs.aws.amazon.com/securityhub/latest/userguide/what-is-securityhub.html)提供了您的安全状态的全面视图 AWS。它还可以帮助您根据安全行业标准和最佳实践检查您的 AWS 环境。
+ [Amazon Simple Notification Service（Amazon SNS）](https://docs.aws.amazon.com/sns/latest/dg/welcome.html)可帮助您协调和管理发布者与客户端（包括 Web 服务器和电子邮件地址）之间的消息交换。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 可帮助您管理在 AWS 云中运行的应用程序和基础设施。它简化了应用程序和资源管理，缩短了检测和解决操作问题的时间，并帮助您大规模安全地管理 AWS 资源。此模式使用 Session Manager，这是 Systems Manager 的一项功能。

**代码存储库**

此模式的代码可在 GitHub [Network Access Analyzer 多账户分析](https://github.com/aws-samples/network-access-analyzer-multi-account-analysis)存储库中找到。代码存储库包含以下文件：
+ **naa-script.sh** — 此 bash 脚本用于启动并行分析多个 AWS 账户网络访问分析器分析。根据 **naa-resources.yaml** CloudFormation 模板中的定义，此脚本将自动部署到亚马逊实例上的文件夹`/usr/local/naa`。 EC2 
+ **naa-resources.yaml** — 您可以使用此 CloudFormation 模板在组织的安全账户中创建堆栈。此模板部署了该账户所需所有资源，以支持此解决方案。此堆栈必须在 **naa-execrole.yaml** 模板之前部署。
**注意**  
如果删除并重新部署此堆栈，则必须重新构建 `NAAExecRole` 堆栈集，以便重新构建 IAM 角色之间的跨账户依赖关系。
+ **naa-execrole.yaml** — 您可以使用此 CloudFormation 模板创建堆栈集，该堆栈集可在组织中的所有账户（包括管理账户）中部署 `NAAExecRole` IAM 角色。
+ **naa-processfindings.py** — **naa-script.sh** 脚本会自动调用此 Python 脚本来处理网络访问分析器 JSON 输出，在 **naa-exclusions.csv** 文件中排除任何已知良好的资源，然后生成合并结果的 CSV 文件或将结果导入 Security Hub CSPM。

## 操作说明
<a name="create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts-epics"></a>

### 准备部署
<a name="prepare-for-deployment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆代码存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 
| 查看模板 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 

### 创建堆 CloudFormation 栈
<a name="create-the-cfnshort-stacks"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在安全账户中预置资源。 | 使用 **naa-resources.yaml** 模板，您可以创建一个 CloudFormation 堆栈，用于在安全账户中部署所有必需的资源。有关说明，请参阅 CloudFormation 文档中的[创建堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。部署此模板时应注意以下几点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 
| 在成员账户中预置 IAM 角色。 | 在 AWS Organizations 管理账户或具有委托管理员权限的账户中 CloudFormation，使用 **naa-execrole.yaml** 模板创建堆栈集。 CloudFormation 堆栈集在组织中的所有成员账户中部署 `NAAExecRole` IAM 角色。有关说明，请参阅 CloudFormation 文档中的[使用服务管理权限创建堆栈集](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-getting-started-create.html#stacksets-orgs-associate-stackset-with-org)。部署此模板时应注意以下几点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 
| 在管理账户中预置 IAM 角色。 | 使用 **naa-execrole.yaml** 模板，您可以创建一个 CloudFormation 堆栈，用于在组织的管理账户中部署 `NAAExecRole` IAM 角色。您之前创建的堆栈集不在管理账户中部署 IAM 角色。有关说明，请参阅 CloudFormation 文档中的[创建堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。部署此模板时应注意以下几点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 

### 执行分析
<a name="perform-the-analysis"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 自定义 shell 脚本。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 
| 分析目标账户。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 
| 选项 1 - 从 Amazon S3 存储桶中检索结果。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 
| 选项 2 — 在 Security Hub CSPM 中查看结果。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 

### 修正和排除结果
<a name="remediate-and-exclude-findings"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 纠正发现的问题。 | 纠正您想要解决的任何问题。有关如何围绕 AWS 身份、资源和网络创建边界的更多信息和最佳实践，请参阅[在 AWS（AWS 白皮书）上构建数据边界](https://docs.aws.amazon.com/whitepapers/latest/building-a-data-perimeter-on-aws/building-a-data-perimeter-on-aws.html)。 | AWS DevOps | 
| 排除具有已知良好网络路径的资源。 | 如果网络访问分析器生成应可从互联网访问的资源的调查发现，则可以将这些资源添加到排除列表中。下次运行网络访问分析器时，它不会为该资源生成调查发现。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 

### （可选）更新 naa-script.sh 脚本
<a name="optional-update-the-naa-script-sh-script"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新 naa-script.sh 脚本。 | 如果要将 **naa-script.sh** 脚本更新到存储库中的最新版本，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 

### （可选）清理
<a name="optional-clean-up"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除所有已部署资源。 | 您可以将资源保留在账户中。如果要取消预配所有资源，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | AWS DevOps | 

## 问题排查
<a name="create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 无法使用会话管理器连接到 Amazon EC2 实例。 | SSM 代理必须能够与 Systems Manager 端点通信。执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts.html) | 
| 部署堆栈集时， CloudFormation 控制台会提示您这样做`Enable trusted access with AWS Organizations to use service-managed permissions`。 | 这表示未在 AWS Organizations 和之间启用可信访问 CloudFormation。部署服务托管堆栈集需要可信访问权限。选择该按钮以启用受信任的访问。有关更多信息，请参阅 CloudFormation 文档中的[启用可信访问](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-enable-trusted-access.html)。 | 

## 相关资源
<a name="create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts-resources"></a>
+ [新增 — Amazon VPC 网络访问分析器](https://aws.amazon.com/blogs/aws/new-amazon-vpc-network-access-analyzer/)（AWS 博客文章）
+ [AWS re: inForce 2022-在 AWS (NIS202) 上验证有效的网络访问控制（视频）](https://youtu.be/aN2P2zeQek0)
+ [演示 - 使用网络访问分析器进行组织范围的 Internet 入口数据路径分析](https://youtu.be/1IFNZWy4iy0)(视频)

## 附加信息
<a name="create-a-report-of-network-access-analyzer-findings-for-inbound-internet-access-in-multiple-aws-accounts-additional"></a>

**控制台输出示例**

以下示例显示了生成目标账户列表和分析目标账户的输出。

```
[root@ip-10-10-43-82 naa]# ./naa-script.sh
download: s3://naa-<account ID>-us-east-1/naa-exclusions.csv to ./naa-exclusions.csv

AWS Management Account: <Management account ID>

AWS Accounts being processed...
<Account ID 1> <Account ID 2> <Account ID 3>

Assessing AWS Account: <Account ID 1>, using Role: NAAExecRole
Assessing AWS Account: <Account ID 2>, using Role: NAAExecRole
Assessing AWS Account: <Account ID 3>, using Role: NAAExecRole
Processing account: <Account ID 1> / Region: us-east-1
Account: <Account ID 1> / Region: us-east-1 – Detecting Network Analyzer scope...
Processing account: <Account ID 2> / Region: us-east-1
Account: <Account ID 2> / Region: us-east-1 – Detecting Network Analyzer scope...
Processing account: <Account ID 3> / Region: us-east-1
Account: <Account ID 3> / Region: us-east-1 – Detecting Network Analyzer scope...
Account: <Account ID 1> / Region: us-east-1 – Network Access Analyzer scope detected.
Account: <Account ID 1> / Region: us-east-1 – Continuing analyses with Scope ID. Accounts with many resources may take up to one hour
Account: <Account ID 2> / Region: us-east-1 – Network Access Analyzer scope detected.
Account: <Account ID 2> / Region: us-east-1 – Continuing analyses with Scope ID. Accounts with many resources may take up to one hour
Account: <Account ID 3> / Region: us-east-1 – Network Access Analyzer scope detected.
Account: <Account ID 3> / Region: us-east-1 – Continuing analyses with Scope ID. Accounts with many resources may take up to one hour
```

**CSV 报告示例**

下图是 CSV 输出的示例。

![\[此解决方案生成的 CSV 报告的示例 1。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/eda6abba-632a-4e3d-92b9-31848fa6dead/images/55e02e61-054e-4da6-aaae-c9a8b6f4f272.png)


![\[此解决方案生成的 CSV 报告的示例 2。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/eda6abba-632a-4e3d-92b9-31848fa6dead/images/95f980ad-92c1-4392-92d4-9c742755aab2.png)


# 在多账户 AWS 环境中为混合网络设置 DNS 解析
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment"></a>

*Anvesh Koganti，Amazon Web Services*

## Summary
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-summary"></a>

此模式为在包含多个 Amazon Web Services（AWS）账户的混合网络环境中设置 DNS 解析提供了全面的解决方案。它支持通过 Amazon Route 53 Resolver 端点在本地网络和 AWS 环境之间进行双向 DNS 解析。此模式提供两种解决方案，可在[多账户、集中式架构](https://docs.aws.amazon.com/whitepapers/latest/hybrid-cloud-dns-options-for-vpc/scaling-dns-management-across-multiple-accounts-and-vpcs.html#multi-account-centralized)中启用 DNS 解析：
+ *基本设置*不使用 Route 53 Profiles，有助于为复杂性较低的中小规模部署优化成本。
+ *增强设置*使用 Route 53 Profiles 来简化操作，最适用于规模更大或更复杂的 DNS 部署场景。

**注意**  
实施前请查看*限制*部分，了解服务限制和配额。做出决定时，请综合考虑管理开销、成本、运营复杂性及团队专业能力等因素。

## 先决条件和限制
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-prereqs"></a>

**先决条件**
+ 一种 AWS 多账户环境，其中包含跨共享服务和工作负载账户部署的亚马逊虚拟私有云（Amazon VPC）（最好[遵循账户结构 AWS 最佳实践通过 AWS Control Tower](https://docs.aws.amazon.com/controltower/latest/userguide/aws-multi-account-landing-zone.html) 进行设置）。
+ 您的本地网络与 AWS 环境之间现有的混合连接（AWS Direct Connect 或 AWS Site-to-Site VPN）。
+ Amazon VPC 对等互连 AWS Transit Gateway，或用于第 3 层网络之间 VPCs连接的 AWS 云 WAN。（应用程序流量需要此连接。 DNS 解析不需要。 DNS 解析独立于两者之间的网络连接 VPCs。）
+ 在本地环境中运行的 DNS 服务器。

**限制**
+ Route 53 Resolver 端点、规则和配置文件是区域结构，可能需要 AWS 区域 对全球组织进行多个复制。
+ 有关 Route 53 Resolver、私有托管区及 Profiles 的服务配额的完整列表，请参阅 Route 53 文档中的[配额](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/DNSLimitations.html)。

## 架构
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-architecture"></a>

**目标技术堆栈**
+ Route 53 出站和入站端点
+ 用于条件转发的 Route 53 Resolver 规则
+ AWS Resource Access Manager (AWS RAM)
+ Route 53 私有托管区

**目标架构 **

**出站和入站端点**

下图显示了从本地 AWS 到内部的 DNS 解析流程。这是针对域名托管在本地场景的出站解析的连接配置。以下是设置所涉及流程的高层级概述。有关详细信息，请参阅[操作说明](#set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-epics)部分。

1. 在共享服务 VPC 中部署 Route 53 Resolver 出站端点。

1. 在共享服务账户中为本地托管的域名创建 Route 53 Resolver 规则（转发规则）。

1.  VPCs 在托管需要解析本地托管域名的资源的其他账户中共享规则并将其关联。根据您的使用案例，可以通过不同的方式完成此操作，具体将在本部分后续内容中说明。

![\[AWS 到本地环境 DNS 解析流程中的入站和出站端点\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/01e700cd-be8c-4a5d-bc89-b901a260d045/images/d69d4cad-5e2c-4481-9370-2708e8a4f8c1.png)


设置连接后，出站解析所涉及的步骤如下：

1. 亚马逊弹性计算云 (Amazon EC2) 实例通过 VPC\$12 地址向 VPC 的 Route 53 解析器发送 DNS 解析请求。`db.onprem.example.com`

1. Route 53 解析器检查解析器规则，并使用出站终端节点将请求转发到本地 DNS 服务器 IPs 。

1. 出站终端节点将请求转发到本地 DNS IPs。流量通过共享服务 VPC 与本地数据中心之间已建立的混合网络连接进行传输。

1. 本地 DNS 服务器向出站端点返回响应，出站端点再将该响应转发回 VPC 的 Route 53 Resolver。解析器将响应返回给 EC2 实例。

下图显示了从本地环境到的 DNS 解析流程 AWS。这是针对域名托管在 AWS场景的入站解析的连接配置。以下是设置所涉及流程的高层级概述。有关详细信息，请参阅[操作说明](#set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-epics)部分。

1. 在共享服务 VPC 中部署 Resolver 入站端点。

1. 在共享服务账户中创建私有托管区（集中式方法）。

1. 将私有托管区与共享服务 VPC 关联。共享这些区域并将其与跨账户关联以进行 VPC-to-VPC DN VPCs S 解析。根据您的使用案例，可以通过不同的方式完成此操作，具体将在本部分后续内容中说明。

![\[本地环境到 AWS DNS 解析流程中的入站和出站端点。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/01e700cd-be8c-4a5d-bc89-b901a260d045/images/a6f5348c-2041-453e-8939-2b4ee0b7ebd8.png)


设置连接后，入站解析所涉及的步骤如下：

1. 本地资源向本地 DNS 服务器发送针对 `ec2.prod.aws.example.com` 的 DNS 解析请求。

1. 本地 DNS 服务器通过混合网络连接，将该请求转发至共享服务 VPC 中的 Resolver 入站端点。

1. 借助 VPC Route 53 Resolver，Resolver 入站端点在关联的私有托管区中查找该请求，并获取相应的 IP 地址。

1. 这些 IP 地址被发送回本地 DNS 服务器，再由本地 DNS 服务器将响应返回给本地资源。

此配置使本地资源能够通过入站端点将查询路由到相应的 AWS 私有托管区域，从而解析私有域名。在此架构中，私有托管区集中部署在共享服务 VPC 中，支持由单个团队进行集中式 DNS 管理。这些区域可以与许多区域相关联 VPCs ，以解决 VPC-to-VPC DNS 解析用例。或者，您可能希望将 DNS 域的所有权和管理委托给每个人 AWS 账户。在这种情况下，每个账户管理各自的私有托管区，并将每个区域与中央共享服务 VPC 关联，以实现与本地环境的统一解析。这种分散式方法不在此模式的范围之内。有关更多信息，请参阅[跨多个账户扩展 DNS 管理以及 VPCs](https://docs.aws.amazon.com/whitepapers/latest/hybrid-cloud-dns-options-for-vpc/scaling-dns-management-across-multiple-accounts-and-vpcs.html) *Amazon VPC 的混合云 DNS 选项*白皮书。

使用 Resolver 端点建立基本的 DNS 解析流程时，您需要确定如何管理跨 AWS 账户的 Resolver 规则和私有托管区的共享与关联。您可以通过两种方式来解决这个问题：通过使用 AWS RAM 共享解析器规则和直接私有托管区域关联进行自我管理共享（如*基本设置*部分所述），或者通过 Route 53 配置文件（如*增强设置*部分所述）。具体选择取决于您组织的 DNS 管理偏好和运维需求。以下架构图说明了一个扩展的环境，该环境包括多个 VPCs 跨不同账户的环境，这代表了典型的企业部署。

**基本设置**

在基本设置中，在多账户 AWS 环境中实现混合 DNS 解析时使用 AWS RAM 共享解析器转发规则和私有托管区域关联，以管理本地和 AWS 资源之间的 DNS 查询。此方法使用连接到本地网络的共享服务 VPC 中的集中式 Route 53 Resolver 端点，高效处理入站和出站 DNS 解析。
+ 要进行出站解析，需要在 Shared Services 账户中创建解析器转发规则，然后使用 AWS RAM与其他 AWS 账户 人共享。此类共享仅限同一区域内的账户。然后，目标账户可以将这些规则与其关联起来， VPCs 并使这些规则中的资源 VPCs 能够解析本地域名。
+ 对于入站解析：在共享服务账户中创建私有托管区，并将其与共享服务 VPC 关联。然后，可以使用 Rout VPCs e 53 API 或 AWS Command Line Interface (AWS CLI) 将这些区域关联到其他账户中。 AWS SDKs然后，关联中的资源 VPCs 可以解析私有托管区域中定义的 DNS 记录，从而在您的 AWS 环境中创建统一的 DNS 视图。

下图显示此基本设置中的 DNS 解析流程。

![\[在多账户 AWS 环境中使用基本设置进行混合 DNS 解析。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/01e700cd-be8c-4a5d-bc89-b901a260d045/images/258e4bcd-e9c6-43b5-bab8-856ca22206b9.png)


当您使用的 DNS 基础设施规模有限时，此设置能良好运行。但随着环境规模的扩大，管理难度会逐渐增加。随着规模的扩展，管理私有托管区域和解析器规则的共享和关联方式的运营开 VPCs 销会显著增加。此外，服务配额（例如每个私有托管区的 300 个 VPC 关联限制）可能会成为大规模部署的限制因素。而增强设置可应对这些挑战。

**增强设置**

Route 53 Profiles 为管理跨多个 AWS 账户的混合网络中的 DNS 解析提供了简化的解决方案。您无需单独管理私有托管区域和解析器规则，而是可以将 DNS 配置分组到一个容器中，便于在一个区域中的多个账户之间共享 VPCs 和应用。此配置既保留了共享服务 VPC 中集中式 Resolver 端点的架构，又显著简化了 DNS 配置的管理流程。

下图显示增强设置中的 DNS 解析流程。

![\[在多账户 AWS 环境中，使用增强设置和 Route 53 Profiles 进行混合 DNS 解析。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/01e700cd-be8c-4a5d-bc89-b901a260d045/images/55b9681d-ddb4-4a55-b4ec-fc9afa9870fa.png)


使用 Route 53 Profiles，您可将私有托管区关联、Resolver 转发规则以及 DNS 防火墙规则整合到单个可共享单元中。您可以在 Shared Services 帐户中创建个人资料并使用与成员帐户共享 AWS RAM。共享配置文件并将其应用于目标时 VPCs，服务会自动处理所有必要的关联和配置。这样可显著降低 DNS 管理的运营开销，并为不断增长的环境提供出色的可扩展性。

**自动化和扩展**

使用 Terraform 等 CloudFormation 基础设施即代码 (IaC) 工具自动配置和管理 Route 53 Resolver 端点、规则、私有托管区域和配置文件。将 DNS 配置与持续集成和持续交付（CI/CD）管道集成，以确保配置的一致性、可重复性，并实现快速更新。

## 工具
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-tools"></a>

**AWS 服务**
+ [AWS Resource Access Manager (AWS RAM)](https://docs.aws.amazon.com/ram/latest/userguide/what-is.html) 可帮助您安全地共享资源， AWS 账户 从而减少运营开销并提供可见性和可审计性。
+ [Amazon Route 53 Resolver](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver.html)以递归方式响应来自 AWS 资源的 DNS 查询，默认情况下全部 VPCs可用。您可以创建 Resolver 端点和条件转发规则，以解析本地数据中心和您的数据中心之间的 DNS 命名空间。 VPCs
+ [Amazon Route 53 私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html)是一个容器，其中包含的信息说明您希望 Route 53 如何响应某个域及其子域的 DNS 查询。
+ [Amazon Route 53 配置文件](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/profiles.html)允许您以简化的方式在许多 VPCs 不同 AWS 账户 版本中应用和管理与 DNS 相关的 Route 53 配置。

## 最佳实践
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-best-practices"></a>

本节提供了优化 Route 53 Resolver 的一些最佳实践，这些实践是 Route 53 最佳实践的一部分。有关完整列表，请参阅 [Amazon Route 53 的最佳实践](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/best-practices.html)。

**避免使用解析器端点进行循环配置**
+ 设计您的 DNS 架构，通过精心规划 VPC 关联来防止递归路由。当 VPC 托管入站端点时，请避免将其与可能产生循环引用的 Resolver 规则相关联。
+ 当您在账户之间共享 DNS 资源以保持干净的路由路径时，请 AWS RAM 策略性地使用。

有关更多信息，请参阅 Route 53 文档中的[避免 Resolver 端点出现循环配置](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/best-practices-resolver-endpoints.html)。

**Resolver 端点扩展**
+ 对于每秒查询量（QPS）需求较高的环境，请注意，端点中每个 ENI 的 QPS 上限为 10,000。 ENIs 可以向终端节点添加更多内容以扩展 DNS QPS。
+ Amazon CloudWatch 提供`InboundQueryVolume`和`OutboundQueryVolume`指标（参见[CloudWatch 文档](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/monitoring-resolver-with-cloudwatch.html)）。建议您设置监控规则，当阈值超过特定值（例如 10,000 QPS 的 80%）时提醒您。
+ 为 Resolver 端点配置有状态安全组规则，以防止在高流量场景下，连接跟踪限制导致 DNS 查询被限流。要详细了解安全组中连接跟踪的工作原理，请参阅[亚马逊 EC2 文档中的亚马逊 EC2 安全组连接跟踪](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html)。

有关更多信息，请参阅 Route 53 文档中的 [Resolver 端点扩展](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/best-practices-resolver-endpoint-scaling.html)。

**为 Resolver 端点提供高可用性**
+ 创建入站端点，采用至少两个可用区中的 IP 地址以实现冗余。
+ 预调配额外的网络接口，以确保维护或流量激增期间的可用性。

有关更多信息，请参阅 Route 53 文档中的 [Resolver 端点的高可用性](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/best-practices-resolver-endpoint-high-availability.html)。

## 操作说明
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-epics"></a>

### 部署 Route 53 Resolver 端点
<a name="deploy-r53r-endpoints"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署入站端点。 | Route 53 Resolver 使用入站端点接收来自本地 DNS 解析器的 DNS 查询。有关说明，请参阅 Route 53 文档[ VPCs 中的将入站 DNS 查询转发](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-forwarding-inbound-queries.html)给您。记下入站端点 IP 地址。 | AWS 管理员、云管理员 | 
| 部署出站端点。 | Route 53 解析器使用出站端点向本地 DNS 解析器发送 DNS 查询。有关说明，请参阅 Route 53 文档中的[将出站 DNS 查询转发到您的网络](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-forwarding-outbound-queries.html)。记下输出端点 ID。 | AWS 管理员、云管理员 | 

### 配置和共享 Route 53 私有托管区
<a name="configure-and-share-r53-private-hosted-zones"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 AWS上托管的域名创建私有托管区。 | 此区域保存 AWS托管域（例如`prod.aws.example.com`）中应从本地环境解析的资源的 DNS 记录。有关说明，请参阅 Route 53 文档中的[创建私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zone-private-creating.html)。创建私有托管区时，必须将 VPC 与同一账户拥有的托管区相关联。为此，请选择共享服务 VPC。 | AWS 管理员、云管理员 | 
| 基本设置：将私有托管区域与其他 VPCs 账户相关联。 | 如果使用的是基本设置（请参阅[架构](#set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-architecture)部分）：要使成员账户中的资源 VPCs 能够解析此私有托管区域中的 DNS 记录，您必须将您的资源 VPCs 与托管区域关联。您必须授权关联，然后通过编程方式完成关联。有关说明，请参阅 Route 53 文档中的[将 Amazon VPC 与您使用不同的 AWS 账户创建的私有托管区相关联](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zone-private-associate-vpcs-different-accounts.html)。 | AWS 管理员、云管理员 | 
| 增强设置：配置和共享 Route 53 Profiles。 | 如果使用的是增强设置（请参阅[架构](#set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-architecture)部分）：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment.html)根据组织的结构和 DNS 要求，您可能需要为不同的账户或工作负载创建和管理多个配置文件。 | AWS 管理员、云管理员 | 

### 配置并共享 Route 53 Resolver 转发规则
<a name="configure-and-share-r53r-forwarding-rules"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为本地托管的域名创建转发规则 | 此规则将指示 Route 53 Resolver 将本地域名（例如 `onprem.example.com`）的任何 DNS 查询转发给本地 DNS 解析器。要创建此规则，您需要本地 DNS 解析器的 IP 地址和出站端点 ID。有关说明，请参阅 Route 53 文档中的[创建转发规则](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-rules-managing-creating-rules.html)。 | AWS 管理员、云管理员 | 
| 基本设置：共享转发规则并将其与您在其他账户 VPCs 中的账户关联。 | 如果使用的是基本设置：要使转发规则生效，您必须将该规则与您在其他账户 VPCs 中共享和关联。然后，Route 53 Resolver 在解析域名时会将此规则纳入考量。有关说明，请参阅 Route 53 文档中的[与其他人共享解析器规则 AWS 账户 和使用共享](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-rules-managing-sharing.html)[规则和将转发规则与 VPC 关联](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-rules-managing-associating-rules.html)。 | AWS 管理员、云管理员 | 
| 增强设置：配置和共享 Route 53 Profiles。 | 如果使用的是增强设置：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment.html)根据组织的结构和 DNS 要求，您可能需要为不同的账户或工作负载创建和管理多个配置文件。 | AWS 管理员、云管理员 | 

### 配置本地 DNS 解析器以进行集成 AWS
<a name="configure-on-premises-dns-resolvers-for-aws-integration"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  在本地 DNS 解析器中配置条件转发。 | 要 AWS 从本地环境发送 DNS 查询以进行解析，您必须在本地 DNS 解析器中配置条件转发以指向入站终端节点 IP 地址。这指示 DNS 解析器将 AWS托管域（例如`prod.aws.example.com`）的所有 DNS 查询转发到入站终端节点 IP 地址，由 Route 53 解析器进行解析。 | 网络管理员 | 

### 在混合环境中验证 end-to-end DNS 解析
<a name="verify-end-to-end-dns-resolution-in-a-hybrid-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 测试从本地环境 AWS 到本地环境的 DNS 解析。 | 从已关联转发规则的 VPC 中的实例，对本地托管域名（例如 `db.onprem.example.com`）执行 DNS 查询。 | 网络管理员 | 
| 测试从本地环境到的 DNS 解析 AWS。 | 在本地服务器上，对 AWS托管域执行 DNS 解析（例如，对于`ec2.prod.aws.example.com`）。 | 网络管理员 | 

## 相关资源
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment-resources"></a>
+ [亚马逊 VPC 的混合云 DNS 选项](https://docs.aws.amazon.com/whitepapers/latest/hybrid-cloud-dns-options-for-vpc/hybrid-cloud-dns-options-for-vpc.html)（AWS 白皮书）
+ [使用私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html)（Route 53 文档）
+ [Route 53 Resolver 入门](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-getting-started.html)（Route 53 文档）
+ [使用 Route 53 解析器简化多账户环境中的 DNS 管理](https://aws.amazon.com/blogs/security/simplify-dns-management-in-a-multiaccount-environment-with-route-53-resolver/)（AWS 博客文章）
+ [使用带有多个 VPCs 和 AWS 账户（AWS 博客文章）的 Amazon Route 53 配置文件统一 DNS 管理](https://aws.amazon.com/blogs/aws/unify-dns-management-using-amazon-route-53-profiles-with-multiple-vpcs-and-aws-accounts/)
+ [将您的多账户 DNS 环境迁移到 Amazon Route 53 配置文件](https://aws.amazon.com/blogs/networking-and-content-delivery/migrating-your-multi-account-dns-environment-to-amazon-route-53-profiles/)（AWS 博客文章）
+ [将 Amazon Route 53 配置文件用于可扩展的多账户 AWS 环境](https://aws.amazon.com/blogs/networking-and-content-delivery/using-amazon-route-53-profiles-for-scalable-multi-account-aws-environments/)（AWS 博客文章）

 

# 验证 ELB 负载均衡器是否需 TLS 终止
<a name="verify-that-elb-load-balancers-require-tls-termination"></a>

*Priyanka Chaudhary，Amazon Web Services*

## Summary
<a name="verify-that-elb-load-balancers-require-tls-termination-summary"></a>

在亚马逊网络服务 (AWS) 云上，Elastic Load Balancing (ELB) 会自动将传入的应用程序流量分配到多个目标，例如亚马逊弹性计算云 (Amazon EC2) 实例、容器、IP 地址和 AWS Lambda 函数。负载均衡器使用侦听器定义负载均衡器用来接受来自用户的流量的端口和协议。应用程序负载均衡器在应用层做出路由决策并使用 HTTP/HTTPS 协议。经典负载均衡器使用 TCP 或安全套接字层 (SSL) 协议在传输层做出路由决策，或使用 HTTP/HTTPS 在应用层做出路由决策。

此模式提供了安全控制，用于检查应用程序负载均衡器和经典负载均衡器的多种事件类型。调用该函数时，AWS Lambda 会检查事件，并确保负载均衡器合规。

该函数通过以下 API 调用启动 Amazon Events CloudWatch 事件：[CreateLoadBalancer[CreateLoadBalancerListeners[DeleteLoadBalancerListeners](https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_DeleteLoadBalancerListeners.html)](https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_CreateLoadBalancerListeners.html)](https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_CreateLoadBalancer.html)、、[CreateLoadBalancerPolicy](https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_CreateLoadBalancerPolicy.html)、[SetLoadBalancerPoliciesOfListener](https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_SetLoadBalancerPoliciesOfListener.html)、[CreateListener](https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_CreateListener.html)、[DeleteListener](https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DeleteListener.html)、和[ModifyListener](https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_ModifyListener.html)。当事件检测到其中一个事件时 APIs，它会调用运行 Python 脚本的 AWS Lambda。Python 脚本会进行评估以查看侦听器是否包含 SSL 凭证，以及所应用的策略是否使用传输层安全性协议（TLS）。如果确定 SSL 策略不是 TLS，则该函数会向用户发送包含相关信息的 Amazon Simple Notiﬁcation Service (Amazon SNS) 通知。 

## 先决条件和限制
<a name="verify-that-elb-load-balancers-require-tls-termination-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户

**限制**
+ 若非对负载均衡器侦听器进行了更新，否则此安全控制不会检查现有的负载均衡器。
+ 这种安全控制为区域性的。您必须将它部署到要监控的每个 AWS 区域。

## 架构
<a name="verify-that-elb-load-balancers-require-tls-termination-architecture"></a>

**目标架构**

![\[确保负载均衡器需要 TLS 终止。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/da99cda2-ac34-4791-a2bd-d37264d8d3d9/images/af92b3c8-32bb-45eb-a2a8-d8276fb3e824.png)


**自动化和扩展**
+ 如果您使用的是 [AWS Organ](https://aws.amazon.com/organizations/) izations，则可以使用 [AWS Cloudformation StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) 在要监控的多个账户中部署此模板。

## 工具
<a name="verify-that-elb-load-balancers-require-tls-termination-tools"></a>

**AWS 服务**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) — AWS CloudFormation 可帮助您建模和设置 AWS 资源，快速一致地配置这些资源，并在资源的整个生命周期中对其进行管理。您可以使用模板来描述资源及其依赖关系，然后将它们作为堆栈一起启动和配置，而不必单独管理资源。
+ [Amazon CloudWatch ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) Events — Amazon CloudWatch Events 提供近乎实时的系统事件流，这些事件描述了 AWS 资源的变化。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) – AWS Lambda 是一项计算服务，支持无需预置或管理服务器即可运行代码。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一项高度可扩展的对象存储服务，可用于各种存储解决方案，包括网站、移动应用程序、备份和数据湖。
+ [Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) — Amazon Simple Notiﬁcation Service (Amazon SNS) 可协调和管理发布者和客户端之间消息的传送或发送，包括 Web 服务器和电子邮件地址。订阅用户接收所有发布至他们所订阅主题的消息，并且一个主题的所有订阅用户收到的消息都相同。

**代码**

此模式包括以下附件：
+ `ELBRequirestlstermination.zip` — 用于安全控制的 Lambda 代码。
+ `ELBRequirestlstermination.yml`— 用于设置事件和 Lambda 函数的 CloudFormation 模板。

## 操作说明
<a name="verify-that-elb-load-balancers-require-tls-termination-epics"></a>

### 设置 S3 存储桶
<a name="set-up-the-s3-bucket"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 定义 S3 存储桶。 | 在 [Amazon S3 控制台](https://console.aws.amazon.com/s3/)，选择或创建 S3 存储桶来托管 Lambda 代码 .zip 文件。此 S3 存储桶必须与要评估的负载均衡器位于同一 AWS 区域 中。S3 存储桶名称是全局唯一的，并且命名空间由所有 AWS 账户共享。S3 存储桶名称不得包含前导斜杠。 | 云架构师 | 
| 上传 Lambda 代码。 | 将*附件*部分中提供的 Lambda 代码（`ELBRequirestlstermination.zip` 文件）上传至 S3 存储桶。 | 云架构师 | 

### 部署 CloudFormation 模板
<a name="deploy-the-cloudformation-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动 AWS CloudFormation 模板。 | 在与您[的 S3 存储桶相同的 AWS 区域中打开 AWS CloudFormation 控制台](https://console.aws.amazon.com/cloudformation/)，然后部署所附的模板`ELBRequirestlstermination.yml`。有关部署 AWS CloudFormation 模板的更多信息，请参阅 CloudFormation 文档中的在 [AWS CloudFormation 控制台上创建堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)。 | 云架构师 | 
| 填写模板中的参数。 | 启动模板时，系统将会提示输入以下信息：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/verify-that-elb-load-balancers-require-tls-termination.html) | 云架构师 | 

### 确认订阅
<a name="confirm-the-subscription"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确认订阅。 |  CloudFormation 模板成功部署后，它会向您提供的电子邮件地址发送一封订阅电子邮件。您必须确认此电子邮件订阅，才能开始接收违规通知。 | 云架构师 | 

## 相关资源
<a name="verify-that-elb-load-balancers-require-tls-termination-resources"></a>
+ 在 [AWS CloudFormation 控制台上创建堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)（AWS CloudFormation 文档）
+ [什么是 AWS Lambda？](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) (AWS Lambda 文档)
+ [什么是经典负载均衡器？](https://docs.aws.amazon.com/elasticloadbalancing/latest/classic/introduction.html) （ELB 文档）
+ [什么是应用程序负载均衡器？](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html) （ELB 文档）

## 附件
<a name="attachments-da99cda2-ac34-4791-a2bd-d37264d8d3d9"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/da99cda2-ac34-4791-a2bd-d37264d8d3d9/attachments/attachment.zip)

# 使用 Splunk 查看 AWS Network Firewall 日志和指标
<a name="view-aws-network-firewall-logs-and-metrics-by-using-splunk"></a>

*Ivo Pinto，Amazon Web Services*

## Summary
<a name="view-aws-network-firewall-logs-and-metrics-by-using-splunk-summary"></a>

许多组织使用 [Splunk Enter](https://www.splunk.com/en_us/products/splunk-enterprise.html) prise 作为来自不同来源的日志和指标的集中聚合和可视化工具。 此模式可帮助您配置 Splunk，使其使用适用[于 AWS 的 Splunk 插件从[亚马逊 CloudWatch 日志](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)中获取 AWS Network Firew](https://docs.aws.amazon.com/network-firewall/latest/developerguide/what-is-aws-network-firewall.html) all 日志和指标。 

为此，您需要创建一个只读的 AWS Identity and Access Management（IAM）角色。适用于 AWS 的 Splunk 附加组件使用此角色进行访问 CloudWatch。您可以配置 AWS 的 Splunk 插件以从中 CloudWatch获取指标和日志。最后，您需要在 Splunk 中根据检索到的日志数据和指标来创建可视化。

## 先决条件和限制
<a name="view-aws-network-firewall-logs-and-metrics-by-using-splunk-prereqs"></a>

**先决条件**
+ 一个 [Splunk](https://www.splunk.com/) 账户
+ 一个 Splunk Enterprise 实例，版本 8.2.2 或更高版本 
+ 一个活跃的 AWS 账户
+ Network Firewall，[设置](https://docs.aws.amazon.com/network-firewall/latest/developerguide/getting-started.html)并[配置为](https://docs.aws.amazon.com/network-firewall/latest/developerguide/logging-cw-logs.html)向日志发送 CloudWatch 日志

**限制**
+ 必须将 Splunk Enterprise 作为一组 Amazon Elastic Compute Cloud（Amazon EC2）实例部署到 AWS 云端。
+ AWS 中国区域不支持使用自动为 Amazon EC2 发现的 IAM 角色来收集数据。

## 架构
<a name="view-aws-network-firewall-logs-and-metrics-by-using-splunk-architecture"></a>

![\[AWS Network Firewall 和 Splunk 日志记录架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/c6ce254a-841f-4bed-8f9f-b35e99f22e56/images/3dd420e9-70af-4a42-b24d-c54872c55e0b.png)


下图说明了以下内容：

1. Network Firewall 将日志发布到 CloudWatch 日志。

1. Splunk Enterprise 从中检索指标和日志。 CloudWatch

为了在此架构中填充示例指标和日志，一个工作负载会生成流量，这些流量将经过 Network Firewall 端点流向互联网。这是通过使用[路由表](https://docs.aws.amazon.com/network-firewall/latest/developerguide/vpc-config.html#vpc-config-route-tables)来实现的。 尽管此模式使用单个 Amazon EC2 实例作为工作负载，但只要将 Network Firewall 配置为向 CloudWatch 日志发送日志，这种模式就可以应用于任何架构。

此架构还使用了另一个虚拟私有云（VPC）中的一个 Splunk Enterprise 实例。但是，Splunk 实例可以位于其他位置，例如与工作负载位于同一个 VPC 中，前提是它可以到达。 CloudWatch APIs

## 工具
<a name="view-aws-network-firewall-logs-and-metrics-by-using-splunk-tools"></a>

**AWS 服务**
+ [Amazon CloudWatch Lo](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) gs 可帮助您集中管理来自所有系统、应用程序和 AWS 服务的日志，以便您可以监控它们并安全地将其存档。
+ [Amazon Elastic Compute Cloud（Amazon EC2）](https://docs.aws.amazon.com/ec2/)在 AWS 云提供了可扩展的计算容量。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [AWS Network Fire](https://docs.aws.amazon.com/network-firewall/latest/developerguide/what-is-aws-network-firewall.html) wall 是一项有状态的托管式网络防火墙以及入侵检测和防御服务，适用于 AWS 云 VPCs 中。

**其他工具**
+ [Splunk](https://www.splunk.com/) 可帮助您监控、可视化和分析日志数据。

## 操作说明
<a name="view-aws-network-firewall-logs-and-metrics-by-using-splunk-epics"></a>

### 创建一个 IAM 角色
<a name="create-an-iam-role"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 IAM 策略。 | 按照[使用 JSON 编辑器创建策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html#access_policies_create-json-editor)中的说明创建授予 CloudWatch 日志数据和 CloudWatch 指标只读访问权限的 IAM 策略。将如下策略粘贴到 JSON 编辑器中。<pre>{<br />    "Statement": [<br />        {<br />            "Action": [<br />                "cloudwatch:List*",<br />                "cloudwatch:Get*",<br />                "network-firewall:List*",<br />                "logs:Describe*",<br />                "logs:Get*",<br />                "logs:List*",<br />                "logs:StartQuery",<br />                "logs:StopQuery",<br />                "logs:TestMetricFilter",<br />                "logs:FilterLogEvents",<br />                "network-firewall:Describe*"<br />            ],<br />            "Effect": "Allow",<br />            "Resource": "*"<br />        }<br />    ],<br />    "Version": "2012-10-17"<br />}</pre> | AWS 管理员 | 
| 创建一个新的 IAM 角色。 | 按照[创建角色中的说明向 AWS 服务委派权限，创建适用于 AWS](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) 的 Splunk 附加组件访问 CloudWatch的 IAM 角色。对于**权限策略**，选择您之前创建的策略。 | AWS 管理员 | 
| 将此 IAM 角色分配给 Splunk 集群中的 EC2 实例。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/view-aws-network-firewall-logs-and-metrics-by-using-splunk.html) | AWS 管理员 | 

### 安装适用于 AWS 的 Splunk 附加组件
<a name="install-the-splunk-add-on-for-aws"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装此附加组件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/view-aws-network-firewall-logs-and-metrics-by-using-splunk.html) | Splunk 管理员 | 
| 配置 AWS 凭证。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/view-aws-network-firewall-logs-and-metrics-by-using-splunk.html)有关详情，请参阅 Splunk 文档中的[在您的 Splunk 平台实例内查找 IAM 角色](https://splunk.github.io/splunk-add-on-for-amazon-web-services/#Find_an_IAM_role_within_your_Splunk_platform_instance)。 | Splunk 管理员 | 

### 将 Splunk 的访问权限配置为 CloudWatch
<a name="configure-splunk-access-to-cloudwatch"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置从日志中检索 Network Firewall 日 CloudWatch 志。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/view-aws-network-firewall-logs-and-metrics-by-using-splunk.html)默认情况下，Splunk 每 10 分钟获取一次日志数据。这是**高级设置**下方的一个可配置参数。有关更多信息，请参阅 Splunk [文档中的使用 Splunk Web 配置 CloudWatch 日志输入](https://splunk.github.io/splunk-add-on-for-amazon-web-services/#Configure_a_CloudWatch_Logs_input_using_Splunk_Web)。 | Splunk 管理员 | 
| 配置从中检索 Network Firewall 指标 CloudWatch。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/view-aws-network-firewall-logs-and-metrics-by-using-splunk.html)默认情况下，Splunk 每 5 分钟获取一次指标数据。这是**高级设置**下方的一个可配置参数。有关更多信息，请参阅 Splunk [文档中的使用 Splunk Web 配置 CloudWatch 输入](https://splunk.github.io/splunk-add-on-for-amazon-web-services/#Configure_a_CloudWatch_input_using_Splunk_Web)。 | Splunk 管理员 | 

### 使用查询创建 Splunk 可视化
<a name="create-splunk-visualizations-by-using-queries"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看排名靠前的源 IP 地址。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/view-aws-network-firewall-logs-and-metrics-by-using-splunk.html) | Splunk 管理员 | 
| 查看数据包统计数据。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/view-aws-network-firewall-logs-and-metrics-by-using-splunk.html) | Splunk 管理员 | 
| 查看最常用的源端口。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/view-aws-network-firewall-logs-and-metrics-by-using-splunk.html) | Splunk 管理员 | 

## 相关资源
<a name="view-aws-network-firewall-logs-and-metrics-by-using-splunk-resources"></a>

**AWS 文档**
+ [创建向 AWS 服务委托权限的角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html)（IAM 文档）
+ [创建 IAM 策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create-console.html#access_policies_create-start)（IAM 文档）
+ [在 AWS Network Firewall 中进行日志记录和监控](https://docs.aws.amazon.com/network-firewall/latest/developerguide/logging-monitoring.html)（Network Firewall 文档）
+ [AWS Network Firewall 的路由表配置](https://docs.aws.amazon.com/network-firewall/latest/developerguide/route-tables.html)（Network Firewall 文档）

**AWS 博客文章**
+ [AWS Network Firewall 部署模式](https://aws.amazon.com/pt/blogs/networking-and-content-delivery/deployment-models-for-aws-network-firewall/)

**Amazon Web Services Marketplace**
+ [Splunk Enterprise 亚马逊机器映像（AMI）](https://aws.amazon.com/marketplace/pp/prodview-l6oos72bsyaks)

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

**Topics**
+ [使用会话管理器和 Amazon Instance Connect 访问堡垒主 EC2 机](access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.md)
+ [使用 AWS Fargate PrivateLink、AWS 和网络负载均衡器在 Amazon ECS 上私下访问容器应用程序](access-container-applications-privately-on-amazon-ecs-by-using-aws-fargate-aws-privatelink-and-a-network-load-balancer.md)
+ [使用 AWS PrivateLink 和 Network Load Balancer 在 Amazon ECS 上私密访问容器应用程序](access-container-applications-privately-on-amazon-ecs-by-using-aws-privatelink-and-a-network-load-balancer.md)
+ [使用本地微软 Active Direct AWS Managed Microsoft AD ory 集中解析 DNS](centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory.md)
+ [使用 AWS Amplify、Angular 和模块联合为微前端创建门户](create-amplify-micro-frontend-portal.md)
+ [使用私有端点和应用程序负载均衡器在内部网站上部署 Amazon API Gateway API](deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer.md)
+ [使用以下方法为公共子网部署基于侦探属性的访问控制 AWS Config](deploy-detective-attribute-based-access-controls-for-public-subnets-by-using-aws-config.md)
+ [为公有子网部署基于属性的预防性访问权限控制](deploy-preventative-attribute-based-access-controls-for-public-subnets.md)
+ [在 Amazon RDS 中为 PostgreSQL 数据库实例启用加密连接](enable-encrypted-connections-for-postgresql-db-instances-in-amazon-rds.md)
+ [使用 AWS Transit Gateway Connect 扩展 VRFs 到 AWS](extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.md)
+ [将 F5 BIG-IP 工作负载迁移到 F5 BIG-IP VE AWS 云](migrate-an-f5-big-ip-workload-to-f5-big-ip-ve-on-the-aws-cloud.md)
+ [启用 Amazon EKS 自动模式时迁移 NGINX 入口控制器](migrate-nginx-ingress-controller-eks-auto-mode.md)
+ [在非工作负载子网的多账户 VPC 设计中保留可路由的 IP 空间](preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets.md)
+ [使用服务控制策略在账户级别阻止访问互联网](prevent-internet-access-at-the-account-level-by-using-a-service-control-policy.md)
+ [将警报从 AWS Network Firewall 发送到 Slack 通道](send-alerts-from-aws-network-firewall-to-a-slack-channel.md)
+ [使用亚马逊通过 VPC 在 Amazon S3 存储桶中提供静态内容 CloudFront](serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront.md)
+ [使用 AWS 弹性灾难恢复为 Oracle JD Edwar EnterpriseOne ds 设置灾难恢复](set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.md)
+ [使用 BMC Discovery 查询提取迁移数据以进行迁移规划](use-bmc-discovery-queries-to-extract-migration-data-for-migration-planning.md)
+ [使用网络防火墙从出站流量的服务器名称指示（SNI）中捕获 DNS 域名](use-network-firewall-to-capture-the-dns-domain-names-from-the-server-name-indication-sni-for-outbound-traffic.md)

# 内容分发
<a name="contentdelivery-pattern-list"></a>

**Topics**
+ [使用 AWS Firewall Manager 和 Amazon Data Firehose 将 AWS WAF 日志发送到 Splunk](send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose.md)
+ [使用亚马逊通过 VPC 在 Amazon S3 存储桶中提供静态内容 CloudFront](serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront.md)
+ [更多模式](contentdelivery-more-patterns-pattern-list.md)

# 使用 AWS Firewall Manager 和 Amazon Data Firehose 将 AWS WAF 日志发送到 Splunk
<a name="send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose"></a>

*Michael Friedenthal、Aman Kaur Gandhi 和 JJ Johnson，Amazon Web Services*

## Summary
<a name="send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose-summary"></a>

一直以来，有两种方法可将数据移入 Splunk：推送架构或提取架构。*提取架构*通过重试为交付数据提供保障，但它需要 Splunk 中的专用资源来轮询数据。因轮询之故，提取架构通常不是实时的。*推送架构*通常具有更低的延迟性、更高的可扩展性，并且可以降低操作复杂性和成本。但是，其无法保证交付，通常需要代理。

Splunk 与 Amazon Data Firehose 集成，通过 HTTP 事件收集器（HEC）向 Splunk 传送实时流数据。此集成带来了推送架构和提取架构的优势，确保通过重试进行数据传输，近实时，延迟低、复杂性低。HEC 通过 HTTP 或 HTTPS 快速高效地将数据直接发送到 Splunk。 HECs 是基于令牌的，因此无需在应用程序或支持文件中对凭据进行硬编码。

在 AWS Firewall Manager 策略中，您可以为所有账户中的所有 AWS WAF Web ACL 流量配置日志记录，然后可以使用 Firehose 传输流将该日志数据发送到 Splunk 进行监控、可视化和分析。该解决方案具有以下优势：
+ 集中管理和记录所有账户中的 AWS WAF Web ACL 流量
+ Splunk 与单一集成 AWS 账户
+ 可扩展性
+ 日志数据的近实时传送
+ 成本已经无服务器解决方案优化，因此您无需为未使用的资源付费。

## 先决条件和限制
<a name="send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose-prereqs"></a>

**先决条件**
+ 属于组织 AWS 账户 成员的活跃分子 AWS Organizations。
+ 您必须拥有以下权限才能使用 Firehose 启用日志记录：
  + `iam:CreateServiceLinkedRole`
  + `firehose:ListDeliveryStreams`
  + `wafv2:PutLoggingConfiguration`
+ AWS WAF 并且 ACLs 必须对其网络进行配置。有关说明，请参阅[入门 AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started.html)。
+ AWS Firewall Manager 必须进行设置。有关说明，请参阅 [AWS Firewall Manager 先决条件](https://docs.aws.amazon.com/waf/latest/developerguide/fms-prereq.html)。
+  AWS WAF 必须配置的 Firewall Manager 安全策略。有关说明，请参阅[AWS Firewall ManagerAWS WAF 策略入门](https://docs.aws.amazon.com/waf/latest/developerguide/getting-started-fms.html)。
+ 必须设置 Splunk，并配置可通过 Firehose 访问的公有 HTTP 端点。

**限制**
+  AWS 账户 必须在中的单个组织中进行管理 AWS Organizations。
+ Web ACL 必须与传输流位于同一区域。如果您要为亚马逊捕获日志 CloudFront，请在美国东部（弗吉尼亚北部）地区创建 Firehose 传送流。`us-east-1`
+ 适用于 Firehose 的 Splunk 附加组件可用于付费 Splunk Cloud 部署、分布式 Splunk Enterprise 部署和单实例 Splunk Enterprise 部署。该附加组件不支持免费试用 Splunk Cloud 部署。

## 架构
<a name="send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose-architecture"></a>

**目标技术堆栈**
+ Firewall Manager
+ Firehose
+ Amazon Simple Storage Service（Amazon S3）
+ AWS WAF
+ Splunk

**目标架构 **

下图显示了如何使用防火墙管理器集中记录所有 AWS WAF 数据并通过 Firehose 将其发送到 Splunk。

![\[架构图显示了通过 Amazon Data Firehose 将 AWS WAF 日志数据发送到 Splunk 的架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/3dfeaae0-985a-42b8-91c4-ece081f0b51b/images/669169b1-caa4-419b-9988-19806ded54eb.png)


1.  AWS WAF 网络 ACLs 向 Firewall Manager 发送防火墙日志数据。

1. Firewall Manager 将日志数据发送至 Firehose。

1. Firehose 传输流将日志数据转发至 Splunk 和 S3 存储桶。当 Firehose 传输流出现错误时，S3 存储桶可充当备份。

**自动化和扩缩**

该解决方案旨在扩展和适应组织 ALCs 内的所有 AWS WAF Web。您可以将所有网络配置 ACLs 为使用相同的 Firehose 实例。但是，如果您想设置和使用多个 Firehose 实例，则可以这样操作。

## 工具
<a name="send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose-tools"></a>

**AWS 服务**
+ [AWS Firewall Manager](https://docs.aws.amazon.com/waf/latest/developerguide/fms-chapter.html)是一项安全管理服务，可帮助您在中的账户和应用程序中集中配置和管理防火墙规则 AWS Organizations。
+ [Amazon Data Firehose](https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html) 可帮助您将实时[流数据传输](https://aws.amazon.com/streaming-data/)到受支持的第三方服务提供商（例如 Splunk）拥有的其他 AWS 服务自定义 HTTP 终端节点和 HTTP 终端节点。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html) 是一种 Web 应用程序防火墙，可帮助您监控转发至受保护 Web 应用程序资源的 HTTP 和 HTTPS 请求。

**其他工具**
+ [Splunk](https://docs.splunk.com/Documentation) 可帮助您监控、可视化和分析日志数据。

## 操作说明
<a name="send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose-epics"></a>

### 配置 Splunk
<a name="configure-splunk"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装适用于 Splunk 的应用程序。 AWS | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose.html) | 安全管理员、Splunk 管理员 | 
| 安装的附加组件 AWS WAF。 | 重复前述说明，以安装适用于 Splunk 的 **AWS Web 应用程序防火墙附加组件**。 | 安全管理员、Splunk 管理员 | 
| 为 Firehose 安装并配置 Splunk 附加组件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose.html) | 安全管理员、Splunk 管理员 | 

### 创建 Firehose 传输流
<a name="create-the-akf-delivery-stream"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 授予 Firehose 访问 Splunk 目的地的权限。 | 配置访问策略，允许 Firehose 访问 Splunk 目标并将日志数据备份至 S3 存储桶。有关更多信息，请参阅[授予 Firehose 进入 Splunk 目的地的权限](https://docs.aws.amazon.com/firehose/latest/dev/controlling-access.html#using-iam-splunk)。 | 安全管理员 | 
| 创建 Firehose 传输流。 | 在您管理网页 ACLs 的同一个账户中 AWS WAF，在 Firehose 中创建传送流。创建传输流时，您需要拥有 IAM 角色。Firehose 承担该 IAM 角色，并获得对指定 S3 存储桶的访问权限。有关说明，请参阅[创建传输流](https://docs.aws.amazon.com/firehose/latest/dev/basic-create.html)。注意以下几点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose.html)对您在 HTTP 事件收集器中配置的每个令牌重复此过程。 | 安全管理员 | 
| 测试传输流。 | 测试传输流以验证配置是否正确。有关说明，请参阅 Firehose 文档中的[使用 Splunk 作为目标进行测试](https://docs.aws.amazon.com/firehose/latest/dev/test-drive-firehose.html#test-drive-destination-splunk)。 | 安全管理员 | 

### 将 Firewall Manager 配置为记录数据
<a name="configure-firewall-manager-to-log-data"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置 Firewall Manager 策略。 | 必须将 Firewall Manager 策略配置为：启用日志记录并将日志转发至正确的 Firehose 传输流。有关更多信息和说明，请参阅[为 AWS WAF 策略配置日志记录](https://docs.aws.amazon.com/waf/latest/developerguide/waf-policies.html#waf-policies-logging-config)。 | 安全管理员 | 

## 相关资源
<a name="send-aws-waf-logs-to-splunk-by-using-aws-firewall-manager-and-amazon-data-firehose-resources"></a>

**AWS resources**
+ [记录 Web ACL 流量](https://docs.aws.amazon.com/waf/latest/developerguide/logging.html)（AWS WAF 文档）
+ [为 AWS WAF 策略配置日志记录](https://docs.aws.amazon.com/waf/latest/developerguide/waf-policies.html#waf-policies-logging-config)（AWS WAF 文档）
+ [教程：使用 Amazon Data Firehose 向 Splunk 发送 VPC 流日志](https://docs.aws.amazon.com/firehose/latest/dev/vpc-splunk-tutorial.html)（Firehose 文档）
+ [如何使用 Amazon Data Firehose 向 Splunk 推送 VPC 流日志？](https://aws.amazon.com/premiumsupport/knowledge-center/push-flow-logs-splunk-firehose/) （AWS 知识中心）
+ [使用 Amazon Data Firehose 支持向 Splunk 摄取数据（博客文章](https://aws.amazon.com/blogs/big-data/power-data-ingestion-into-splunk-using-amazon-kinesis-data-firehose/)）AWS 

**Splunk 文档**
+ [适用于 Amazon Data Firehose 的 Splunk 附加组件](https://docs.splunk.com/Documentation/AddOns/released/Firehose/About)

# 使用亚马逊通过 VPC 在 Amazon S3 存储桶中提供静态内容 CloudFront
<a name="serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront"></a>

*Angel Emmanuel Hernandez Cebrian，Amazon Web Services*

## Summary
<a name="serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront-summary"></a>

当您提供托管在亚马逊网络服务 (AWS) 上的静态内容时，推荐的方法是使用亚马逊简单存储服务 (S3) Simple Service 存储桶作为来源，然后使用 CloudFront 亚马逊来分发内容。该解决方案有两个主要优点：便于在边缘位置缓存静态内容，以及能够为 CloudFront 分发定义 [Web 访问控制列表](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl.html) (Web ACLs)，这有助于您以最小的配置和管理开销保护对内容的请求。

然而，标准推荐方法有一个常见的架构限制。在某些环境中，您希望部署在虚拟私有云（VPC）中的虚拟防火墙设备检查所有内容，包括静态内容。标准方法不通过 VPC 路由流量进行检查。此模式提供了另一种架构解决方案。您仍然使用 CloudFront 分配在 S3 存储桶中提供静态内容，但是流量是使用 Application Load Balancer 通过 VPC 路由的。然后，AWS Lambda 函数从 S3 存储桶检索并返回内容。

## 先决条件和限制
<a name="serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account。
+ S3 存储桶中托管的静态网站内容。

**限制**
+ 这种模式中的资源必须位于单个 AWS 区域 ，但可以在不同的 Amazon Web Services account 中进行预调配。
+ 限制分别适用于 Lambda 函数可以接收和发送的最大请求与响应大小。有关更多信息，请参阅 [Lambda 函数作为目标](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html)中的*限制*（弹性负载均衡文档）。
+ 使用此方法时，在性能、可扩展性、安全性和成本效益之间找到良好的均衡非常重要。尽管 Lambda 具有很高的可扩展性，但如果并发 Lambda 调用数量超过最大限额，某些请求会受到限制。有关更多信息，请参阅 Lambda 限额（Lambda 文档）。在使用 Lambda 时，您还需考虑定价。要最大限度地减少 Lambda 调用，请确保正确定义分配的缓存。 CloudFront 有关更多信息，请参阅[优化缓存和可用性](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ConfiguringCaching.html)（CloudFront 文档）。

## 架构
<a name="serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront-architecture"></a>

**目标技术堆栈**
+ CloudFront
+ Amazon Virtual Private Cloud（Amazon VPC）
+ 应用程序负载均衡器
+ Lambda
+ Amazon S3

**目标架构**

下图显示了当您需要使用 CloudFront 通过 VPC 从 S3 存储桶提供静态内容时建议的架构。

![\[通过 VPC 中的应用程序负载均衡器到达 Lambda 函数的流量。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e0dd6928-4fe0-47ab-954f-9de5563349d8/images/b42c7dd9-4a72-4998-bf88-195c8f90ed3e.png)


1. 客户端请求 CloudFront 分发 URL 以获取 S3 存储桶中的特定网站文件。

1. CloudFront 将请求发送到 AWS WAF。AWS WAF 使用 ACLs 应用于分配的 Web 来筛选请求。 CloudFront 如果确定请求有效，则流程继续。如果请求被确定为无效，客户端会收到 403 错误。

1. CloudFront 检查其内部缓存。如果存在与传入请求匹配的有效密钥，则关联的值将作为响应发送回客户端。否则，流程将继续。

1. CloudFront 将请求转发到指定的 Application Load Balancer 的 URL。

1. 应用程序负载均衡器有一个与基于 Lambda 函数目标组关联的侦听器。应用程序负载均衡器调用 Lambda 函数。

1. Lambda 函数连接至 S3 存储桶，对其执行 `GetObject` 操作，然后将内容作为响应返回。

**自动化和扩展**

要使用这种方法自动部署静态内容，请创建 CI/CD 管道来更新托管网站的 Amazon S3 存储桶。

Lambda 函数会在服务的限额和限制范围内自动扩缩以处理并发请求。有关更多信息，请参阅 [Lambda 函数扩展](https://docs.aws.amazon.com/lambda/latest/dg/invocation-scaling.html)和 [Lambda 限额](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html)（Lambda 文档）。对于其他 AWS 服务和功能，例如 CloudFront 和 Application Load Balancer，AWS 会自动对其进行扩展。

## 工具
<a name="serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront-tools"></a>
+ [Amazon](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) 通过全球数据中心网络交付您的网页内容，从而降低延迟并提高性能，从而 CloudFront加快网络内容的分发。
+ [弹性负载均衡（ELB）](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html)将传入的应用程序或网络流量分发到多个目标。在这种模式中，您可使用通过弹性负载均衡预调配的[应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html)，将流量引导到 Lambda 函数。
+ [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 Virtual Private Cloud (Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) 可帮助您将 AWS 资源启动到您定义的虚拟网络中。此虚拟网络类似于您在自己的数据中心内运行的传统网络，具有使用 AWS 可扩展基础设施的优势。

## 操作说明
<a name="serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront-epics"></a>

### 用于通过 VPC 提供 CloudFront 来自 Amazon S3 的静态内容
<a name="use-cloudfront-to-serve-static-content-from-amazon-s3-through-a-vpc"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 VPC。 | 创建一个 VPC 以托管在此模式中部署的资源，例如应用程序负载均衡器和 Lambda 函数。 有关说明，请参阅[创建 VPC](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html#Create-VPC)（Amazon VPC 文档）。 | 云架构师 | 
| 创建 AWS WAF web ACL。 | 创建 AWS WAF web ACL。稍后在此模式中，您将此 Web ACL 应用于 CloudFront 分发。有关说明，请参阅[创建 Web ACL](https://docs.aws.amazon.com/waf/latest/developerguide/web-acl-creating.html)（AWS WAF 文档）。 | 云架构师 | 
| 创建 Lambda 函数。 | 创建 Lambda 函数，将 S3 存储桶中托管的静态内容以网站形式提供。使用此模式的[其他信息](#serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront-additional)部分中提供的代码。自定义代码，以识别您的目标 S3 存储桶。 | 常规 AWS | 
| 上传 Lambda 函数。 | 输入以下命令将 Lambda 函数代码上传至 Lambda 中的 .zip 文件存档中。<pre>aws lambda update-function-code \<br />--function-name  \ <br />--zip-file fileb://lambda-alb-s3-website.zip</pre> | 常规 AWS | 
| 创建应用程序负载均衡器。 | 创建指向 Lambda 函数的面向互联网的应用程序负载均衡器。有关说明，请参阅[为 Lambda 函数创建目标组](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html#register-lambda-function)（弹性负载均衡文档）。要实现高可用性配置，请创建应用程序负载均衡器并将其连接至不同可用区中的私有子网。 | 云架构师 | 
| 创建分 CloudFront 配。 | 创建指向您创建的 Application Load Balancer 的分 CloudFront 配。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront.html) | 云架构师 | 

## 相关资源
<a name="serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront-resources"></a>

**AWS 文档**
+ [优化缓存和可用性](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/ConfiguringCaching.html)（CloudFront 文档）
+ [Lambda 函数作为目标](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/lambda-functions.html)（弹性负载均衡文档）
+ [Lambda 限额](https://docs.aws.amazon.com/lambda/latest/dg/gettingstarted-limits.html)（Lambda 文档）

**Amazon Web Services 网站**
+ [应用程序负载均衡器](https://aws.amazon.com/es/elasticloadbalancing/application-load-balancer/)
+ [Lambda](https://aws.amazon.com/en/lambda/)
+ [CloudFront](https://aws.amazon.com/en/cloudfront/)
+ [Amazon S3](https://aws.amazon.com/en/s3/)
+ [AWS WAF](https://aws.amazon.com/en/waf/)
+ [Amazon VPC](https://aws.amazon.com/en/vpc/)

## 附加信息
<a name="serve-static-content-in-an-amazon-s3-bucket-through-a-vpc-by-using-amazon-cloudfront-additional"></a>

**代码**

下面的 Lambda函数示例是用 Node.js 编写而成。此 Lambda 函数充当 Web 服务器，对包含网站资源的 S3 存储桶执行 `GetObject` 操作。

```
/**

 * This is an AWS Lambda function created for demonstration purposes.

 * It retrieves static assets from a defined Amazon S3 bucket.

 * To make the content available through a URL, use an Application Load Balancer with a Lambda integration.
 * 
 * Set the S3_BUCKET environment variable in the Lambda function definition.
 */

var AWS = require('aws-sdk');

exports.handler = function(event, context, callback) {

    var bucket = process.env.S3_BUCKET;    
    var key = event.path.replace('/', '');
    
    if (key == '') {
        key = 'index.html';
    }

    // Fetch from S3
    var s3 = new AWS.S3();
    return s3.getObject({Bucket: bucket, Key: key},
       function(err, data) {

            if (err) {
                return err;
            }

            var isBase64Encoded = false;
            var encoding = 'utf8';
            
            if (data.ContentType.indexOf('image/') > -1) {
                isBase64Encoded = true;
                encoding = 'base64'
            }
    
            var resp = {
                statusCode: 200,
                headers: {
                    'Content-Type': data.ContentType,
                },
                body: new Buffer(data.Body).toString(encoding),
                isBase64Encoded: isBase64Encoded
            };

            callback(null, resp);
        }
    );
};
```

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

**Topics**
+ [查看亚马逊 CloudFront 分配的访问日志、HTTPS 和 TLS 版本](check-an-amazon-cloudfront-distribution-for-access-logging-https-and-tls-version.md)
+ [在 Amazon EKS 集群上部署基于 gRPC 的应用程序并使用应用程序负载均衡器访问它](deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer.md)
+ [为公有子网部署基于属性的预防性访问权限控制](deploy-preventative-attribute-based-access-controls-for-public-subnets.md)
+ [使用 Terraform 在 AWS Wavelength 区域中部署资源](deploy-resources-wavelength-zone-using-terraform.md)
+ [使用 Terraform 为 AWS WAF 解决方案部署安全自动化](deploy-the-security-automations-for-aws-waf-solution-by-using-terraform.md)
+ [为基于单元的架构设置无服务器单元路由器](serverless-cell-router-architecture.md)
+ [将 Amazon Q 开发者版用作编码助手来提高工作效率](use-q-developer-as-coding-assistant-to-increase-productivity.md)
+ [使用 Splunk 查看 AWS Network Firewall 日志和指标](view-aws-network-firewall-logs-and-metrics-by-using-splunk.md)