

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

# 开发人员工具
<a name="developer-tools-pattern-list"></a>

**Topics**
+ [DevOps](devops-pattern-list.md)
+ [Infrastructure](infrastructure-pattern-list.md)
+ [Web 应用程序和移动应用程序](websitesandwebapps-pattern-list.md)

# DevOps
<a name="devops-pattern-list"></a>

**Topics**
+ [MLOps 使用后台和自助服务 Amazon A SageMaker I 模板加速](accelerate-mlops-with-backstage-and-sagemaker-templates.md)
+ [使用 Amazon Bedrock 实现 AWS 基础设施运营自动化](automate-aws-infrastructure-operations-by-using-amazon-bedrock.md)
+ [使用 Terraform 在负载平衡器端点发生变化时自动 CloudFront 更新](automate-cloudfront-updates-when-load-balancer-endpoints-change.md)
+ [使用 GitHub 操作在亚马逊自动 CodeGuru 审查 AWS CDK Python 应用程序](automate-amazon-codeguru-reviews-for-aws-cdk-python-applications.md)
+ [使用 GitHub Actions、Artifactory 和 Terraform 在多存储库设置中自动部署 AWS Supply Chain 数据湖](automate-the-deployment-of-aws-supply-chain-data-lakes.md)
+ [自动执行 AWS 资源评测](automate-aws-resource-assessment.md)
+ [使用开源工具自动安装 SAP 系统](install-sap-systems-automatically-by-using-open-source-tools.md)
+ [使用 AWS CDK 自动部署 AWS Service Catalog 产品组合与产品](automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.md)
+ [使用和自动进行动态管道管理，以便在 Gitflow 环境中部署修补程序解决方案 AWS Service Catalog AWS CodePipeline](automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.md)
+ [自动删除 AWS CloudFormation 堆栈和相关资源](automate-deletion-cloudformation-stacks-associated-resources.md)
+ [使用 Terraform 在 Amazon Managed Grafana 上自动摄取和可视化 Amazon MWAA 自定义指标](automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.md)
+ [使用 AWS CodePipeline 和 AWS 自动部署堆栈集 CodeBuild](automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.md)
+ [使用云托管人和 AWS CDK 将适用于 Systems Manager 的 AWS 托管策略自动附加到 EC2 实例配置文件](automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.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)
+ [使用 AWS CodeCommit、AWS 和 AWS Device Farm 构建和测试 iOS 应用程序 CodePipeline](build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm.md)
+ [为在 Amazon EKS 上运行的应用程序配置双向 TLS 身份验证](configure-mutual-tls-authentication-for-applications-running-on-amazon-eks.md)
+ [使用自动创建 Amazon WorkSpaces 应用程序资源 AWS CloudFormation](automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation.md)
+ [使用 Firelens 日志路由器为 Amazon ECS 创建自定义日志解析器](create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.md)
+ [使用 GitHub Actions 和 Terragrunt 创建由 API 驱动的资源编排框架](create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.md)
+ [使用操作为 Terraform 托管的基础架构创建自动拉 AWS 取请求 GitHub](create-automated-pull-requests-for-terraform-managed-aws-infrastructure.md)
+ [自动为 Java 和 Python 项目创建动态 CI 管道](create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.md)
+ [使用 Terraf CloudWatch orm 部署 Synthetics 加那利群岛](deploy-cloudwatch-synthetics-canaries-by-using-terraform.md)
+ [部署 ChatOps 解决方案来管理 SAST 扫描结果，方法是在聊天应用程序中使用 Amazon Q Developer 自定义操作和 CloudFormation](deploy-chatops-solution-to-manage-sast-scan-results.md)
+ [通过 Terraform 在 Amazon Bedrock 上使用 CrewAI 框架部署代理式系统](deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.md)
+ [使用 AWS CodePipeline CI/CD 管道部署 AWS Glue 作业](deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline.md)
+ [使用 AWS CodePipeline、AWS 和 AWS 在多个 AWS CodeCommit 区域部署代码 CodeBuild](deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild.md)
+ [将工作负载从 Azure DevOps 管道部署到私有的 Amazon EKS](deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.md)
+ [使用 Terraform 执行 Amazon Redshift SQL 查询](execute-redshift-sql-queries-using-terraform.md)
+ [将 AWS Organizations 中整个组织的 AWS Backup 报告导出为 CSV 文件](export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.md)
+ [将亚马逊 EC2 实例列表的标签导出到 CSV 文件](export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file.md)
+ [使用 Troposphere 生成包含 AWS Config 托管规则的 AWS CloudFormation 模板](generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere.md)
+ [为 SageMaker 笔记本实例提供对另一个 AWS 账户中 CodeCommit 存储库的临时访问权限](give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.md)
+ [为多 DevOps 账户环境实施 GitHub Flow 分支策略](implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.md)
+ [为多账户环境实施 Gitflow 分支策略 DevOps](implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.md)
+ [为多 DevOps 账户环境实施中继分支策略](implement-a-trunk-branching-strategy-for-multi-account-devops-environments.md)
+ [在部署 AWS 基础设施之前，实施集中式自定义 Checkov 扫描以强制执行策略](centralized-custom-checkov-scanning.md)
+ [通过 K8sGPT 和 Amazon Bedrock 集成，实施人工智能驱动的 Kubernetes 诊断和问题排查](implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration.md)
+ [自动检测变化并为 monorepo 启动不同的 CodePipeline 管道 CodeCommit](automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.md)
+ [使用 AWS 将 Bitbucket 存储库与 AWS Amplify 集成 CloudFormation](integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.md)
+ [使用 Step Functions 和 Lambda 代理函数在 AWS 账户上启动 CodeBuild 项目](launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.md)
+ [使用应用程序恢复控制器管理 EMR 集群的多可用区失效转移](multi-az-failover-spark-emr-clusters-arc.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 和 AWS CloudFormation Config 监控亚马逊 ECR 存储库的通配符权限](monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config.md)
+ [使用 AWS CDK 和 GitHub 操作工作流程优化多账户无服务器部署](optimize-multi-account-serverless-deployments.md)
+ [使用 GitHub 操作基于 AWS CloudFormation 模板配置 AWS Service Catalog 产品](provision-aws-service-catalog-products-using-github-actions.md)
+ [通过部署角色自动分配机器解决方案，预调配最低权限 IAM 角色](provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.md)
+ [将亚马逊 CloudWatch 指标发布到 CSV 文件](publish-amazon-cloudwatch-metrics-to-a-csv-file.md)
+ [使用 AWS Lambda 自动化功能 AWS 账户 从 AWS Managed Microsoft AD 正面移除 Amazon EC2 条目](remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.md)
+ [使用 AWS Lambda 自动化功能 AWS 账户 从 AWS Managed Microsoft AD 中移除 Amazon EC2 条目](remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.md)
+ [AWS Glue 使用 pytest 框架对 Python ETL 作业运行单元测试](run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.md)
+ [使用 AWS CodePipeline 和 AWS CDK 设置 CI/CD 管道](set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.md)
+ [使用 Terraform 设置企业级规模的集中式日志记录](set-up-centralized-logging-at-enterprise-scale-by-using-terraform.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)
+ [使用自动化工作流简化 Amazon Lex 机器人的开发和部署](streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.md)
+ [使用 AWS Fargate WaitCondition 挂钩构造协调资源依赖关系和任务执行](use-the-aws-fargate-waitcondition-hook-construct.md)
+ [在 AWS 中使用第三方 Git 源存储库 CodePipeline](use-third-party-git-source-repositories-in-aws-codepipeline.md)
+ [使用 AWS 创建用于验证 Terraform 配置的 CI/CD 管道 CodePipeline](create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.md)
+ [更多模式](devops-more-patterns-pattern-list.md)

# MLOps 使用后台和自助服务 Amazon A SageMaker I 模板加速
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates"></a>

*Ashish Bhatt、Shashank Hirematt 和 Shivanshu Suryakar，Amazon Web Services*

## Summary
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-summary"></a>

使用机器学习运营 (MLOps) 系统的组织在扩展、标准化和保护其机器学习基础架构方面面临重大挑战。这种模式引入了一种变革性方法，它将开源开发者门户 [Backstag](https://backstage.io/) e 与 A [mazon SageMaker AI](https://aws.amazon.com/sagemaker/) 和强化基础设施即代码 (IaC) 模块相结合，以改善数据科学团队开发、部署和管理机器学习工作流程的方式。

此模式的 IaC 模块在 GitHub [AWS AIOps 模块](https://github.com/awslabs/aiops-modules/tree/main/modules/sagemaker)存储库中提供。这些模块提供了用于设置 ML 基础设施和创建一致的 ML 环境的预建模板。但是，数据科学家往往难以直接使用这些模板，因为這些模板需要基础设施专业知识。添加 Backstage 之类的开发人员门户为数据科学家提供了一种用户友好的途径，无需了解底层基础设施细节即可部署标准化 ML 环境。

通过将 Backstage 用作自助服务平台并集成预配置的 SageMaker AI 模板，您可以：
+ 缩短 AI 计划的价值实现时间。
+ 帮助实施一致的安全和治理。
+ 为数据科学家提供标准化、合规的环境。
+ 降低运营开销和基础设施复杂性。

这种模式提供了一种解决关键挑战的 MLOps 解决方案，还提供了一个可扩展、可重复的框架，在保持组织标准的同时实现创新。

**目标受众**

这种模式适用于组织内参与 ML、云架构和平台工程的广泛受众。这包括：
+ 想要实现 ML 工作流部署标准化和自动化的 **ML 工程师**。
+ 想要自助访问已预配置且合规的 ML 环境的**数据科学家**。
+ 负责构建和维护内部开发者平台和共享基础设施的**平台工程师**。
+ 为其设计可扩展、安全且经济实惠的云解决方案的云@@ **架构**师 MLOps。
+ DevOps 有兴趣将持续集成和持续交付 (CI/CD) 实践扩展到机器学习基础架构配置和工作流程的@@ **工程师**。
+ 监督 ML 计划并希望提高团队生产力、治理和上市时间的**技术主管和经理**。

有关 MLOps 挑战、 SageMaker AI MLOps 模块以及此模式提供的解决方案如何满足您的机器学习团队需求的更多信息，请参阅 “[其他信息](#accelerate-mlops-with-backstage-and-sagemaker-templates-additional)” 部分。

## 先决条件和限制
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-prereqs"></a>

**先决条件**
+ AWS Identity and Access Management (IAM) [角色和权限](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#prerequisites)，用于将资源配置到您的 AWS 账户
+ 了解 A [mazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated.html)、[SageMaker 项目](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-projects-whatis.html)、[SageMaker 管道](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-overview.html)和[SageMaker 模型注册表](https://docs.aws.amazon.com/sagemaker/latest/dg/model-registry.html)的概念
+ 了解 IaC 原理并有使用 [AWS Cloud Development Kit (AWS CDK)](https://aws.amazon.com/cdk/) 之类工具的经验

**限制**
+ **模板覆盖范围有限**。目前，该解决方案仅支持更广泛的[AIOps 解决方案](https://github.com/awslabs/aiops-modules)中 SageMaker 与 AI 相关的 AIOps 模块。其他模块，例如亚马逊 Elastic Kubernetes Service（亚马逊 EKS）上的 Ray MLflow、Apache Airflow 以及亚马逊 Bedrock 的微调，尚未作为后台模板提供。
+ **不可配置的默认设置**。模板使用 AIOps SageMaker 模块中的固定默认配置，无需自定义。您无法通过 Backstage 界面修改实例类型、存储大小、网络配置或安全策略，这限制了特定使用案例的灵活性。
+ **仅支持AWS**。该平台专为 AWS 部署而设计，不支持多云场景。在外部使用云服务的组织 AWS 云 不能使用这些模板来满足其机器学习基础架构需求。
+ **手动凭证管理** 您必须为每个部署手动提供 AWS 证书。此解决方案不提供与企业身份提供商的集成 AWS IAM Identity Center，也不提供自动凭证轮换。
+ **生命周期管理有限**。这些模板缺少全面的资源生命周期管理功能，例如自动清理策略、成本优化建议和基础设施偏差检测。创建后，您必须手动管理和监控部署的资源。

## 架构
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-architecture"></a>

下图显示了统一开发者门户的解决方案架构，该门户通过跨环境的 SageMaker AI 来标准化和加速机器学习基础架构的部署。

![\[包含后台、CNOE、Actions 和 Seed-Farmer 的统一开发者门户架构。 GitHub\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/c16160cf-d637-423e-93a7-485ffbb28646/images/233adab3-83cf-42f3-a1de-72d0b8ade5ae.png)


在此架构中：

1. [AWS 应用程序现代化蓝图](https://github.com/aws-samples/appmod-blueprints.git)将基础设施设置配置为 [Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) 集群作为[云原生卓越运营 (CNOE)](https://cnoe.io/) 框架的基础。这个全面的解决方案通过提供可扩展的内部开发者平台（IDP）来解决复杂的云原生基础设施管理挑战。这些蓝图提供了一种结构化的方法来建立强大、灵活的基础设施，以适应您不断变化的组织需求。

1. CNOE 开源框架通过统一的平台工程方法整合 DevOps 工具并解决生态系统碎片化问题。通过整合不同的工具和技术，简化了云原生开发的复杂格局，使您的团队可以专注于创新而非工具链管理。该框架提供了一种用于选择、集成和管理开发工具的标准化方法。

1. 在 CNOE 中，Backstage 作为 out-of-the-box解决方案部署在 Amazon EKS 集群中。Backstage 捆绑了通过 [Keycloak](https://www.keycloak.org/) 实现的强大身份验证和通过 [Argo CD](https://argo-cd.readthedocs.io/en/stable/) 实现的全面部署工作流。该集成平台创建了一个用于管理开发流程的集中式环境，并为团队提供了在多个环境中访问、部署和监控其基础设施和应用程序的单一场所。

1.  GitHub 存储库包含涵盖整个 SageMaker AI 生命周期的预配置 AIOps 软件模板。这些模板可满足关键的机器学习基础架构需求，包括 SageMaker Studio 配置、模型训练、推理管道和模型监控。这些模板可帮助您加速 ML 计划，并确保不同项目和团队之间的一致性。

1. GitHub A@@ [c](https://github.com/features/actions) tions 实现了一个自动化工作流程，该工作流程通过 [Seed-Farmer](https://github.com/awslabs/seed-farmer) 实用程序动态触发资源配置。这种方法将 Backstage 目录与 AIOps 模块存储库集成，并创建了简化的基础架构部署流程。自动化减少了手动干预，最大限度地减少了人为错误，并确保在不同的环境中快速、一致地创建基础设施。

1. [AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 可帮助您以代码形式定义和预调配基础设施，并确保在指定 AWS 账户内进行可重复、安全且合规的资源部署。这种方法以最少的人工干预提供了最大限度的治理，因此您可以创建易于进行复制、版本控制和审计的标准化基础设施模板。

## 工具
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-tools"></a>

**AWS 服务**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)是一个软件开发框架，可帮助您在代码中定义和配置 AWS 云 基础架构。
+ [亚马逊 Elastic Kubernetes Service（亚马逊](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。
+ [Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/) 是一项托管机器学习服务，可帮助您构建和训练机器学习模型，然后将其部署到可用于生产的托管环境中。

**其他工具**
+ [Backstage](https://backstage.io/) 是一个开源框架，可帮助您构建内部开发者门户。
+ GitHub Actions 是一个自动@@ [执行](https://github.com/features/actions)软件开发工作流程的 CI/CD 平台，包括构建、测试和部署代码等任务。

**代码存储库**

此模式使用来自以下 GitHub 存储库的代码和模板：
+ [AIOps 带有后台存储库的内部开发者平台 (IDP)](https://github.com/aws-samples/sample-aiops-idp-backstage/)
+ SageMaker 来自模块存储库的 AI 相关[AWS AIOps 模块](https://github.com/awslabs/aiops-modules)
+ [AWS中的现代工程](https://github.com/aws-samples/appmod-blueprints)存储库

**实施**

此实现使用了 [AWS中的现代工程](https://github.com/aws-samples/appmod-blueprints)存储库中的 Backstage 生产级部署模式。这种方法极大地简化了设置过程，同时纳入了安全性和可扩展性方面 AWS 的最佳实践。

此模式的[操作说明](#accelerate-mlops-with-backstage-and-sagemaker-templates-epics)部分概述了实现方法。有关详细的 step-by-step部署说明，请参阅[带有 Backstage 存储库的AIOps 内部开发者平台 (IDP)](https://github.com/aws-samples/sample-aiops-idp-backstage/) 中提供的综合[部署指南](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md)。实现包括：
+ 初始 Backstage 平台部署
+ 将 SageMaker 软件模板与 Backstage 集成
+ 使用和维护 Backstage 模板

部署指南还包括有关持续维护、问题排查和平台扩展的指南。

## 最佳实践
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-best-practices"></a>

遵循这些最佳实践，以帮助确保 MLOps 基础设施实施中的安全性、治理和卓越运营。

**模板管理**
+ 切勿对实时模板进行重大更改。
+ 在生产部署之前，请务必对更新进行全面测试。
+ 保持清晰且有据可查的模板版本。

**安全性**
+ 将 GitHub 操作固定到特定的提交安全哈希算法 (SHAs)，以帮助防止供应链攻击。
+ 使用具有精细权限的最低权限 IAM 角色。
+ 将敏感凭据存储在 S [GitHub ecret](https://docs.github.com/en/actions/concepts/security/secrets) s 和[AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)。
+ 切勿在模板中对凭证进行硬编码。

**治理和跟踪**
+ 实施全面的资源标签标准。
+ 实现精确的成本跟踪和合规性监测。
+ 对基础设施变更保持清晰的审计跟踪记录。

本指南为使用 Backstage、 SageMaker AI 和 IaC 模块实现这些最佳实践提供了坚实的基础。

## 操作说明
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 Backstage。 | 此步骤使用 AWS存储库[现代工程](https://github.com/aws-samples/appmod-blueprints)中的蓝图来构建一个强大、可扩展的基础架构，该基础架构集成了多个 AWS 服务 基础架构，为机器学习工作流程创建集中式 IDP。按照部署指南的 [Backstage 部署部分](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#backstage-deployment)中的说明克隆存储库、安装依赖项、引导 AWS CDK 配置环境变量以及部署 Backstage 平台。该基础设施使用 Amazon EKS 作为用于部署 IDP 组件的容器编排平台。Amazon EKS 架构包括安全的联网配置，用于建立严格的网络隔离和控制访问模式。该平台与身份验证机制集成，以帮助保护用户的跨服务和环境访问。 | 平台工程师 | 
| 设置你的 SageMaker AI 模板。 | 此步骤使用 GitHub [AIOps 内部开发者平台 (IDP) 中的脚本和 Backstage](https://github.com/aws-samples/sample-aiops-idp-backstage/) 存储库。按照部署指南[SageMaker 模板设置](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#sagemaker-template-setup)部分中的说明克隆存储库、设置先决条件并运行安装脚本。此过程将创建一个存储库，其中包含与 Backstage 集成所需的 SageMaker AI 模板。 | 平台工程师 | 
| 将 SageMaker AI**** 模板与 Backstage 集成。 | 按照部署指南的 “[SageMaker 模板集成](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#sagemaker-templates-integration)” 部分中的说明注册您的 SageMaker AI 模板。此步骤将 AIOps 模块（上一步中的 SageMaker AI 模板）集成到您的 Backstage 部署中，这样您就可以自助满足机器学习基础架构的需求。 | 平台工程师 | 
| 使用 Backstage 中的 SageMaker AI 模板。 | 按照部署指南的 “[使用 SageMaker 模板](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#using-sagemaker-templates)” 部分中的说明访问 Backstage 门户并在 SageMaker Studio 中创建机器学习环境。在 Backstage 门户中，您可以从可用的 SageMaker AI 模板中进行选择，包括 SageMaker Studio 环境、 SageMaker 笔记本、自定义 SageMaker 项目模板和模型部署管道的选项。在您提供配置参数后，平台会自动创建专用存储库，并通过 Actions 和 Seed- GitHub Farmer 配置 AWS 资源。您可以通过 GitHub 操作日志和 Backstage 组件目录监控进度。 | 数据科学家、数据工程师、开发人员 | 

### 管理治理和合规模板
<a name="manage-templates-for-governance-and-compliance"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新 SageMaker AI 模板。 | 要在 Backstage 中更新 SageMaker AI 模板，请按照以下步骤操作。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/accelerate-mlops-with-backstage-and-sagemaker-templates.html) | 平台工程师 | 
| 创建和管理模板的多个版本。 | 要进行重大更改或升级，您可能需要创建 SageMaker AI 模板的多个版本。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/accelerate-mlops-with-backstage-and-sagemaker-templates.html) | 平台工程师 | 

### 扩展您的 ML 环境
<a name="extend-your-ml-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将模板覆盖范围扩展到 SageMaker AI 之外。 | 当前的解决方案仅实现 SageMaker 与 AI 相关的 AIOps 模板。您可以通过添加[AIOps 模块](https://github.com/awslabs/aiops-modules)和为其他 AWS 服务 应用程序集成自定义软件模板来扩展机器学习环境。您可以通过使用 Backstage 中的模板设计器界面、实现自定义脚手架操作或使用标准元数据维护模板存储库来创建它们。该平台支持模板版本控制、跨团队共享和验证工作流，以确保一致性。有关更多信息，请参阅[后台文档](https://backstage.io/docs/overview/what-is-backstage/)。您还可以实现模板继承模式来创建基础模板的专用版本。这种可扩展性使您能够管理 SageMaker 人工智能以外的各种 AWS 资源和应用程序，同时保留简化的开发人员体验并保持组织的标准。 | 平台工程师 | 
| 使用动态参数注入。 | 当前模板使用无需自定义的默认配置，并运行 Seed-Farmer CLI 以使用默认变量部署资源。您可以通过对模块特定的配置使用动态参数注入来扩展默认配置。 | 平台工程师 | 
| 增强安全性与合规性。 | 为了增强 AWS 资源创建过程中的安全性，您可以启用基于角色的访问控制（RBAC）集成，支持单点登录（SSO）、SAML、OpenID Connect（OIDC）和策略即代码强制执行。 | 平台工程师 | 
| 添加自动资源清理。 | 您可以启用自动清理策略的功能，还可以添加基础设施偏差检测和修复。 | 平台工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 移除后台基础架构和 SageMaker AI 资源。 | 使用完机器学习环境后，请按照部署指南的 “[清理和资源管理](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#cleanup-and-resource-management)” 部分中的说明移除 Backstage 基础架构并删除 ML 环境中的 SageMaker AI 资源。 | 平台工程师 | 

## 问题排查
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| AWS CDK 引导失败 |  验证 AWS 凭证和区域配置。 | 
| Amazon EKS 集群访问问题 | 检查 **kubectl** 配置和 IAM 权限。 | 
| 应用程序负载均衡器连接问题 | 确保安全组允许端口 80/443 上的入站流量。 | 
| GitHub 集成问题 | 验证 GitHub 令牌权限和组织访问权限。 | 
| SageMaker AI 部署失败 | 检查 [AWS 服务 配额](https://docs.aws.amazon.com/general/latest/gr/sagemaker.html#limits_sagemaker)和 IAM 权限。 | 

## 相关资源
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-resources"></a>
+ [平台工程](https://docs.aws.amazon.com/prescriptive-guidance/latest/aws-caf-platform-perspective/platform-eng.html)（位于《*AWS 云采用框架：平台视角*》指南中）
+ [亚马逊 SageMaker AI 文档](https://docs.aws.amazon.com/sagemaker/)
+ [Backstage 软件模板](https://backstage.io/docs/features/software-templates/)（Backstage 网站）
+ [AIOps 模块存储库](https://github.com/awslabs/aiops-modules)（用于机器学习的可重复使用的 IaC 模块集合）
+ [AIOps 带有后台存储库的内部开发者平台 (IDP)](https://github.com/aws-samples/sample-aiops-idp-backstage/)
+ [AWS中的现代工程](https://github.com/aws-samples/appmod-blueprints)存储库
+ [云原生卓越运营（CNOE）网站](https://cnoe.io/)

## 附加信息
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-additional"></a>

**业务挑战**

开始或扩大其 MLOps 计划的组织经常会遇到以下业务和技术挑战：
+ **环境不一致**。由于缺乏标准化开发和部署环境，因此协作变得困难，并且部署风险增加。
+ **手动预调配开销**。使用 SageMaker Studio、Amazon Simple Storage Service (Amazon S3) 存储桶、IAM 角色 CI/CD 和管道手动设置机器学习基础设施既耗时又容易出错，而且会使数据科学家偏离模型开发的核心任务。
+ **缺乏可发现性和重复使用性**。由于缺乏集中式目录，因此很难找到现有的 ML 模型、数据集和管道。这会导致冗余工作和错失重复使用的机会。
+ **复杂的治理和合规性**。若缺乏自动化防护措施，确保 ML 项目遵守组织安全政策、数据隐私法规和合规标准（如《健康保险流通与责任法案》（HIPAA）和《通用数据保护条例》（GDPR））会面临诸多挑战。
+ **价值实现得很慢**。这些挑战的累积效应导致 ML 项目生命周期延长，并延迟 ML 投资业务价值的实现。
+ **安全风险**。不一致的配置和手动流程可能会产生安全漏洞，导致难以强制执行最低权限和网络隔离。

这些问题会延长开发周期，增加运营开销，并带来安全风险。ML 的迭代性质要求可重复的工作流和高效的协作。

Gartner 预测，到 2026 年，80% 的软件工程组织将拥有平台团队。（请参阅 Gartner 网站上的[平台工程赋能开发者变得更好、更快、更开心](https://www.gartner.com/en/experts/top-tech-trends-unpacked-series/platform-engineering-empowers-developers)。） 该预测凸显了 IDP 如何加快软件交付。作为 IDP，Backstage 可帮助恢复复杂基础设施的秩序，以使团队能够快速安全地交付高质量的代码。将 Backstage 与强化 AIOps 模块集成，可帮助您从被动故障排除转变为主动预防。

**MLOps SageMaker 模块**

 GitHub 存储库中用于此模式的[AIOps 模块](https://github.com/awslabs/aiops-modules)为 AWS 通过可重复使用和强化的 IaC 实现标准化 MLOps 提供了宝贵的基础。这些模块封装了配置 SageMaker 项目、管道以及相关的网络和存储资源的最佳实践，目的是降低复杂性并加快机器学习环境的设置。您可以将这些模板用于各种 MLOps 用例，以建立一致且安全的部署模式，从而为机器学习工作流程提供更受管控和更有效的方法。

直接使用这些 AIOps 模块通常需要平台团队部署和管理这些 IaC 模板，这可能会给想要自助访问的数据科学家带来挑战。要发现和了解可用模板、配置必要的参数并触发其部署，可能需要浏览 AWS 服务 控制台或直接与 IaC 工具进行交互。如果这些模板不通过集中且用户友好的界面进行管理，可能会形成阻力，增加更喜欢专注于 ML 任务的数据科学家的认知负担，并有可能导致参数化不一致或偏离组织标准。将这些强大的 AIOps 模块与诸如Backstage之类的IDP集成，可为使用这些标准 MLOps 化构建块提供简化的自助服务体验、增强的可发现性以及更强的治理控制，从而帮助应对这些挑战。

**Backstage 作为 IDP**

内部开发者平台（IDP）是由平台团队构建的自助服务层，旨在简化和标准化开发人员构建、部署和管理应用程序的方式。它将基础设施复杂性抽象化，让开发人员能够通过统一的界面轻松访问工具、环境和服务。

IDP 的主要目标是通过以下方式增强开发者的体验和生产力：
+ 对服务创建和部署等任务启用自助服务。
+ 通过标准模板促进一致性和合规性。
+ 在整个开发生命周期（CI/CD、监控和文档化）中集成工具。

Backstage 是由 Spotify 创建的开源开发人员门户，现在是云原生计算基金会（CNCF）的一部分。它通过提供集中式、可扩展的平台来管理软件组件、工具和文档，帮助组织构建自己的 IDP。借助 Backstage，开发者可以：
+ 通过软件目录发现和管理所有内部服务。
+ 通过脚手架插件使用预定义模板创建新项目。
+ 从一个位置访问集成工具，例如 CI/CD 管道、Kubernetes 仪表板和监控系统。
+ 通过以下方式保持一致的、基于降价的文档。 TechDocs

**常见问题解答**

**使用此后台模板与通过 SageMaker 控制台手动部署 SageMaker Studio 有什么区别？**

与手动 AWS 控制台部署相比，Backstage模板具有多种优势，包括遵循组织最佳实践的标准化配置、使用Seed-Farmer和的自动IaC部署 AWS CDK、内置的安全策略和合规措施，以及通过与组织的开发人员工作流程集成。 GitHub该模板还通过版本控制创建可重现的部署，这样可以更轻松地跨不同阶段（开发、暂存、生产）复制环境，并保持团队间的一致性。此外，该模板还包括自动清理功能，并通过 Backstage 与贵组织的身份管理系统集成。通过控制台进行手动部署需要深厚的 AWS 专业知识，并且无法提供版本控制或模板所提供的相同级别的标准化和治理。出于这些原因，控制台部署比生产 ML 环境更适合一次性实验。

**什么是 Seed-Farmer？这个解决方案为什么要使用它？**

Seed-Farmer 是一款 AWS 部署编排工具，它使用管理基础架构模块。 AWS CDK这种模式之所以使用 Seed-Farmer，是因为它提供了专为工作负载设计的标准化、可重复使用的基础设施组件，可以 AWS 服务 自动处理 AI/ML 工作负载之间的复杂依赖关系，并确保在不同环境中实现一致的部署。

**我需要安装 AWS CLI 才能使用这些模板吗？**

不，您不必 AWS CLI 在计算机上安装。这些模板完全通过云端 GitHub 操作运行。您通过 Backstage 界面提供您的 AWS 凭据（访问密钥、密钥和会话令牌），然后在 Actions 环境中自动进行 GitHub 部署。

**部署 SageMaker Studio 环境需要多长时间？**

典型的 SageMaker Studio 部署需要 15-25 分钟才能完成。这包括 AWS CDK 引导（2-3 分钟）、Seed-Farmer 工具链设置（3-5 分钟）和资源创建（10-15 分钟）。确切的时间取决于您的网络设置 AWS 区域 以及您的网络设置的复杂性。

**我可以在同一个 SageMaker 环境中部署多个环境 AWS 账户吗？**

是的，可以。每个部署都会根据您在模板中提供的组件名称创建具有唯一名称的资源。但是，请注意 AWS 服务 配额：每个账户在每个区域可以拥有有限数量的 SageMaker 域名，因此在创建多个环境之前，[请检查配额](https://docs.aws.amazon.com/general/latest/gr/sagemaker.html#limits_sagemaker)。

# 使用 Amazon Bedrock 实现 AWS 基础设施运营自动化
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock"></a>

*Ishwar Chauthaiwale 和 Anand Bukkapatnam Tirumala，Amazon Web Services*

## Summary
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-summary"></a>

在云原生解决方案中，自动执行常见基础设施操作在维护高效、安全和经济实惠的环境方面起着至关重要的作用。手动处理操作非常耗时，而且容易出现人为错误。此外，具有不同 AWS 专业知识水平的团队成员需要在执行这些任务的同时确保遵守安全协议。此模式演示了如何使用 Amazon Bedrock 通过自然语言处理 (NLP) 自动执行常见的 AWS 基础设施操作。

这种模式可以帮助组织开发可重复使用、模块化和安全的代码，用于在多个环境中部署基于生成式人工智能的基础设施。通过专注于基础设施即代码 (IaC) 和自动化，它提供了关键 DevOps 优势，包括版本控制、一致的部署、减少错误、更快的配置和改进的协作。

该模式实现了一个安全的架构，使团队能够管理与密钥相关的操作， AWS 服务 包括：
+ Amazon Simple Storage Service（Amazon S3）存储桶版本控制管理
+ Amazon Relational Database Service（Amazon RDS）快照创建
+ Amazon Elastic Compute Cloud（Amazon EC2）实例管理

该架构使用亚马逊虚拟私有云（Amazon VPC）终端节点和私有网络进行安全通信，其 AWS Lambda 功能在私有子网中充当任务执行者。Amazon S3 提供数据管理并实施全面的 AWS Identity and Access Management (IAM) 角色和权限，以确保适当的访问控制。此解决方案不包括聊天记录功能，也不会存储聊天记录。

## 先决条件和限制
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-prereqs"></a>
+ 活跃 AWS 账户的.
+ 应当采取适当的访问控制措施，以帮助保护和控制访问权限。访问控制的示例包括使用基础模型访问权限 AWS Systems Manager、用于部署的 IAM 角色和基于服务的角色、禁用对 Amazon S3 存储桶的公开访问以及设置死信队列。
+  AWS Key Management Service (AWS KMS) [客户管理的密钥](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#customer-cmk)。
+ AWS Command Line Interface (AWS CLI) 版本 2 或更高版本，[已在部署环境中安装](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)和[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。
+ [安装](https://registry.terraform.io/providers/-/aws/latest/docs/guides/version-4-upgrade)并配置了 Terraform P AWS rovider 版本 4 或更高版本。
+ 已[安装](https://developer.hashicorp.com/terraform/install)并配置 1.5.7 或更高版本的 Terraform。
+ 查看并[在 Amazon Bedrock 中为代理的操作组定义 OpenAPI 架构](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-api-schema.html)，以帮助防范未经授权的访问并保持数据完整性。
+ [在你 AWS 账户 中@@ [启用了所需的 Amazon Titan Text Embeddings v2 以及 Claude 3.5 Sonnet 或 Claude 3 Haiku 基础模型的访问权限](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access-modify.html)。](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html)为避免部署失败，请确认您的目标部署 AWS 区域 [支持所需的模型](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)。
+ 遵循 [AWS Well Architected Framework](https://docs.aws.amazon.com/wellarchitected/latest/framework/sec-design.html) 最佳实践的虚拟私有云（VPC）。
+ 已完成对 [Amazon 负责任的人工智能政策](https://aws.amazon.com/ai/responsible-ai/policy/)的审阅。

**产品版本**
+ Amazon Titan 文本嵌入 v2
+ Anthropic Claude 3.5 Sonnet 或 Claude 3 Haiku
+ Terraform P AWS rovider 版本 4 或更高版本
+ Terraform 版本 1.5.7 或更高版本

## 架构
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-architecture"></a>

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

![\[使用 Amazon Bedrock 自动执行常见 AWS 基础设施操作的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/924e503f-bfc5-4452-abdf-d72a58d4d36f/images/bd56ad29-b435-4543-8ee8-dc4e1d38df18.png)


解决方案架构由多个层组成，它们协同工作以处理自然语言请求并执行相应的 AWS 操作：

1. 用户通过 Amazon Bedrock 聊天控制台提出操作请求。

1. 聊天机器人使用 Amazon Bedrock 知识库来处理请求。它实现了用于自然语言处理的 Amazon Titan 文本嵌入 v2 模型。

1. 如果用户提示中包含操作请求，则 Amazon Bedrock 操作组使用 Anthropic Claude 3 Haiku 或 Claude 3.5 Sonnet 模型（取决于您的选择）作为执行逻辑，并通过 OpenAPI 架构定义操作。

1. 操作组使用访问 AWS PrivateLink 用于安全服务通信的 Amazon VPC [终端节点](https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/what-are-vpc-endpoints.html)。

1. 该 AWS Lambda 功能可通过亚马逊 Bedrock 服务的亚马逊 VPC 终端节点访问。

1. Lambda 函数是主要的执行引擎。根据请求，Lambda 函数调用 API 以对 AWS 服务执行操作。Lambda 函数还处理操作的路由和执行。

1. 从 Lambda 函数中 AWS 服务 获取 API 请求并执行相应的操作。

1. Lambda 函数计算 Amazon Bedrock 可以理解的输出有效载荷。

1. 此有效载荷通过使用 PrivateLink 安全服务通信发送到 Amazon Bedrock。Amazon Bedrock 使用的大语言模型（LLM）可以理解此有效载荷，并将其转换为人类可理解的格式。

1. 然后在 Amazon Bedrock 聊天控制台上向用户显示输出。

该解决方案支持以下主要操作：
+ Amazon S3 – 启用存储桶版本控制以进行版本控制。
+ Amazon RDS – 创建用于备份的数据库快照。
+ Amazon EC2 – 列出实例并控制实例的启动和停止。

## 工具
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-tools"></a>

**AWS 服务**
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 是一项完全托管的服务，它通过统一的 API 提供来自领先的人工智能初创公司和亚马逊的高性能基础模型 (FMs) 供您使用。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您 AWS 服务 通过命令行 shell 中的命令进行交互。
+ [Amazon Elastic Compute Cloud（Amazon EC2）](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)在 AWS 云中提供可扩展的计算容量。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [Amazon OpenSearch Server](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-overview.html) less 是亚马逊 OpenSearch 服务的按需无服务器配置。
+ [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html)帮助您创建从您的虚拟私有云 (VPCs) 到 VPC 外部服务的单向私有连接。
+ [Amazon Relational Database Service（Amazon RDS）](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html)可帮助您在 AWS 云中设置、操作和扩展关系数据库。
+ [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 资源。
+ [Amazon Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。该虚拟网络类似于您在数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。

**其他工具**
+ [Git](https://git-scm.com/docs) 是开源分布式版本控制系统。
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。

**代码存储库**

此模式的代码可在 GitHub [aws-sam infra-ops-orchestrator](https://github.com/aws-samples/infra-ops-orchestrator) ples/ 存储库中找到。

## 最佳实践
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-best-practices"></a>
+ 定期监控 Lambda 执行日志。有关更多信息，请参阅 [Lambda 函数监控和故障排除](https://docs.aws.amazon.com/lambda/latest/dg/lambda-monitoring.html)。有关最佳实践的更多信息，请参阅[使用 AWS Lambda 函数的最佳实践](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)。
+ 定期审核安全配置，以确保符合贵组织的要求。有关更多信息，请参阅[安全最佳实践](https://docs.aws.amazon.com/wellarchitected/latest/framework/sec-bp.html)。
+ 遵循最低权限原则，并授予执行任务所需的最低权限。有关详情，请参阅 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="automate-aws-infrastructure-operations-by-using-amazon-bedrock-epics"></a>

### 部署解决方案
<a name="deploy-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要在本地计算机上克隆存储库，请运行以下命令：<pre>git clone "git@github.com:aws-samples/infra-ops-orchestrator.git"<br />cd infra-ops-orchestrator</pre> | AWS DevOps， DevOps 工程师 | 
| 编辑环境变量。 | 编辑克隆存储库的根目录中的 `terraform.tfvars` 文件。查看 `[XXXXX]` 所指示的占位符，并根据您的环境对其进行更新。 | AWS DevOps， DevOps 工程师 | 
| 创建基础设施。 | 要创建基础设施，请运行以下命令：<pre>terraform init</pre><pre>terraform plan</pre>仔细审查执行计划。如果计划的更改可以接受，则请运行以下命令：<pre>terraform apply --auto-approve</pre> | AWS DevOps， DevOps 工程师 | 

### 访问该解决方案
<a name="access-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 访问该解决方案。 | 成功部署后，请按照以下步骤使用基于聊天的界面：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-infrastructure-operations-by-using-amazon-bedrock.html) | AWS DevOps， DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除创建的资源。 | 要删除此模式创建的所有基础设施，请运行以下命令：<pre>terraform plan -destroy </pre>仔细审查销毁计划。如果计划的删除可以接受，则请运行以下命令：<pre>terraform destroy</pre>注意：此命令将永久删除由此模式创建的所有资源。在移除任何资源之前，该命令会提示进行确认。 | AWS DevOps， DevOps 工程师 | 

## 问题排查
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 代理行为  | 有关此问题的信息，请参阅 Amazon Bedrock 文档中的[测试代理行为并进行问题排查](https://docs.aws.amazon.com/lambda/latest/dg/troubleshooting-networking.html)。 | 
| Lambda 网络问题 | 有关这些问题的信息，请参阅 Lambda 文档中的 [Lambda 中的联网问题疑难解答](https://docs.aws.amazon.com/lambda/latest/dg/troubleshooting-networking.html)。 | 
| IAM 权限 | 有关这些问题的信息，请参阅 IAM 文档中的[排查 IAM 问题](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot.html)。 | 

## 相关资源
<a name="automate-aws-infrastructure-operations-by-using-amazon-bedrock-resources"></a>
+ [为 Amazon RDS 的单可用区数据库实例创建数据库快照](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateSnapshot.html)
+ [在 Amazon Bedrock 中为代理的操作组定义 OpenAPI 架构](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-api-schema.html)
+ [在存储桶上启用版本控制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/manage-versioning-examples.html)
+ [亚马逊 Bedrock Agents 的工作原理](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-how.html)
+ [利用 Amazon Bedrock 知识库检索数据并生成人工智能响应](https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/aws-privatelink.html)
+ [通过安全访问服务 AWS PrivateLink](https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/aws-privatelink.html)
+ [停止并启动 Amazon EC2 实例](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Stop_Start.html)
+ [使用操作组来定义代理要执行的操作](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-action-create.html)

# 使用 Terraform 在负载平衡器端点发生变化时自动 CloudFront 更新
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change"></a>

*Tamilselvan P、Mohan Annam 和 Naveen Suthar，Amazon Web Services*

## Summary
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-summary"></a>

当 Amazon Elastic Kubernetes Service（Amazon EKS）的用户通过 Helm 图表删除并重新安装其入口配置时，就会创建一个新应用程序负载均衡器（ALB）。这就造成了一个问题，因为Amazon CloudFront 继续引用旧的ALB的DNS记录。因此，将无法访问发往此端点的服务。（有关此问题工作流的更多详细信息，请参阅[其他信息](#automate-cloudfront-updates-when-load-balancer-endpoints-change-additional)。）

为了解决这个问题，此模式描述了如何使用使用 Python 开发的自定义 AWS Lambda 函数。此 Lambda 函数会自动检测何时通过亚马逊规则创建新 ALB。 EventBridge 然后 适用于 Python (Boto3) 的 AWS SDK，该函数使用新 ALB 的 DNS 地址更新 CloudFront 配置，确保流量路由到正确的终端节点。

这种自动化解决方案可在不增加路由或延迟的情况下保持服务连续性。该过程有助于确保即使底层基础设施发生变化，也 CloudFront 始终引用正确的 ALB DNS 端点。

## 先决条件和限制
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ 使用 Helm 在 Amazon EKS 上部署的用于测试和验证的示例 Web 应用程序。有关更多详细，请参阅 Amazon EKS 文档中的[使用 Helm 在 Amazon EKS 上部署应用程序](https://docs.aws.amazon.com/eks/latest/userguide/helm.html)。
+ 配置 CloudFront 为将呼叫路由到由 Helm [入口](https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/)控制器创建的 ALB。有关更多信息，请参阅 Amazon EKS 文档中的[使用 Helm 安装 AWS 负载均衡器控制器和](https://docs.aws.amazon.com/eks/latest/userguide/lbc-helm.html)文档中的[限制对应用程序负载均衡器的访问权限](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/restrict-access-to-load-balancer.html)。 CloudFront 
+ Terraform 已在本地工作区中[安装](https://developer.hashicorp.com/terraform/install?product_intent=terraform)和配置。

**限制**
+ 有些 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)，然后选择相应服务的链接。

**产品版本**
+ Terraform 版本 1.0.0 或更高版本
+ Terraform [AWS Provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs) 版本 4.20 或更高版本

## 架构
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-architecture"></a>

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

![\[使用通过 EventBridge 规则检测到 CloudFront 的新 ALB DNS 地址进行更新的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/03c30b18-4dd7-4dd4-b960-5a5cc58cec63/images/28854767-0902-4398-80af-b19141dd94e4.png)


该解决方案将执行以下步骤：

1. 每当重启或部署 Helm 时，Amazon EKS 入口控制器都会创建一个新应用程序负载均衡器（ALB）。

1. EventBridge 查找 ALB 创建事件。

1. ALB 创建事件会触发 Lambda 函数。

1. Lambda 函数是基于 python 3.9 部署的，并使用 boto3 API 进行调用。 AWS 服务 Lambda 函数使用最新的负载均衡器 DNS 名称更新 CloudFront 条目，该名称是从创建负载均衡器事件中收到的。

## 工具
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-tools"></a>

**AWS 服务**
+ [Amazon](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) 通过全球数据中心网络交付您的网页内容，从而降低延迟并提高性能，从而 CloudFront加快网络内容的分发。
+ [亚马逊 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 Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [适用于 Python (Boto3) 的 AWS SDK](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)是一个软件开发套件，可帮助您将 Python 应用程序、库或脚本与集成 AWS 服务。

**其他工具**
+ [Python](https://www.python.org/) 是通用的计算机编程语言。
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。

**代码存储库**

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

## 操作说明
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-epics"></a>

### 设置本地工作站
<a name="set-up-local-workstation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置和配置 Git CLI。 | 要在本地工作站中安装和配置 Git 命令行界面（CLI），请遵照 Git 文档中的[开始使用 – 安装 Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 说明操作。 | DevOps 工程师 | 
| 创建项目文件夹并添加文件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-cloudfront-updates-when-load-balancer-endpoints-change.html) | DevOps 工程师 | 

### 使用 Terraform 配置来预调配目标架构
<a name="provision-the-target-architecture-using-the-terraform-configuration"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署解决方案。 | 要在目标中部署资源 AWS 账户，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-cloudfront-updates-when-load-balancer-endpoints-change.html) | DevOps 工程师 | 

### 验证部署
<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/automate-cloudfront-updates-when-load-balancer-endpoints-change.html) | DevOps 工程师 | 

### 清理基础设施
<a name="clean-up-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理基础设施。 | 要清理您之前创建的基础设施，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-cloudfront-updates-when-load-balancer-endpoints-change.html) | DevOps 工程师 | 

## 问题排查
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 验证提供商凭证时出错 | 在本地计算机上运行 Terraform `apply` 或 `destroy` 命令时，可能会遇到类似以下内容的错误：<pre>Error: configuring Terraform AWS Provider: error validating provider <br />credentials: error calling sts:GetCallerIdentity: operation error STS: <br />GetCallerIdentity, https response error StatusCode: 403, RequestID: <br />123456a9-fbc1-40ed-b8d8-513d0133ba7f, api error InvalidClientTokenId: <br />The security token included in the request is invalid.</pre>此错误是由本地计算机配置中使用的凭证安全令牌过期引起的。要解决此错误，请参阅 AWS Command Line Interface (AWS CLI) 文档中的[设置和查看配置设置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-methods)。 | 

## 相关资源
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-resources"></a>

**AWS resources**
+ [限制对应用程序负载均衡器的访问权限](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/restrict-access-to-load-balancer.html)
+ [使用 Loa AWS d Balancer 控制器路由互联网流量](https://docs.aws.amazon.com/eks/latest/userguide/aws-load-balancer-controller.html)

**Terraform 文档**
+ [AWS Provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)
+ [安装 Terraform](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli)
+ [远程状态](https://developer.hashicorp.com/terraform/language/state/remote)

## 附加信息
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-additional"></a>

**有问题的工作流**

![\[在中生成 out-of-date ALB DNS 条目的工作流程。 CloudFront\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/03c30b18-4dd7-4dd4-b960-5a5cc58cec63/images/bb3c2c93-c749-435d-9b1d-2bbf6f0cf085.png)


下图显示了如下工作流：

1. 当用户访问应用程序时，呼叫将转到。 CloudFront

1. CloudFront 将呼叫路由到相应的 Application Load Balancer (ALB)。

1. ALB 包括目标 IP 地址，即应用程序容器组（pod）的 IP 地址。然后，ALB 向用户提供预期的结果。

但是，此工作流出现问题。应用程序部署通过 Helm 图表进行。每当有部署或者有人重启 Helm 时，也会重新创建相应的入口。因此，外部负载均衡器控制器会重新创建 ALB。此外，在每次重新创建期间，都会使用不同的 DNS 名称重新创建 ALB。因此， CloudFront 将在原始设置中有一个陈旧的条目。由于该条目过时，用户将无法访问应用程序。此问题会导致用户停机。

**替代解决方案**

另一种可能的解决方案是为 ALB 创建[外部 DNS](https://github.com/kubernetes-sigs/external-dns)，然后将其指向中的 CloudFront Amazon Route 53 私有托管区域终端节点。但是，这种方法在应用程序流中又增加了一个跃点，这可能会导致应用程序延迟。此模式的 Lambda 函数解决方案不会中断当前流。

# 使用 GitHub 操作在亚马逊自动 CodeGuru 审查 AWS CDK Python 应用程序
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications"></a>

*Vanitha Dontireddy 和 Sarat Chandra Pothula，Amazon Web Services*

## Summary
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-summary"></a>

注意：自 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 针对 AWS Cloud Development Kit (AWS CDK) Python 应用程序的 CodeGuru 自动代码审查的集成，这些审查是通过操作精心编排的。 GitHub 该解决方案部署了在 Python AWS CDK 中定义的无服务器架构。通过在开发管道中自动执行专家代码分析，此方法可以为 AWS CDK Python 项目执行以下操作：
+ 提高代码质量。
+ 简化工作流。
+ 最大限度地发挥无服务器计算的优势。

## 先决条件和限制
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ AWS Command Line Interface [(AWS CLI) 版本 2.9.11 或更高版本，[已安装并配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)。](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ 具有读写工作流程权限的活跃 GitHub 账户和 GitHub 存储库，并通过 GitHub Actions 创建拉取请求 (PR)，以确保 PR 工作流程正常运行。
+ 在 “ GitHub 操作” 中扮演一个 OpenID Connect (OIDC) 角色，用于在中部署解决方案。 AWS 账户要创建角色，请使用 [AWS CDK 构造](https://github.com/aws-samples/github-actions-oidc-cdk-construct)。

**限制**
+ Amazon CodeGuru Profiler [支持用所有 Java 虚拟机 (JVM) 语言（例如 Scala 和 Kotlin）、运行时和 Python 3.6 或更高版本编写的应用程序](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/what-is-codeguru-profiler.html#what-is-language-support)。
+ Amazon CodeGuru Reviewer 仅[支持与来自以下来源提供商的 Java 和 Python 代码存储库的关联](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/working-with-repositories.html)： AWS CodeCommit、Bitbucket GitHub、、 GitHub 企业云和 GitHub 企业服务器。此外，只有通过操作才能支持 GitHub 亚马逊简单存储服务 (Amazon S3) Service 存储库。
+ 在持续集成和持续部署（CI/CD）管道中，没有自动打印调查发现的方法。相反，这种模式使用 GitHub 操作作为处理和显示发现结果的替代方法。
+ 有些 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="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-architecture"></a>

下图显示了该解决方案的架构。

![\[使用 GitHub 操作为 AWS CDK Python 应用程序集成 AWS CDK Python 应用程序 CodeGuru 代码审查的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/c5395e3e-ff2a-41cf-bd64-c73cc928b60b/images/18f880a2-9bc3-4d71-a598-bb83b68ee383.png)


如图所示，当开发者创建拉取请求 (PR) 以供审核时，Acti GitHub ons 会触发以下步骤：

1. IAM 角色假设 — 管道使用 GitHub 密钥中指定的 IAM 角色来执行部署任务。

1. 代码分析
   + CodeGuru 审阅者分析存储在 Amazon S3 存储桶中的代码。它可识别缺陷并提供关于修复和优化建议。
   + CodeGuru 对违反政策的行为和漏洞进行安全扫描。

1. 调查发现审核
   + 管道会在控制台输出中打印指向调查发现控制面板的链接。
   + 如果检测到关键调查发现，管道会立即失效。
   + 对于高、正常或低严重性的调查发现，管道会继续执行下一步。

1. PR 批准
   + 审阅者必须手动批准 PR。
   + 如果 PR 被拒绝，则管道将失败并停止进一步的部署步骤。

1. CDK 部署 – 在 PR 批准后，开始 CDK 部署过程。它设置了以下内容 AWS 服务 和资源：
   + CodeGuru Profiler
   + AWS Lambda 函数
   + Amazon Simple Queue Service（Amazon SQS）队列

1. 生成分析数据-要为 P CodeGuru rofiler 生成足够的分析数据，请执行以下操作：
   + 该管道通过定期向 Amazon SQS 队列发送消息来多次调用 Lambda 函数。

## 工具
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-tools"></a>

**AWS 服务**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)是一个软件开发框架，可帮助您在代码中定义和配置 AWS 云 基础架构。
+ [CDK Toolkit](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) 是一个命令行云开发套件，可帮助您与 AWS CDK 应用程序进行交互。
+ [Amazon CodeGuru Profiler](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/what-is-codeguru-profiler.html) 会从您的实时应用程序收集运行时性能数据，并提供建议，以帮助您微调应用程序性能。
+ [Amazon CodeGuru Reviewer](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/welcome.html) 使用程序分析和机器学习来检测开发人员难以发现的潜在缺陷。然后，P CodeGuru rofiler 会提供改进你的 Java 和 Python 代码的建议。
+ Amazon CodeGuru Security 是一款静态应用程序安全工具，它使用机器学习来检测违反安全策略和漏洞。它提供解决安全风险的建议并生成指标，让您可以跟踪应用程序的安全状况。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [Amazon Simple Queue Service (Amazon SQS)](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html) 提供了一个安全、持久且可用的托管队列，它可帮助您集成和分离分布式软件系统与组件。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**其他工具**
+ GitHub A@@ [c](https://docs.github.com/en/actions/writing-workflows/quickstart) tions 是一个持续集成和持续交付 (CI/CD) 平台，与 GitHub 存储库紧密集成。您可以使用 GitHub Actions 来自动执行构建、测试和部署管道。

**代码存储库**

此模式的代码可在 GitHub [amazon-codeguru-suite-cdk-python](https://github.com/aws-samples/amazon-codeguru-suite-cdk-python) 存储库中找到。

## 最佳实践
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-best-practices"></a>
+ 遵循[使用 AWS CDK开发和部署云基础设施的最佳实践](https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html)。
+ 在 GitHub 操作工作流程[中使用时，请遵循 IAM AWS 服务 中的安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)，包括：
  + 请勿在存储库代码中存储凭证。
  + [代入 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-workloads-use-roles)以接收临时凭证，并在可能的情况下使用临时凭证。
  + 向 GitHub 操作工作流程中使用的 IAM 角色@@ [授予最低权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)。仅授予在操作工作流程中执行操作所需的权限。 GitHub 
  + [监控 GitHub 操作工作流程中使用的 IAM 角色的活动](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#remove-credentials)。
  + 定期轮换您使用的长期凭证。

## 操作说明
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 AWS 凭据。 | 要导出定义堆栈 AWS 账户 以及部署堆栈 AWS 区域 位置的变量，请运行以下命令：<pre>export CDK_DEFAULT_ACCOUNT=<12-digit AWS account number></pre><pre>export CDK_DEFAULT_REGION=<AWS Region></pre>的 AWS 凭证通过环境变量提供。 AWS CDK  | AWS DevOps， DevOps 工程师 | 
| 克隆存储库。 | 要在本地计算机上克隆存储库，请运行以下命令：<pre>git clone https://github.com/aws-samples/amazon-codeguru-suite-cdk-python.git</pre> | AWS DevOps， DevOps 工程师 | 
| 安装 CDK Toolkit。 | 要确认已安装 CDK Toolkit 并检查其版本，请运行以下命令： <pre>cdk --version</pre>如果 CDK Toolkit 版本低于 2.27.0，输入以下命令以将其更新至 2.27.0 版本：<pre>npm install -g aws-cdk@2.27.0</pre>如果*未*安装 CDK Toolkit，请运行以下命令进行安装：<pre>npm install -g aws-cdk@2.27.0 --force</pre> | AWS DevOps， DevOps 工程师 | 
| 安装所需的依赖项。 | 要安装所需项目依赖项，请运行以下命令：<pre>python -m pip install --upgrade pip<br />pip install -r requirements.txt</pre> | AWS DevOps， DevOps 工程师 | 
| 引导 CDK 环境。 | 要[引导](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html) AWS CDK 环境，请运行以下命令：<pre>npm install<br />npm run cdk bootstrap "aws://${ACCOUNT_NUMBER}/${AWS_REGION}"</pre>成功引导环境后，应该显示以下输出：<pre>⏳  Bootstrapping environment aws://{account}/{region}...<br />✅  Environment aws://{account}/{region} bootstrapped</pre> | AWS DevOps， DevOps 工程师 | 

### 部署 CDK 应用程序
<a name="deploy-the-cdk-app"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 合成 AWS CDK 应用程序。 | 要合成 AWS CDK 应用程序，请运行以下命令：<pre>cdk synth</pre>有关此命令的更多信息，请参阅文档中的 [cdk synthesiz](https://docs.aws.amazon.com/cdk/v2/guide/ref-cli-cmd-synth.html) e。 AWS CDK  | AWS DevOps， DevOps 工程师 | 
| 部署资源 | 要部署资源，请运行以下命令：<pre>cdk deploy --require-approval never</pre>`--require-approval never` 标志表示 CDK 将自动批准并执行所有更改。这包括 CDK 通常会标记为需要人工审查的更改（例如 IAM 策略变更或资源移除）。在生产环境中使用该`--require-approval never`标志之前，请确保您的 CDK 代码和 CI/CD 管道经过充分测试且安全。 | AWS DevOps， DevOps 工程师 | 

### 创建 GitHub 机密和个人访问令牌
<a name="create-github-secrets-and-personal-access-token"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在中创建所需的密钥 GitHub。 | 要允许 A GitHub ctions 工作流程在不暴露仓库代码中的敏感信息的情况下安全地访问 AWS 资源，请创建密钥。要在、和中 GitHub 创建密钥 `ROLE_TO_ASSUME` `CodeGuruReviewArtifactBucketName``AWS_ACCOUNT_ID`，请按照 GitHub 操作文档中[为存储库创建密钥](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository)中的说明进行操作。下面是有关这些变量的详细信息：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-amazon-codeguru-reviews-for-aws-cdk-python-applications.html) | AWS DevOps， DevOps 工程师 | 
| 创建 GitHub 个人访问令牌。 | 要为您 GitHub 的 Actions 工作流程设置一种安全的身份验证和交互方式 GitHub，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-amazon-codeguru-reviews-for-aws-cdk-python-applications.html) | AWS DevOps， DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理资源。 | 要清理你的 AWS CDK Python 应用程序，请运行以下命令：<pre>cdk destroy --all</pre> | DevOps 工程师 | 

## 问题排查
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 显示指向控制面板调查发现的链接。 | 在 CI/CD 管道期间无法打印调查结果。相反，这种模式使用 GitHub 操作作为处理和显示发现结果的替代方法。 | 

## 相关资源
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-resources"></a>

**AWS resources**
+ [AWS Cloud 开发套件](https://aws.amazon.com/cdk/)
+ [亚马逊 CodeGuru 文档](https://docs.aws.amazon.com/codeguru/)
+ [Amazon S3](https://aws.amazon.com/s3/)
+ [AWS Identity and Access Management](https://aws.amazon.com/iam/)
+ [Amazon Simple Queue Service](https://aws.amazon.com/sqs/)
+ [什么是 AWS Lambda？](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)

**GitHub 文档**
+ [在 Amazon Web Services 中配置 OpenID Connect](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)
+ [GitHub 操作](https://github.com/features/actions)
+ [重复使用工作流程](https://docs.github.com/en/actions/using-workflows/reusing-workflows)
+ [触发工作流](https://docs.github.com/en/actions/using-workflows/triggering-a-workflow) 

# 使用 GitHub Actions、Artifactory 和 Terraform 在多存储库设置中自动部署 AWS Supply Chain 数据湖
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes"></a>

*Keshav Ganesh，亚马逊 Web Services*

## Summary
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-summary"></a>

这种模式提供了一种使用多存储库持续集成和持续部署（CI/CD) pipeline. It demonstrates two deployment methods: automated deployment using GitHub Actions workflows, or manual deployment using Terraform directly. Both approaches use Terraform for infrastructure as code (IaC), with the automated method adding GitHub Actions and JFrog Artifactory for enhanced CI/CD功能）来部署和管理 AWS Supply Chain 数据湖的自动化方法。

该解决方案利用 AWS Supply Chain AWS Lambda、和 Amazon Simple Storage Service (Amazon S3) 来建立数据湖基础设施，同时使用任一部署方法自动配置和资源创建。这种自动化消除了手动配置步骤，并确保了跨环境部署的一致性。此外， AWS Supply Chain 无需在提取、转换和加载 (ETL) 方面拥有深厚的专业知识，并且可以提供由 Amazon Quick Sight 支持的见解和分析。

通过实施这种模式，组织可以缩短部署时间，维护基础设施即代码，并通过版本控制的自动化流程管理供应链数据湖。多存储库方法提供了精细的访问控制，并支持独立部署不同的组件。团队可以选择最适合其现有工具和流程的部署方法。

## 先决条件和限制
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-prereqs"></a>

**先决条件**

确保在本地计算机上安装了以下内容：
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 版本 2
+ [GitHub CLI](https://docs.github.com/en/get-started/git-basics/set-up-git)
+ [Python](https://www.python.org/downloads/) v3.13
+ [Terraform](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) v1.12 或更高版本

在部署之前，请确保以下内容准备就绪：
+ 活跃 AWS 账户的.
+ [虚拟私有云 (VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/create-vpc.html)，其中有两个[私有子网](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-example-private-subnets-nat.html)供您选择。 AWS 账户 AWS 区域 
+ 用于部署到以下服务的 AWS Identity and Access Management (IAM) 角色有足够的权限：
  + AWS Supply Chain — Full Access 首选部署其组件（如数据集和集成流），以及从中进行访问 AWS 管理控制台。
  + Amazon CloudWatch 日志-用于创建和管理 CloudWatch 日志组。
  + 亚马逊弹性计算云 (Amazon EC2) — 适用于亚马逊 EC2 安全组和亚马逊虚拟私有云 (亚马逊 VPC) 终端节点。
  + 亚马逊 EventBridge -供使用 AWS Supply Chain。
  + IAM — 用于创建 AWS Lambda 服务角色。
  + AWS Key Management Service (AWS KMS) — AWS KMS keys 用于访问用于 Amazon S3 工件存储桶和 Amazon S3 AWS Supply Chain 暂存存储桶的。
  + AWS Lambda — 用于创建用于部署组件的 Lambda 函数。 AWS Supply Chain 
  + Amazon S3 — 用于访问 Amazon S3 项目存储桶、服务器访问日志存储桶和 AWS Supply Chain 暂存存储桶。如果您使用的是手动部署，则还需要获得 Amazon S3 Terraform 项目存储桶的权限。
  + 亚马逊 VPC — 用于创建和管理 VPC。

如果您更喜欢使用 GitHub 操作工作流程进行部署，请执行以下操作：
+ 使用前面提到的权限为 IAM 角色设置 [OpenID Connect (OIDC)](https://docs.github.com/en/actions/how-tos/secure-your-work/security-harden-deployments/oidc-in-aws#configuring-the-role-and-trust-policy)。
+ 创建具有类似权限的 IAM 角色来访问 AWS 管理控制台。有关更多信息，请参阅 I [AM 文档中的创建角色以向 IAM 用户授予权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html)。

如果您更喜欢手动部署，请执行以下操作：
+ 创建一个 IAM 用户来代入具有前面提到的权限的 IAM 角色。有关更多信息，请参阅 I [AM 文档中的创建角色以向 IAM 用户授予权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html)。
+ 在您的本地终端中@@ [扮演该角色](https://docs.aws.amazon.com/cli/v1/userguide/cli-configure-role.html)。

如果您更喜欢使用 GitHub 操作工作流程进行部署，请进行以下设置：
+ 一个 [JFrog Artifactory 帐户](https://jfrog.com/artifactory/?utm_source=google&utm_medium=cpc_search&utm_campaign=SearchDSKBrandAPACIN202506&utm_term=jfrog%20cloud&gads_network=g&utm_content=u-bin&gads_campaign_id=22674833884&gads_adgroup_id=184501797241&gads_extension_id=233003714635&gads_target_id=aud-312135645780:kwd-1598615735032&gads_matchtype=b&gad_source=1&gad_campaignid=22674833884&gbraid=0AAAAADqV85U5B37iapTR9IIFHBvydF5AQ&gclid=CjwKCAjwiY_GBhBEEiwAFaghvqdNV-odNLZXPHjT7NAwf8lA-QuMtg666hgvDW1oCJ4nn7wvf869_xoCW4IQAvD_BwE)，用于获取主机名、登录用户名和登录访问令牌。
+ 用于[存储工件的JFrog 项目密钥和存储库](https://jfrog.com/help/r/jfrog-platform-administration-documentation/step-1-set-up-a-new-project)。

**限制**
+ 该 AWS Supply Chain 实例不支持复杂的数据转换技术。
+ AWS Supply Chain 最适合供应链领域，因为它提供了内置的分析和见解。对于任何其他域， AWS Supply Chain 可用作数据存储作为数据湖架构的一部分。
+ 可能需要增强此解决方案中使用的 Lambda 函数，以处理生产规模部署中的 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="automate-the-deployment-of-aws-supply-chain-data-lakes-architecture"></a>

您可以使用自动 GitHub 操作工作流程或使用 Terraform 手动部署此解决方案。

**使用 GitHub 操作自动部署**

下图显示了使用 GitHub 操作工作流的自动部署选项。 JFrog Artifactory 用于工件管理。它存储资源信息和输出，以便在多存储库部署中使用。

![\[自动部署选项，使用 GitHub 操作工作流程和 JFrog.\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/2f0b78b0-a174-4703-b533-d66b3fb005e0/images/d454a5c5-ed51-421c-a87f-ff74cfcb30be.png)


**使用 Terraform 进行手动部署**

下图显示了通过 Terraform 的手动部署选项。Amazon S3 不是 A JFrog rtifactory，而是用于项目管理。

![\[使用 Terraform 和 Amazon S3 的手动部署选项。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/2f0b78b0-a174-4703-b533-d66b3fb005e0/images/1130e728-44d5-4ae7-9586-1e497f54352a.png)


**部署工作流**

图表显示了以下工作流程：

1. 使用以下部署方法之一部署 AWS Supply Chain 服务数据集基础架构和数据库：
   + **自动部署**-使用 GitHub 操作工作流程来协调所有部署步骤，并使用 JFrog Artifactory 进行工件管理。
   + **手动部署 — 直接为每个部署**步骤执行 Terraform 命令，并使用 Amazon S3 进行项目管理。

1. 创建 AWS Supply Chain 服务操作所需的支持 AWS 资源：
   + 亚马逊 VPC 终端节点和安全组
   + AWS KMS keys
   + CloudWatch 日志日志组

1. 创建和部署以下基础架构资源：
   + 管理（创建、更新和删除） AWS Supply Chain 服务实例、命名空间和数据集的 Lambda 函数。
   + AWS Supply Chain 暂存用于数据摄取的 Amazon S3 存储桶

1. 部署 Lambda 函数来管理暂存存储桶和数据集之间的集成流程。 AWS Supply Chain 部署完成后，其余工作流程步骤将管理数据摄取和分析。

1. 将源数据提取配置到暂存 A AWS Supply Chain mazon S3 存储桶。

1. 将数据添加到 AWS Supply Chain 暂存 Amazon S3 存储桶后，该服务会自动触发 AWS Supply Chain 数据集的集成流程。

1. AWS Supply Chain 与 Quick Sight Analytics 集成，可根据摄取的数据生成仪表板。

## 工具
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-tools"></a>

**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 服务 通过命令行 shell 中的命令进行交互。
+ [Amazon Elastic Compute Cloud（Amazon EC2）](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html)在 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 IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)帮助您集中管理对所有应用程序 AWS 账户 和云应用程序的单点登录 (SSO) 访问权限。
+ [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) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [Amazon Q](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/qinasc.html) in AWS Supply Chain 是一款交互式生成式 AI 助手，可通过分析数据湖中的数据来帮助您更高效地运营供应链。 AWS Supply Chain 
+ [Amazon Quick Sight](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) 是一种云级商业智能（BI）服务，可用于在单独的控制面板中可视化、分析和报告数据。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/adminguide/getting-started.html)是一款基于云的托管应用程序，可用作组织中供应链域的数据存储，可用于生成见解并对摄取的数据进行分析。
+ [Amazon Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。该虚拟网络类似于您在数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。[Amazon VPC 终端节点](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html)是一种虚拟设备，可帮助您将自己的 VPC 私密连接到受支持的， AWS 服务 而无需互联网网关、NAT 设备、VPN AWS Direct Connect 连接或连接。

**其他工具**
+ GitHub A@@ [c](https://docs.github.com/en/actions) tions 是一个持续集成和持续交付 (CI/CD) 平台，与 GitHub 存储库紧密集成。您可以使用 GitHub Actions 来自动执行构建、测试和部署管道。
+ [HashiCorp Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具，可帮助您创建和管理云和本地资源。
+ [JFrog Artifactor](https://jfrog.com/help/r/jfrog-artifactory-documentation/jfrog-artifactory) y 通过应用程序交付 end-to-end流程提供二进制文件和工件的自动化和管理。
+ [Python](https://www.python.org/) 是一种通用的计算机编程语言。此模式使用 Python 让 AWS 函数的代码与之交互 AWS Supply Chain

  .

## 最佳实践
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-best-practices"></a>
+ 在实施此模式时，保持尽可能高的安全性。如[先决条件](#automate-the-deployment-of-aws-supply-chain-data-lakes-prereqs)中所述，请确保您 AWS 账户 选择具有两个[私有[子网的虚拟私](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-example-private-subnets-nat.html)有云 (VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/create-vpc.html)。 AWS 区域 
+ 尽可能使用 AWS KMS [客户托管的密钥](https://docs.aws.amazon.com/kms/latest/cryptographic-details/basic-concepts.html)，并向其授予有限的访问权限。
+ 要设置获取此模式数据所需的最低访问权限的 IAM 角色，请参阅此模式存储库中[从源系统到 Amazon S3 的安全数据摄取](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main?tab=readme-ov-file#secure-data-ingestion-from-source-systems-to-amazon-s3)。

## 操作说明
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-epics"></a>

### （两个选项）设置本地工作站
<a name="both-options-set-up-local-workstation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要克隆此模式的存储库，请在您的本地工作站中运行如下命令：<pre>git clone https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment.git<br />cd ASC-Deployment</pre> | AWS DevOps | 
| （自动选项）验证部署的先决条件。 | 确保已完成自动部署的[先决条件](#automate-the-deployment-of-aws-supply-chain-data-lakes-prereqs)。 | 应用程序所有者 | 
| （手动选项）准备部署 AWS Supply Chain 数据集。 | 要转到的`terraform-deployment`目录`ASC-Datasets`，请运行以下命令：<pre>cd ASC-Datasets/terraform-deployment</pre>要代入在[先决条件](#automate-the-deployment-of-aws-supply-chain-data-lakes-prereqs)中创建的 ARN 角色，请运行以下命令：<pre>aws sts assume-role --role-arn <enter AWS user role ARN> --role-session-name <your-session-name></pre>要配置和导出环境变量，请运行以下命令：<pre># Export Environment variables<br />export REGION=<Enter deployment region><br />export REPO_NAME=<Enter Current ASC Datasets dir name><br />export PROJECT_NAME="asc-deployment-poc"<br />export ACCOUNT_ID=<Enter deployment Account ID><br />export ENVIRONMENT="dev"<br />export LAMBDA_LAYER_TEMP_DIR_TERRAFORM="layerOutput"<br />export LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM="lambdaOutput"<br />export AWS_USER_ROLE=<Enter user role ARN for AWS Console access and deployment><br />export S3_TERRAFORM_ARTIFACTS_BUCKET_NAME="$PROJECT_NAME-$ACCOUNT_ID-$REGION-terraform-artifacts-$ENVIRONMENT"</pre> | AWS DevOps | 
| （手动选项）为管理部署中的 AWS Supply Chain 集成流程做好准备。 | 要转到的`terraform-deployment`目录`ASC-Integration-Flows`，请运行以下命令：<pre>cd ASC-Integration-Flows/terraform-deployment</pre>要代入之前创建的 ARN 角色，请运行以下命令：<pre>aws sts assume-role --role-arn <enter AWS user role ARN> --role-session-name <your-session-name></pre>要配置和导出环境变量，请运行以下命令：<pre># Export Environment variables<br />export REGION=<Enter deployment region><br />export REPO_NAME=<Enter Current ASC Integration Flows dir name><br />export ASC_DATASET_VARS_REPO=<Enter Current ASC Datasets dir name>  #Must be the same directory name used for ASC Datasets deployment<br />export PROJECT_NAME="asc-deployment-poc"<br />export ACCOUNT_ID=<Enter deployment Account ID><br />export ENVIRONMENT="dev"<br />export LAMBDA_LAYER_TEMP_DIR_TERRAFORM="layerOutput"<br />export LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM="lambdaOutput"<br />export S3_TERRAFORM_ARTIFACTS_BUCKET_NAME="$PROJECT_NAME-$ACCOUNT_ID-$REGION-terraform-artifacts-$ENVIRONMENT"</pre> | 应用程序所有者 | 

### （自动选项）使用 GitHub 操作工作流部署 AWS Supply Chain 数据集
<a name="automated-option-deploy-supplychain-datasets-using-github-actions-workflows"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 复制该`ASC-Datasets`目录。 | 要将`ASC-Datasets`目录复制到新位置，请执行以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-deployment-of-aws-supply-chain-data-lakes.html) | AWS DevOps | 
| 设置`ASC-Datasets`目录。 | 要在组织中设置`ASC-Datasets`为独立存储库，请运行以下命令：<pre>git init<br />git add .<br />git commit -m "Initial commit: ASC-Datasets standalone repository"<br />git remote add origin <INSERT_ASC_DATASETS_GITHUB_URL><br />git branch -M dev</pre> | AWS DevOps | 
| 在.github 工作流程文件中配置分支名称。 | 在[部署](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Datasets/.github/workflows/asc-datasets.yml)工作流文件中设置分支名称，如以下示例所示：<pre>   on:<br />     workflow_dispatch:<br />     push:<br />       branches:<br />         - dev     #Change to any other branch preferred for deployment</pre> | 应用程序所有者 | 
| 设置 GitHub 环境并配置环境值。 | 要在 GitHub 组织中设置 GitHub 环境，请使用此模式存储库中的[安装 GitHub 环境](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Datasets#setup-github-environments)中的说明。要在工作流文件中配置[环境值](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Datasets#setup-environment-values-in-the-workflow-files)，请使用此模式存储库[中工作流程文件中的安装环境值](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Datasets#setup-environment-values-in-the-workflow-files)中的说明。 | 应用程序所有者 | 
| 触发工作流程。 | 要将更改推送到您的 GitHub 组织并触发部署工作流程，请运行以下命令：<pre>git push -u origin dev</pre> | AWS DevOps | 

### （自动选项）使用 GitHub 操作工作流程部署 AWS Supply Chain 集成流程
<a name="automated-option-deploy-supplychain-integration-flows-using-github-actions-workflows"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 复制该`ASC-Integration-Flows`目录。 | 要将`ASC-Integration-Flows`目录复制到新位置，请执行以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-deployment-of-aws-supply-chain-data-lakes.html) | AWS DevOps | 
| 设置`ASC-Integration-Flows`目录。 | 要将该`ASC-Integration-Flows`目录设置为组织中的独立存储库，请运行以下命令：<pre>git init<br />git add .<br />git commit -m "Initial commit: ASC-Integration-Flows standalone repository"<br />git remote add origin <INSERT_ASC_Integration_Flows_GITHUB_URL><br />git branch -M dev</pre> | AWS DevOps | 
| 在.github 工作流程文件中配置分支名称。 | 在[部署](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Integration-Flows/.github/workflows/asc-integration-flows.yml)工作流文件中设置分支名称，如以下示例所示：<pre>   on:<br />     workflow_dispatch:<br />     push:<br />       branches:<br />         - dev     #Change to any other branch preferred for deployment</pre> | 应用程序所有者 | 
| 设置 GitHub 环境并配置环境值。 | 要在 GitHub 组织中设置 GitHub 环境，请使用此模式存储库中的[安装 GitHub 环境](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Integration-Flows#setup-github-environments)中的说明。要在工作流文件中配置[环境值](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Integration-Flows#setup-github-environments)，请使用此模式存储库[中工作流程文件中的安装环境值](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/tree/main/ASC-Integration-Flows#setup-environment-values-in-the-workflow-files)中的说明。 | 应用程序所有者 | 
| 触发工作流程。 | 要将更改推送到您的 GitHub 组织并触发部署工作流程，请运行以下命令：<pre>git push -u origin dev</pre> | AWS DevOps | 

### （手动选项）使用 Terraform 部署 AWS Supply Chain 数据集
<a name="manual-option-deploy-supplychain-datasets-using-terraform"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 导航到 `terraform-deployment ` 目录。 | 要转到的`terraform-deployment`目录`ASC-Datasets`，请运行以下命令：<pre>cd ASC-Datasets/terraform-deployment</pre> | AWS DevOps | 
| 设置 Terraform 状态 Amazon S3 存储桶。 | 要设置 Terraform 状态 Amazon S3 存储桶，请使用以下脚本：<pre># Setup terraform bucket<br />chmod +x ../scripts/setup-terraform.sh<br />../scripts/setup-terraform.sh</pre> | AWS DevOps | 
| 设置 Terraform 工件 Amazon S3 存储桶。 | 要设置 Terraform 工件 Amazon S3 存储桶，请使用以下脚本：<pre># Setup terraform artifacts bucket<br />chmod +x ../scripts/setup-terraform-artifacts-bucket.sh<br />../scripts/setup-terraform-artifacts-bucket.sh</pre> | AWS DevOps | 
| 设置 Terraform 后端和提供者配置。 | 要设置 Terraform 后端和提供程序配置，请使用以下脚本：<pre># Setup terraform backend and providers config if they don't exist<br />chmod +x ../scripts/generate-terraform-config.sh<br />../scripts/generate-terraform-config.sh</pre> | AWS DevOps | 
| 生成部署计划。 | 要生成部署计划，请运行以下命令：<pre># Run terraform init and validate<br />terraform init<br />terraform validate<br /><br /># Run terraform plan<br />terraform plan \<br />-var-file="tfInputs/$ENVIRONMENT.tfvars" \<br />-var="project_name=$PROJECT_NAME" \<br />-var="environment=$ENVIRONMENT" \<br />-var="user_role=$AWS_USER_ROLE" \<br />-var="lambda_temp_dir=$LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM" \<br />-var="layer_temp_dir=$LAMBDA_LAYER_TEMP_DIR_TERRAFORM" \<br />-parallelism=40 \<br />-out='tfplan.out'</pre> | AWS DevOps | 
| 部署配置。 | 要部署配置，请运行以下命令：<pre># Run terraform apply<br />terraform apply tfplan.out</pre> | AWS DevOps | 
| 更新其他配置并存储输出。 | 要更新 AWS KMS 密钥策略并将应用的配置输出存储在 Terraform 工件 Amazon S3 存储桶中，请运行以下命令：<pre># Update AWS Supply Chain KMS Key policy with the service's requirements<br />chmod +x ../scripts/update-asc-kms-policy.sh<br />../scripts/update-asc-kms-policy.sh<br /></pre><pre># Update AWS KMS Keys' policy with IAM roles<br />chmod +x ../scripts/update-kms-policy.sh<br />../scripts/update-kms-policy.sh<br /></pre><pre># Create terraform outputs file to be used as input variables<br />terraform output -json > raw_output.json<br />jq -r 'to_entries | map(<br />  if .value.type == "string" then<br />      "\(.key) = \"\(.value.value)\""<br />  else<br />      "\(.key) = \(.value.value | tojson)"<br />  end<br />) | .[]' raw_output.json > $REPO_NAME-outputs.tfvars<br /></pre><pre># Upload reformed outputs file to Amazon S3 terraform artifacts bucket (For retrieval from other repositories)<br />aws s3 cp $REPO_NAME-outputs.tfvars s3://$S3_TERRAFORM_ARTIFACTS_BUCKET_NAME/$REPO_NAME-outputs.tfvars<br />rm -f raw_output.json<br />rm -f $REPO_NAME-outputs.tfvars<br /></pre> | AWS DevOps | 

### （手动选项）使用 Terraform 部署 AWS Supply Chain 服务集成流程
<a name="manual-option-deploy-supplychain-service-integration-flows-using-terraform"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 导航到 `terraform-deployment` 目录。 | 要转到的`terraform-deployment`目录`ASC-Integration-Flows`，请运行以下命令：<pre>cd ASC-Integration-Flows/terraform-deployment</pre> | AWS DevOps | 
| 设置 Terraform 后端和提供者配置。 | 要设置 Terraform 后端和提供程序配置，请使用以下脚本：<pre># Setup terraform backend and providers config if they don't exist<br />chmod +x ../scripts/generate-terraform-config.sh<br />../scripts/generate-terraform-config.sh</pre> | AWS DevOps | 
| 生成部署计划。 | 要生成部署计划，请运行以下命令。这些命令初始化您的 Terraform 环境，将配置变量`ASC-Datasets`与现有 Terraform 配置合并，并生成部署计划。<pre># Run terraform init and validate<br />terraform init<br />terraform validate<br /></pre><pre># Download and merge ASC DATASET tfvars<br />chmod +x ../scripts/download-vars-through-s3.sh<br />../scripts/download-vars-through-s3.sh $ASC_DATASET_VARS_REPO<br /></pre><pre># Run terraform plan<br />terraform plan \<br />-var-file="tfInputs/$ENVIRONMENT.tfvars" \<br />-var="project_name=$PROJECT_NAME" \<br />-var="environment=$ENVIRONMENT" \<br />-var="lambda_temp_dir=$LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM" \<br />-var="layer_temp_dir=$LAMBDA_LAYER_TEMP_DIR_TERRAFORM" \<br />-parallelism=40 \<br />-out='tfplan.out'</pre> | AWS DevOps | 
| 部署配置。 | 要部署配置，请运行以下命令：<pre># Run terraform apply<br />terraform apply tfplan.out</pre> | AWS DevOps | 
| 更新其他配置。 | 要更新 AWS KMS 密钥策略并将应用的配置输出存储在 Terraform 工件 Amazon S3 存储桶中，请运行以下命令：<pre># Update AWS KMS Keys' policy with IAM roles<br />chmod +x ../scripts/update-kms-policy-through-s3.sh<br />../scripts/update-kms-policy-through-s3.sh $ASC_DATASET_VARS_REPO<br /></pre><pre># Create terraform outputs file to be used as input variables<br />terraform output -json > raw_output.json<br />jq -r 'to_entries | map(<br />  if .value.type == "string" then<br />      "\(.key) = \"\(.value.value)\""<br />  else<br />      "\(.key) = \(.value.value | tojson)"<br />  end<br />) | .[]' raw_output.json > $REPO_NAME-outputs.tfvars<br /></pre><pre># Upload reformed outputs file to Amazon S3 terraform artifacts bucket (For retrieval from other repositories)<br />aws s3 cp $REPO_NAME-outputs.tfvars s3://$S3_TERRAFORM_ARTIFACTS_BUCKET_NAME/$REPO_NAME-outputs.tfvars<br />rm -f raw_output.json<br />rm -f $REPO_NAME-outputs.tfvars<br /></pre> | AWS DevOps | 

### （两个选项）摄取数据
<a name="both-options-ingest-data"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 上传示例 CSV 文件。 | 要上传数据集的示例 CSV 文件，请按以下步骤操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-deployment-of-aws-supply-chain-data-lakes.html) | 数据工程师 | 

### （两个选项）设置 AWS Supply Chain 访问权限
<a name="both-options-set-up-supplychain-access"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 AWS Supply Chain 访问权限。 | 要从中设置 AWS Supply Chain 访问权限 AWS 管理控制台，请按以下步骤操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-deployment-of-aws-supply-chain-data-lakes.html) | 应用程序所有者 | 

### （自动选项）使用 GitHub 操作工作流程清理所有资源
<a name="automated-option-clean-up-all-resources-using-github-actions-workflows"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 触发集成流资源的销毁工作流程。 | `ASC-Integration-Flows`从 GitHub 组织中的部署分支触发的[销毁工作流程](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Integration-Flows/.github/workflows/destroy-workflow.yml)。 | AWS DevOps | 
| 触发数据集资源的销毁工作流程。 | `ASC-Datasets`从 GitHub 组织中的部署分支触发的[销毁工作流程](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Datasets/.github/workflows/destroy-workflow.yml)。 | AWS DevOps | 

### （手动选项）使用 Terraform 清理 AWS Supply Chain 集成流程的资源
<a name="manual-option-clean-up-resources-of-supplychain-integration-flows-using-terraform"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 导航到 `terraform-deployment` 目录。 | 要转到的`terraform-deployment`目录`ASC-Integration-Flows`，请运行以下命令：<pre>cd ASC-Integration-Flows/terraform-deployment</pre> | AWS DevOps | 
| 设置 Terraform 后端和提供者配置。 | 要设置 Terraform 后端和提供程序配置，请使用以下脚本：<pre># Setup terraform backend and providers config if they don't exist<br />chmod +x ../scripts/generate-terraform-config.sh<br />../scripts/generate-terraform-config.sh</pre> | AWS DevOps | 
| 制定基础设施销毁计划。 | 要通过生成详细的拆卸计划为有控制地销毁 AWS 基础设施做好准备，请运行以下命令。该过程初始化 Terraform，合并 AWS Supply Chain 数据集配置，并创建销毁计划，您可以在执行之前查看该计划。<pre># Run terraform init and validate<br />terraform init<br />terraform validate<br /></pre><pre># Download and merge ASC DATASET tfvars<br />chmod +x ../scripts/download-vars-through-s3.sh<br />../scripts/download-vars-through-s3.sh $ASC_DATASET_VARS_REPO<br /></pre><pre># Run terraform plan<br />terraform plan -destroy\<br />-var-file="tfInputs/$ENVIRONMENT.tfvars" \<br />-var="project_name=$PROJECT_NAME" \<br />-var="environment=$ENVIRONMENT" \<br />-var="lambda_temp_dir=$LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM" \<br />-var="layer_temp_dir=$LAMBDA_LAYER_TEMP_DIR_TERRAFORM" \<br />-parallelism=40 \<br />-out='tfplan.out'</pre> | AWS DevOps | 
| 执行基础设施销毁计划。 | 要按计划销毁您的基础架构，请运行以下命令：<pre># Run terraform apply<br />terraform apply tfplan.out</pre> | AWS DevOps | 
| 从 Amazon S3 存储桶中删除 Terraform 的输出。 | 要删除部署期间上传的输出文件`ASC-Integration-Flows`，请运行以下命令：<pre># Delete the outputs file<br />aws s3 rm s3://$S3_TERRAFORM_ARTIFACTS_BUCKET_NAME/$REPO_NAME-outputs.tfvars</pre> | AWS DevOps | 

### （手动选项）使用 Terraform 清理 AWS Supply Chain 服务数据集的资源
<a name="manual-option-clean-up-resources-of-supplychain-service-datasets-using-terraform"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 导航到 `terraform-deployment` 目录。 | 要转到的`terraform-deployment`目录`ASC-Datasets`，请运行以下命令：<pre>cd ASC-Datasets/terraform-deployment</pre> | AWS DevOps | 
| 设置 Terraform 后端和提供者配置。 | 要设置 Terraform 后端和提供程序配置，请使用以下脚本：<pre># Setup terraform backend and providers config if they don't exist<br />chmod +x ../scripts/generate-terraform-config.sh<br />../scripts/generate-terraform-config.sh</pre> | AWS DevOps | 
| 制定基础设施销毁计划。 | 要制定销毁 AWS Supply Chain 数据集资源的计划，请运行以下命令：<pre># Run terraform init and validate<br />terraform init<br />terraform validate<br /><br /># Run terraform plan<br />terraform plan -destroy\<br />-var-file="tfInputs/$ENVIRONMENT.tfvars" \<br />-var="project_name=$PROJECT_NAME" \<br />-var="environment=$ENVIRONMENT" \<br />-var="user_role=$AWS_USER_ROLE" \<br />-var="lambda_temp_dir=$LAMBDA_FUNCTION_TEMP_DIR_TERRAFORM" \<br />-var="layer_temp_dir=$LAMBDA_LAYER_TEMP_DIR_TERRAFORM" \<br />-parallelism=40 \<br />-out='tfplan.out'</pre> | AWS DevOps | 
| 清空 Amazon S3 存储桶。 | 要清空所有 Amazon S3 存储桶（配置为的服务器访问日志存储桶除外`force-destroy`），请使用以下脚本：<pre># Delete S3 buckets excluding server access logging bucket<br />chmod +x ../scripts/empty-s3-buckets.sh<br />../scripts/empty-s3-buckets.sh tfplan.out</pre> | AWS DevOps | 
| 执行基础设施销毁计划。 | 要使用生成的计划按计划销毁数据 AWS Supply Chain 集基础架构，请运行以下命令：<pre># Run terraform apply<br />terraform apply tfplan.out</pre> | AWS DevOps | 
| 从 Amazon S3 Terraform 工件存储桶中删除 Terraform 输出。 | 要完成清理过程，请运行以下命令删除部署期间上传`ASC-Datasets`的输出文件：<pre># Delete the outputs file<br />aws s3 rm s3://$S3_TERRAFORM_ARTIFACTS_BUCKET_NAME/$REPO_NAME-outputs.tfvars</pre> | AWS DevOps | 

## 问题排查
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 由于 AWS Supply Chain 内部错误或服务角色的 IAM 权限不足， AWS Supply Chain 数据集或集成流程未正确部署。 | 首先，清理所有资源。然后，重新部署 AWS Supply Chain [数据集资源](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Datasets/README.md)，然后重新部署 AWS Supply Chain [集成流](https://github.com/aws-samples/sample-automate-aws-supply-chain-deployment/blob/main/ASC-Integration-Flows/README.md)资源。 | 
|  AWS Supply Chain 集成流程不会获取为数据 AWS Supply Chain 集上传的新数据文件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-deployment-of-aws-supply-chain-data-lakes.html) | 

## 相关资源
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-resources"></a>

**AWS 文档**
+ [AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/adminguide/getting-started.html)

**其他资源**
+ [了解 GitHub 操作工作流程](https://docs.github.com/en/actions/get-started/understand-github-actions)（GitHub 文档）

## 附加信息
<a name="automate-the-deployment-of-aws-supply-chain-data-lakes-additional"></a>

该解决方案可以复制到更多数据集，也可以通过 Amazon Quick Sight 提供的预建仪表板 AWS Supply Chain 或与 Amazon Quick Sight 的自定义集成进行查询以进行进一步分析。此外，您可以使用 Amazon Q 来询问与您的 AWS Supply Chain 实例相关的问题。

**使用 “分析” AWS Supply Chain 分析数据**

有关设置 AWS Supply Chain 分析的说明，请参阅 AWS Supply Chain 文档中的[设置 AWS Supply Chain 分析](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/setting_analytics.html)。

这种模式演示了**日历**和 **Outbound\$1Order\$1L** ine 数据集的创建。要创建使用这些数据集的分析，请使用以下步骤：

1. 要分析数据集，请使用**季节性分析**仪表板。要添加仪表板，请按照 AWS Supply Chain 文档中[预建仪表板](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/prebuilt_dashboards.html)中的步骤进行操作。

1. 选择控制面板以查看其基于日历数据和出库订单行数据的示例 CSV 文件的分析。

该仪表板根据数据集摄取的数据按需提供多年来的见解。您可以进一步指定产品编号、客户编号、年份和其他参数进行分析。

**使用 Amazon Q 询问与您的 AWS Supply Chain 实例相关的问题**

[Amazon Q in AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/qinasc.html) 是一款交互式生成人工智能助手，可帮助您更有效地运营供应链。Amazon Q 可以执行以下操作：
+ 分析数据湖中的 AWS Supply Chain 数据。
+ 提供运营和财务见解。
+ 回答您当前的供应链问题。

有关使用 Amazon Q 的更多信息，请参阅 AWS Supply Chain 文档[中的启用 Ama](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/enabling_QinASC.html) [zon Q AWS Supply Chain和使用 Amazon Q](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/using_QinASC.html)。 AWS Supply Chain

# 自动执行 AWS 资源评测
<a name="automate-aws-resource-assessment"></a>

*Naveen Suthar、Arun Bagal、Manish Garg 和 Sandeep Gawande，Amazon Web Services*

## Summary
<a name="automate-aws-resource-assessment-summary"></a>

此示例介绍了一种使用 [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 设置资源评测功能的自动方法。通过使用这种模式，运营团队可以自动收集资源审计详细信息，并在单个控制面板上查看部署在 AWS 账户中的所有资源的详细信息。这在以下用例中很有用：
+ 识别基础设施即代码 (IaC) 工具，隔离由不同 IaC 解决方案（例如 Ter [HashiCorp raform](https://www.terraform.io/)、AWS CloudFormation、AWS CDK 和 AW [S](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) [命令行](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)界面 (AWS CLI)）创建的资源
+ 获取资源审计信息

该解决方案还将帮助领导团队通过单独的控制面板深入了解 AWS 账户中的资源和活动。


| 
| 
| 注意：[Amazon Quick Sight](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) 是一项付费服务。在运行它来分析数据和创建控制面板之前，请查看 [Amazon Quick Sight 的定价](https://aws.amazon.com/quicksight/pricing/)。 | 
| --- |

## 先决条件和限制
<a name="automate-aws-resource-assessment-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ AWS Identity and Acccess Management（IAM）角色和权限，具有预配置资源访问权限
+ [创建的 [Amazon Quick 账户](https://docs.aws.amazon.com/quicksight/latest/user/signing-up.html)，可以访问[亚马逊简单存储服务 (Amazon S3) 和亚马逊 A](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) thena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html)
+ 已安装 2.55.1 或更高版本的 AWS CDK。
+ 已安装 3.9 或更高版本的 [Python](https://www.python.org/downloads/release/python-390/)。

**限制**
+ 此解决方案部署至单个 AWS 账户。
+ 除非已设置 AWS 并将数据存储在 S3 存储桶中，否则 CloudTrail 该解决方案不会跟踪部署前发生的事件。

**产品版本**
+ AWS CDK 版本 2.55.1 或更高版本
+ Python 版本 3.9 或更高版本

## 架构
<a name="automate-aws-resource-assessment-architecture"></a>

**目标技术堆栈**
+ Amazon Athena
+ AWS CloudTrail
+ AWS Glue
+ AWS Lambda
+ Amazon Quick Sight
+ Amazon S3

**目标架构**

AWS CDK 代码将部署所有资源，这些资源是在 AWS 账户中设置资源评测功能的必要条件。下图显示了向 AWS Glue、Amazon Athena 和 Quick Sight 发送 CloudTrail 日志的过程。

![\[AWS Glue、Amazon Athena 和 QuickSight 亚马逊的 AWS 资源评估分为六个步骤。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a504774e-db7a-4c36-a22c-ce56d252fb58/images/8f2b549d-33a8-4cbf-86fd-33244716b668.png)


1. CloudTrail 将日志发送到 S3 存储桶进行存储。

1. 事件通知会调用 Lambda 函数，以处理日志并生成经过筛选数据。

1. 筛选后的数据存储至另一个 S3 存储桶。

1. 在 S3 存储桶中的筛选数据上设置 AWS Glue 爬网程序，以便在 AWS Glue Data Catalog 表创建架构。

1. 筛选后的数据已就绪，可供 Amazon Athena 查询。

1. Quick Sight 可以访问查询的数据以进行可视化。

**自动化和扩展**
+ 如果 AWS Organizations 中存在组织范围的 CloudTrail 跟踪，则该解决方案可以从一个 AWS 账户扩展到多个 AWS 账户。通过在组织 CloudTrail 级别部署，您还可以使用此解决方案来获取所有所需资源的资源审计详细信息。
+ 此模式使用 AWS 无服务器资源部署解决方案。

## 工具
<a name="automate-aws-resource-assessment-tools"></a>

**Amazon Web Services**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一种交互式查询服务，可帮助您使用标准 SQL 直接在 Amazon S3 中分析数据。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一个软件开发框架，可帮助您在代码中定义和预调配 Amazon Web Services Cloud 基础设施。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可帮助您设置 AWS 资源，快速一致地配置这些资源，并在 AWS 账户和 AWS 区域的整个生命周期中对其进行管理。
+ [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) 可帮助您审计 AWS 账户的治理、合规和运营风险。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是一项完全托管的提取、转换、加载（ETL）服务。它可以帮助您在数据存储和数据流之间对数据进行可靠地分类、清理、扩充和移动。此模式使用 AWS Glue 爬网程序与 AWS Glue Data Catalog 表。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，而无需预置或管理服务器。它仅在需要时运行您的代码，并且能自动扩缩，因此您只需为使用的计算时间付费。
+ [Amazon Quick](https://docs.aws.amazon.com/quicksight/latest/user/welcome.html) 是一项云规模的商业智能 (BI) 服务，可帮助您在单个控制面板中可视化、分析和报告数据。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**代码存储库 **

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

此代码存储库包含以下文件和文件夹：
+ `lib` 文件夹 — 用于创建 AWS 资源的 AWS CDK 构造 Python 文件
+ `src/lambda_code` — 在 Lambda 函数中运行的 Python 代码
+ `requirements.txt` — 必须安装的所有 Python 依赖项列表
+ `cdk.json` — 用于提供启动资源所需值的输入文件

## 最佳实践
<a name="automate-aws-resource-assessment-best-practices"></a>

为 Lambda 函数设置监控和警报。有关更多信息，请参阅 [Lambda 函数监控和故障排除](https://docs.aws.amazon.com/lambda/latest/dg/lambda-monitoring.html)。有关使用 Lambda 函数时的一般最佳实践标准，请参阅 [AWS 文档](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)

## 操作说明
<a name="automate-aws-resource-assessment-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在本地机器克隆存储库。 | 要克隆存储库，请运行 `git clone https://github.com/aws-samples/infrastructure-assessment-iac-automation.git`命令。 | AWS DevOps， DevOps 工程师 | 
| 设置 Python 虚拟环境以及安装所需依赖项。 | 要设置 Python 虚拟环境，请运行以下命令。<pre>cd infrastructure-assessment-iac-automation<br />python3 -m venv .venv<br />source .venv/bin/activate</pre>要设置所需依赖项，请运行命令 `pip install -r requirements.txt`。 | AWS DevOps， DevOps 工程师 | 
| 设置 AWS CDK 环境和合成 AWS CDK 代码。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps， DevOps 工程师 | 

### 在本地机器上设置 AWS 凭证
<a name="set-up-aws-credentials-on-your-local-machine"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为待部署堆栈的账户和区域导出变量。 | 要使用环境变量为 AWS CDK 提供 AWS 凭证，请运行以下命令。<pre>export CDK_DEFAULT_ACCOUNT=<12 Digit AWS Account Number><br />export CDK_DEFAULT_REGION=<region></pre> | AWS DevOps， DevOps 工程师 | 
| 设置 AWS CLI 配置文件。 | 要为账户设置 AWS CLI 配置文件，请按 [AWS 文档](https://docs.aws.amazon.com/toolkit-for-visual-studio/latest/user-guide/keys-profiles-credentials.html)中的说明进行操作。 | AWS DevOps， DevOps 工程师 | 

### 配置和部署资源评测工具
<a name="configure-and-deploy-the-resource-assessment-tool"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在账户中部署资源。 | 若要使用 AWS CDK 在 AWS 账户中部署资源，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps | 
| 运行 AWS Glue 爬网程序，并创建数据目录表。 | [AWS Glue 爬网程序](https://docs.aws.amazon.com/glue/latest/dg/add-crawler.html)用于保持数据架构的动态性。该解决方案通过按照 AWS Glue 爬网程序调度程序的定义定期运行爬网程序来创建和更新 [AWS Glue Data Catalog](https://docs.aws.amazon.com/athena/latest/ug/querying-glue-catalog.html) 表中的分区。在输出 S3 存储桶中有数据后，使用以下步骤运行 AWS Glue 爬网程序，并创建用于测试的数据目录表架构：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html)AWS CDK 代码将 AWS Glue 爬网程序配置为在特定时间运行，但您也可以按需运行。 | AWS DevOps， DevOps 工程师 | 
| 部署 Quick Sight 构造。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps， DevOps 工程师 | 
| 创建快速查看仪表板。 | 要创建示例 Quick Sight 仪表板和分析，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html)有关更多信息，请参阅在 Amazon Qu [ick Sight 中开始分析和在 Amazon Q](https://docs.aws.amazon.com/quicksight/latest/user/creating-an-analysis.html) u [ick Sight 中启动视觉类型](https://docs.aws.amazon.com/quicksight/latest/user/working-with-visual-types.html)。 | AWS DevOps， DevOps 工程师 | 

### 清理解决方案中的所有 AWS 资源
<a name="clean-up-all-aws-resources-in-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 移除 AWS 资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps， DevOps 工程师 | 

### 基于 AWS 资源评测工具自动化设置其他功能
<a name="set-up-additional-features-on-top-of-the-aws-resource-assessment-tool-automation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 监控和清理手动创建资源。 | （可选）如果您的组织有使用 IaC 工具创建资源的合规性要求，则您可以使用 AWS 资源评测工具，自动获取手动配置的资源，从而实现合规。您也可以使用此工具将资源导入至 IaC 工具或重新创建这些资源。若要监控手动配置的资源，请执行以下概要任务：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps， DevOps 工程师 | 

## 问题排查
<a name="automate-aws-resource-assessment-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| AWS CDK 会返回错误信息。 | 要获得有关 AWS CDK 问题的帮助，请参阅[常见 AWS CDK 问题疑难解答](https://docs.aws.amazon.com/cdk/v2/guide/troubleshooting.html)。 | 

## 相关资源
<a name="automate-aws-resource-assessment-resources"></a>
+ [使用 Python 构建 Lambda 函数](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python.html)
+ [AWS CDK 入门](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)
+ [在 Python 中使用 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-python.html)
+ [创建 CloudTrail 日志跟踪](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-create-and-update-a-trail.html)
+ [开始使用 Amazon Quick Sight](https://aws.amazon.com/quicksight/getting-started/)

## 附加信息
<a name="automate-aws-resource-assessment-additional"></a>

**多个账户**

若要为多个账户设置 AWS CLI 凭证，请使用 AWS 配置文件。有关更多信息，请参阅[设置 AWS CLI](https://aws.amazon.com/getting-started/guides/setup-environment/module-three/) 中的*配置多项配置文件*部分。

**AWS CDK 命令**

使用 AWS CDK 时，切记以下有用的命令：
+ 列出应用程序的所有堆栈

  ```
  cdk ls
  ```
+ 发出合成的 AWS 模板 CloudFormation 

  ```
  cdk synth
  ```
+ 将堆栈部署至您的默认 AWS 账户和区域

  ```
  cdk deploy
  ```
+ 将已部署的堆栈与当前状态比较

  ```
  cdk diff
  ```
+ 打开 AWS CDK 文档

  ```
  cdk docs
  ```

# 使用开源工具自动安装 SAP 系统
<a name="install-sap-systems-automatically-by-using-open-source-tools"></a>

*Guilherme Sesterheim，Amazon Web Services*

## Summary
<a name="install-sap-systems-automatically-by-using-open-source-tools-summary"></a>

此模式介绍了如何使用开源工具创建以下资源，以自动安装 SAP 系统：
+ SAP S/4HANA 1909 数据库
+ 一个 SAP ABAP 中央服务 (ASCS) 实例
+ 一个 SAP 主应用程序服务器 (PAS) 实例

HashiCorp Terraform 创建 SAP 系统的基础架构，Ansible 配置操作系统 (OS) 并安装 SAP 应用程序。Jenkins 运行安装。

这种设置将 SAP 系统的安装变成了可重复的过程，有助于提高部署效率和质量。

**注意**  
此模式中提供的示例代码适用于高可用性（HA）系统和非高可用性系统。

## 先决条件和限制
<a name="install-sap-systems-automatically-by-using-open-source-tools-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 包含所有 SAP 媒体文件的 Amazon Simple Storage Service (Amazon S3) 存储桶
+ 具有[访问密钥和私有密钥](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html)、并有以下权限的 AWS Identity and Access Management (IAM) 主体：
  + **只读权限：**Amazon Route 53、AWS Key Management Service (AWS KMS)
  + **读写权限：**亚马逊 S3、亚马逊弹性计算云（亚马逊）、亚马逊弹性文件系统（亚马逊 EFS EC2）、IAM、亚马逊、亚马逊 CloudWatch、亚马逊 DynamoDB
+ Route 53 [私有托管区域](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html)
+ 在 Amazon Marketplace 中订阅 [Red Hat Enterprise Linux for SAP with HA and Update Services 8.2](https://aws.amazon.com/marketplace/pp/prodview-5grz5a5thx7c2) 亚马逊机器映像（AMI）
+ [AWS KMS 客户托管密钥](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html#aws-managed-customer-managed-keys)
+ [Secure Shell (SSH) 密钥对](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)
+ 一个 [Amazon EC2 安全组](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security-groups.html)，允许从你安装 Jenkins 的主机名在端口 22 上进行 SSH 连接（主机名很可能是**本地主**机）
+  HashiCorp 已安装和@@ [配置的 Vagrant](https://www.vagrantup.com/)
+ [VirtualBox](https://www.virtualbox.org/)由 Oracle 安装和配置
+ 熟悉 Git、Terraform、Ansible 以及 Jenkins

**限制**
+ 仅 SAP S/4HANA 1909 针对此特定场景进行了全面测试。如果您使用其他版本的 SAP HANA，则需要修改此模式中的示例 Ansible 代码。
+ 此模式中的示例程序适用于 Mac OS 和 Linux 操作系统。部分命令只能在基于 Unix 的终端中运行。但是，您可通过使用不同的命令和 Windows 操作系统，以获得类似的结果。

**产品版本**
+ SAP S/4HANA 1909
+ Red Hat Enterprise Linux (RHEL) 8.2 或更高版本

## 架构
<a name="install-sap-systems-automatically-by-using-open-source-tools-architecture"></a>

下图介绍了使用开源工具在 Amazon Web Services account 中自动安装 SAP 系统的示例工作流：

![\[使用开源工具在 AWS 账户中自动安装 SAP 系统的示例工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/aaf11dac-38cc-4e89-be86-51d4409cf238/images/d7902f9d-f1be-461f-b69b-cf3c663c8f2f.png)


下图显示了如下工作流：

1. Jenkins 通过运行 Terraform 和 Ansible 代码编排 SAP 系统安装的运行。

1. Terraform 代码构建 SAP 系统基础设施。

1. Ansible 代码配置操作系统和安装 SAP 应用程序。

1. Amazon 实例上安装了 SAP S/4HANA 1909 数据库、ASCS 实例和包含所有已定义先决条件的 PAS 实例。 EC2 

**注意**  
此模式中的示例设置会自动在您的 AWS 账户中创建 Amazon S3 存储桶，以存储 Terraform 状态文件。

**技术堆栈**
+ Terraform
+ Ansible
+ Jenkins
+ SAP S/4HANA 1909 数据库
+ SAP ASCS 实例
+ SAP PAS 实例
+ Amazon EC2 

## 工具
<a name="install-sap-systems-automatically-by-using-open-source-tools-tools"></a>

**AWS 服务**
+ [亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/ec2/?id=docs_gateway) 在 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) 可帮助您创建和控制加密密钥以保护您的数据。
+ [Amazon Virtual Private Cloud (Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) 可帮助您将 AWS 资源启动到您定义的虚拟网络中。此虚拟网络类似于您在自己的数据中心内运行的传统网络，具有使用 AWS 可扩展基础设施的优势。

**其他工具**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款命令行界面应用程序，可帮助您使用代码来配置和管理云基础架构和资源。
+ [Ansible](https://www.ansible.com/) 是一款开源配置即代码 (CaC) 工具，可帮助实现应用程序、配置和 IT 基础设施的自动化。
+ [Jenkins](https://www.jenkins.io/) 是一款开源自动化服务器，它使开发人员能够构建、测试和部署其软件。

**代码**

此模式的代码可在 GitHub [aws-install-sap-with-jenkins-](https://github.com/aws-samples/aws-install-sap-with-jenkins-ansible) ansible 存储库中找到。

## 操作说明
<a name="install-sap-systems-automatically-by-using-open-source-tools-epics"></a>

### 配置先决条件
<a name="configure-the-prerequisites"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将您的 SAP 媒体文件添加至 Amazon S3 存储桶。 | [创建包含所有 SAP 媒体文件的 Amazon S3 存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)。请务必遵守 [Launch Wizard 文档](https://docs.aws.amazon.com/launchwizard/latest/userguide/launch-wizard-sap-software-install-details.html)中 **S/4HANA** 的 AWS Launch Wizard 文件夹层次结构。 | 云管理员 | 
| 安装 VirtualBox。 | [VirtualBox](https://www.virtualbox.org/)由 Oracle 安装和配置。 | DevOps 工程师 | 
| 安装 Vagrant。 | 通过以下方式安装和配置 [Vagrant](https://www.vagrantup.com/)。 HashiCorp | DevOps 工程师 | 
| 配置 Amazon Web Services account。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html) | 常规 AWS | 

### 构建和运行您的 SAP 安装
<a name="build-and-run-your-sap-installation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 从中克隆代码存储库 GitHub。 | 在上克隆 [aws-install-sap-with-jenkins-an](https://github.com/aws-samples/aws-install-sap-with-jenkins-ansible) sible 存储库。 GitHub | DevOps 工程师 | 
| 启动 Jenkins 服务。 | 打开 Linux 终端。然后，导航至包含克隆代码存储库文件夹的本地文件夹，并运行以下命令：<pre>sudo vagrant up</pre>Jenkins 启动大约需要 20 分钟。成功后，该命令会返回**服务已启动并正在运行**消息。 | DevOps 工程师 | 
| 在 Web 浏览器中打开并登录 Jenkins。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html) | DevOps 工程师 | 
| 配置 SAP 系统安装参数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html)您可根据您的使用案例按需配置其他非必需参数。例如，您可以更改实例的 SAP 系统 ID (SID)、SAP 系统的默认密码、名称和标签。所有必需变量的名称开头都有**（必填）**。 | AWS 系统管理员、 DevOps 工程师 | 
| 运行您的 SAP 系统安装。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html)有关管道操作步骤的信息，请参阅 AWS Blog 上的[使用开源工具自动化 SAP 安装](https://aws.amazon.com/blogs/awsforsap/automating-sap-installation-with-open-source-tools/)中的**了解管道操作步骤**部分。如果发生错误，请将光标移至所示红色错误框，然后选择**日志**。显示错误管道操作步骤日志。大多数错误的原因是参数设置不正确。 | DevOps 工程师，AWS 系统管理员 | 

## 相关资源
<a name="install-sap-systems-automatically-by-using-open-source-tools-resources"></a>
+ [DevOps 适用于 SAP — SAP 安装：从 2 个月到 2 小时](https://videos.itrevolution.com/watch/707351918/)（DevOps 企业峰会视频库）

# 使用 AWS CDK 自动部署 AWS Service Catalog 产品组合与产品
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk"></a>

*Sandeep Gawande、Viyoma Sachdeva 和 RAJNEESH TYAGI，Amazon Web Services*

## Summary
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-summary"></a>

AWS Service Catalog 可帮助您集中管理获准在组织 AWS 环境中使用的 IT 服务或*产品*目录。一系列产品称为*产品组合*，产品组合还包含配置信息。利用 AWS Service Catalog，您可以为组织内的每类用户创建一个自定义产品组合，然后授予对适当产品组合的访问权限。然后，这些用户可在产品组合中快速部署他们需要的任何产品。

如果您拥有复杂的网络基础架构（例如多区域和多账户架构），建议您在单个中央账户中创建和管理服务目录组合。此模式介绍如何使用 AWS Cloud Development Kit（AWS CDK）在中央账户中自动创建服务目录组合，向最终用户授予访问权限，然后选择向一个或多个目标 AWS 账户配置产品。此 ready-to-use解决方案在源账户中创建 Service Catalog 产品组合。它还可以选择使用 AWS CloudFormation 堆栈在目标账户中配置产品，并帮助您 TagOptions 为产品进行配置：
+ **AWS CloudFormation StackSets** — 您可以使用 StackSets 在多个 AWS 区域和账户中启动 Service Catalog 产品。在此解决方案中，您可选择在部署此解决方案时自动配置产品。有关更多信息，请参阅[使用 AWS CloudFormation StackSets（S](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/using-stacksets.html) ervice Catalog 文档）和[StackSets 概念](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-concepts.html)（CloudFormation 文档）。
+ **TagOption 库**-您可以使用 TagOption 库管理已配置产品的标签。A *TagOption*是在 AWS Service Catalog 中管理的键值对。它不是 AWS 标签，但它可以用作基于创建 AWS 标签的模板 TagOption。有关更多信息，请参阅[TagOption 库](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/tagoptions.html)（Service Catalog 文档）。

## 先决条件和限制
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-prereqs"></a>

**先决条件**
+ 用作管理 Service Catalog 产品组合的源账户的活跃 AWS 账户
+ 如果您使用此解决方案在一个或多个目标客户中配置产品，则目标账户必须已经存在并且处于活动状态。
+ AWS Identity and Access Management (IAM) 权限，用于访问 AWS Service Catalog CloudFormation、AWS 和 AWS IAM。

**产品版本**
+ AWS CDK 版本 2.27.0

## 架构
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-architecture"></a>

**目标技术堆栈**
+ 集中式 AWS 账户中的 Service Catalog 产品组合
+ 部署至目标账户的 Service Catalog 产品

**目标架构**

![\[AWS CDK 创建 Service Catalog 产品组合，并在目标账户中配置产品。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e8f217a7-aec4-4c85-8f6b-f91995506be0/images/1f027b82-14c3-485a-909b-1544e974b90a.png)


1. 在产品组合（或*源*）账户中，您可使用您的使用案例的 AWS 账户、AWS 区域、IAM 角色、产品组合和产品信息更新 **config.json** 文件。

1. 您部署 AWS CDK 应用程序。

1. AWS CDK 应用程序扮演部署 IAM 角色并创建 **config.json** 文件中定义的 Service Catalog 产品组合和产品。

   如果您配置 StackSets 为在目标账户中部署产品，则该过程将继续进行。如果您未配置 StackSets 为配置任何产品，则该过程已完成。

1. AWS CDK 应用程序扮演**StackSet 管理员**角色并部署您在 c **onfig.** json 文件中定义的 AWS CloudFormation 堆栈集。

1. 在目标账户中， StackSets 担任**StackSet 执行**角色并配置产品。

## 工具
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-tools"></a>

**Amazon Web Services**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一个软件开发框架，可帮助您在代码中定义和预调配 Amazon Web Services Cloud 基础设施。
+ [AWS CDK Toolkit](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) 是一个命令行云开发套件，可帮助您与 AWS CDK 应用程序进行交互。
+ [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 Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html) 可帮助您集中管理获准在 AWS 上使用的 IT 服务目录。最终用户可在遵循组织设定约束的情况下快速部署他们所需已获得批准的 IT 服务。

**代码存储库**

此模式的代码可在 GitHub[aws-cdk-servicecatalog-automation](https://github.com/aws-samples/aws-cdk-servicecatalog-automation.git)存储库中找到。此代码存储库包含以下文件和文件夹：
+ **cdk-sevicecatalog-app**— 此文件夹包含此解决方案的 AWS CDK 应用程序。
+ **config** — 此文件夹包含 **config.json** 文件和用于在 Service Catalog 产品组合中部署产品的 CloudFormation 模板。
+ **config/config.json** — 该文件包含所有配置信息。您可更新此文件，以针对您的用例自定义此解决方案。
+ **config/tem** plates — 此文件夹包含服务中心产品的 CloudFormation 模板。
+ **setup.sh** — 此脚本部署解决方案。
+ **uninstall.sh** — 此脚本删除部署此解决方案时所创建的堆栈和所有 AWS 资源。

若要使用示例代码，请按照[操作](#automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-epics)部分的说明执行。

## 最佳实践
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-best-practices"></a>
+ 用于部署此解决方案的 IAM 角色应遵守[最低权限原则](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)（IAM 文档）。
+ [遵守使用 AWS CDK 开发云应用程序的最佳实践](https://aws.amazon.com/blogs/devops/best-practices-for-developing-cloud-applications-with-aws-cdk/)（AWS Blog 文章）。
+ 遵守 A [WS CloudFormation 最佳实践](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/best-practices.html)（CloudFormation 文档）。

## 操作说明
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装 AWS CDK Toolkit。 | 确保您已安装 AWS CDK Toolkit。输入以下命令，以确认是否已安装并检查版本。 <pre>cdk --version</pre>如果未安装 AWS CDK Toolkit，请输入以下命令以进行安装。<pre>npm install -g aws-cdk@2.27.0</pre>如果 AWS CDK Toolkit 版本低于 2.27.0，则输入以下命令，以将其更新至 2.27.0 版本。<pre>npm install -g aws-cdk@2.27.0 --force</pre> | AWS DevOps， DevOps 工程师 | 
| 克隆存储库。 | 输入如下命令。在[其他信息](#automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-additional)部分的*克隆存储库*中，您可以复制包含存储库 URL 的完整命令。这将从中克隆[aws-cdk-servicecatalog-automation](https://github.com/aws-samples/aws-cdk-servicecatalog-automation)存储库。 GitHub<pre>git clone <repository-URL>.git</pre>这将在目标目录中创建 `cd aws-cdk-servicecatalog-automation` 文件夹。输入以下命令以导航至此文件夹。<pre>cd aws-cdk-servicecatalog-automation</pre> | AWS DevOps， DevOps 工程师 | 
| 设置 AWS 凭证。 | 输入以下命令。它们会导出以下变量，这些变量定义您要部署堆栈的 AWS 账户和区域。<pre>export CDK_DEFAULT_ACCOUNT=<12-digit AWS account number></pre><pre>export CDK_DEFAULT_REGION=<AWS Region></pre>AWS CDK 的 AWS 凭证是通过环境变量提供的。 | AWS DevOps， DevOps 工程师 | 
| 为最终用户 IAM 角色配置权限。 | 如果您要使用 IAM 角色授予对产品组合及其中的产品的访问权限，则这些角色必须具有由 **servicecatalog.amazonaws.com** 服务主体担任的权限。有关如何授予这些权限的说明，请参阅[使用 Service Catalog 启用可信访问](https://docs.aws.amazon.com/organizations/latest/userguide/services-that-can-integrate-servicecatalog.html#integrate-enable-ta-servicecatalog)(AWS Organizations 文档)。 | AWS DevOps， DevOps 工程师 | 
| 配置所需的 IAM 角色 StackSets。 | 如果您使用 StackSets 在目标账户中自动配置产品，则需要配置管理和运行堆栈集的 IAM 角色。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.html) | AWS DevOps， DevOps 工程师 | 

### 自定义与部署解决方案
<a name="customize-and-deploy-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 CloudFormation 模板。 | 在该`config/templates`文件夹中，为要包含在产品组合中的任何产品创建 CloudFormation 模板。有关更多信息，请参阅[使用 AWS CloudFormation 模板](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)（CloudFormation 文档）。 | 应用程序开发人员、AWS DevOps、 DevOps 工程师 | 
| 自定义配置文件。 | 在 `config` 文件夹中，打开 **config.json** 文件。并根据您的用例定义相应的参数。若非另有说明，以下参数为必需参数：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.html)有关已完成的配置文件的示例，请参阅[其他信息](#automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-additional)部分的*示例配置文件*。 | 应用程序开发人员、 DevOps 工程师、AWS DevOps | 
| 部署解决方案。 | 输入如下命令。这将部署 AWS CDK 应用程序，并按照 **config.json** 文件中指定的方式配置 Service Catalog 产品组合和产品。<pre>sh +x setup.sh</pre> | 应用程序开发人员、 DevOps 工程师、AWS DevOps | 
| 验证部署。 | 通过执行以下操作，验证部署是否成功：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.html) | 常规 AWS | 
| （可选）更新产品组合与产品。 | 如果您想使用此解决方案更新产品组合、产品或配置新产品：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.html)例如，您可添加其他产品组合或预配置更多资源。AWS CDK 应用程序仅实施更改。如果先前部署的产品组合或产品无变化，则重新部署不会影响它们。 | 应用程序开发人员、 DevOps 工程师、通用 AWS | 

### 清理解决方案
<a name="clean-up-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| （可选）移除此解决方案所部署的 AWS 资源。 | 如果要删除预配置产品，请按[删除预配置产品](https://docs.aws.amazon.com/servicecatalog/latest/userguide/enduser-delete.html)（Service Catalog 文档）中的说明进行操作。如果您想删除此解决方案所创建的所有资源，请输入以下命令。<pre>sh uninstall.sh</pre> | AWS DevOps， DevOps 工程师，应用程序开发人员 | 

## 相关资源
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-resources"></a>
+ [AWS Service Catalog Construct Library](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_servicecatalog-readme.html)（AWS API 参考）
+ [StackSets 概念](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-concepts.html)（CloudFormation 文档）
+ [AWS Service Catalog](https://aws.amazon.com/servicecatalog)（AWS Marketing）
+ [在 AWS CDK 中使用 Service Catalog](https://catalog.us-east-1.prod.workshops.aws/workshops/d40750d7-a330-49be-9945-cde864610de9/en-US/4-builders-devs/sc-cdk)（AWS 研讨会）

## 附加信息
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk-additional"></a>

**克隆存储库**

输入以下命令以从中克隆存储库 GitHub。

```
git clone https://github.com/aws-samples/aws-cdk-servicecatalog-automation.git
```

**示例配置文件**

以下是带示例值的 **config.json** 文件示例。

```
{
    "portfolios": [
        {
            "displayName": "EC2 Product Portfolio",
            "providerName": "User1",
            "description": "Test1",
            "roles": [
                "<Names of IAM roles that can access the products>"
            ],
            "users": [
                "<Names of IAM users who can access the products>"
            ],
            "groups": [
                "<Names of IAM user groups that can access the products>"
            ]
        },
        {
            "displayName": "Autoscaling Product Portfolio",
            "providerName": "User2",
            "description": "Test2",
            "roles": [
                "<Name of IAM role>"
            ]
        }
    ],
    "tagOption": [
        {
            "key": "Group",
            "value": [
                "finance",
                "engineering",
                "marketing",
                "research"
            ]
        },
        {
            "key": "CostCenter",
            "value": [
                "01",
                "02",
                "03",
                "04"
            ]
        },
        {
            "key": "Environment",
            "value": [
                "dev",
                "prod",
                "stage"
            ]
        }
    ],
    "products": [
        {
            "portfolioName": "EC2 Product Profile",
            "productName": "Ec2",
            "owner": "owner1",
            "productVersionName": "v1",
            "templatePath": "../../config/templates/template1.json"
        },
        {
            "portfolioName": "Autoscaling Product Profile",
            "productName": "autoscaling",
            "owner": "owner1",
            "productVersionName": "v1",
            "templatePath": "../../config/templates/template2.json",
            "deployWithStackSets": {
                "accounts": [
                    "012345678901",
                ],
                "regions": [
                    "us-west-2"
                ],
                "stackSetAdministrationRoleName": "AWSCloudFormationStackSetAdministrationRole",
                "stackSetExecutionRoleName": "AWSCloudFormationStackSetExecutionRole"
            }
        }
    ]
}
```

# 使用和自动进行动态管道管理，以便在 Gitflow 环境中部署修补程序解决方案 AWS Service Catalog AWS CodePipeline
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions"></a>

*Balaji Vedagiri、Faisal Shahdad、Shanmugam Shanker 和 Vivek Thangamuthu，Amazon Web Services*

## Summary
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-summary"></a>

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

此模式适用于管理专门用于将修补程序解决方案安全地部署到生产环境的动态修补程序管道的情况。该解决方案是通过使用产品 AWS Service Catalog 组合和产品来实施和管理的。Amazon EventBridge 规则用于事件自动化。使用 Service Catalog 产品组合约束以及开发人员的 AWS Identity and Access Management （IAM）角色强制执行限制。只有一个 AWS Lambda 函数可以启动由 EventBridge 规则触发的 Service Catalog 产品。此模式专为采用特定 Gitflow 设置的环境而设计，详见[附加信息](#automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-additional)。

通常，部署修补程序是为了解决在实时环境（例如生产）中报告的关键问题或安全问题。修补程序应当仅直接部署到暂存和生产环境。暂存和生产管道广泛用于常规开发请求。这些管道不能用于部署修补程序，因为质量保证中有一些在研功能无法部署到生产中。为了发布修补程序，该模式描述了具有以下安全功能的动态、短暂的管道：
+ **自动创建**-每当在存储库中创建修补程序分支时，都会自动创建修补程序管道。 AWS CodeCommit 
+ **访问限制** - 开发人员无权在修补程序流程之外创建此管道。
+ **受控阶段** – 管道具有使用特殊访问令牌的受控阶段，确保拉取请求（PR）只能创建一次。
+ **审批阶段** – 审批阶段包括在该管道中，以获得相关干系人的必要审批。
+ **自动删除**-每当仓库中的分支与 PR 合并后，只要删除 CodeCommit 存储库中的`hotfix`分支，就会自动删除该修补程序管道。

## 先决条件和限制
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-prereqs"></a>

**先决条件**
+ 需要三个 AWS 账户 处于活动状态，如下所示：
  + 工具账户 - 用于持续集成和持续交付（CI/CD）设置。
  + 暂存账户 - 用于用户验收测试。
  + 生产账户 - 用于企业最终用户。
  + （可选）添加一个 AWS 账户 以充当 QA 帐户。如果您想要同时使用主管道设置（包括 QA）和修补程序管道解决方案进行测试，则需要此账户。
+ 具有可选条件的 AWS CloudFormation 堆栈，可根据需要使用主管道在 QA 账户中部署。通过创建和删除 `hotfix` 分支，仍然可以在没有主管道设置的情况下测试该模式。
+ 亚马逊简单存储服务 (Amazon S3) 存储桶，用于存储 CloudFormation 用于创建服务目录产品的模板。
+ 根据合规性要求为 CodeCommit 存储库创建 PR 批准规则（在创建存储库之后）。
+ 限制开发人员和团队负责人的 IAM 权限以禁止其执行 [prcreation-lambda](https://github.com/aws-samples/dynamic_hotfix_codepipeline/blob/main/pre-requisites/lambdasetup.yaml#L55) Lambda 函数，因为该函数仅应从管道中调用。

**限制**
+ 在部署阶段使用 CloudFormation 提供程序，使用 CloudFormation 更改集部署应用程序。如果要使用其他部署选项，请根据需要修改 CodePipeline 堆栈。
+ 此模式使用 AWS CodeBuild 和其他配置文件来部署示例微服务。如果您有不同的工作负载类型（例如，无服务器工作负载），则必须更新所有相关配置。
+ 这种模式将应用程序部署在单个 AWS 区域 （例如，美国东部（弗吉尼亚北部）us-east-1）中。 AWS 账户要跨多个区域进行部署，请更改命令和堆栈中的区域引用。
+ 有些 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="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-architecture"></a>

本节中的图表提供了创建生命周期事件和删除生命周期事件的工作流。

![\[创建生命周期事件的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/64311acc-8c0f-4734-aa1b-74345d86c752/images/3939f77c-4221-4c23-a3a1-3e8a294b2b32.png)


上面创建生命周期事件的图表显示了以下内容：

1. 开发人员在 CodeCommit 存储库中创建一个`hotfix-*`分支来开发与 hotfix 相关的解决方案。

1. 分`hotfix-*`支创建事件是通过 EventBridge 规则捕获的。事件详细信息包括存储库名称和分支名称。

1. 该 EventBridge 规则调用该函数。 AWS Lambda `hotfix-lambda-function`该 EventBridge 规则将事件信息作为输入传递给 Lambda 函数。

1. Lambda 函数处理输入以检索存储库名称和分支名称。它使用从处理的输入中检索到的值启动 Service Catalog 产品。

1. Service Catalog 产品包括将解决方案部署到预发布和生产环境的管道设置。管道块包括源、构建和部署阶段。此外，还有一个手动批准阶段，可以促进生产环境的部署。

1. 源阶段从第一步中创建的存储库和 `hotfix-*` 分支检索代码。该代码通过用于存放构件的 Amazon S3 存储桶传递到构建阶段。在构建阶段，将创建一个容器映像，其中包含在 `hotfix-*` 分支中开发并推送到 Amazon Elastic Container Registry（Amazon ECR）中的修补程序。

1. 预发布环境的部署阶段使用包含此修补程序的最新容器映像更新 Amazon Elastic Container Service（Amazon ECS）。此修补程序是通过创建和执行 CloudFormation 更改集来部署的。

1. 在 Stage 环境中成功部署后调用 `prcreation-lambda` Lambda 函数。此 Lambda 函数创建从 `hotfix-*` 分支到存储库 `develop` 和 `main` 分支的 PR。Lambda 函数可确保 `hotfix-*` 分支中开发的修复程序被回溯并包含在后续部署中。

1. 手动批准阶段有助于确保必要的利益相关者审核该修复并批准在生产环境中部署。

1. 生产环境的部署阶段使用包含此修补程序的最新容器映像更新 Amazon ECS。此修补程序是通过创建和执行 CloudFormation 更改集来部署的。

![\[删除生命周期事件的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/64311acc-8c0f-4734-aa1b-74345d86c752/images/192aa897-bd9b-4a9f-804e-340371612b3b.png)


上面删除生命周期事件的图表显示了以下内容：

1. 成功将修补程序部署到生产环境后，开发人员会删除该 `hotfix-*` 分支。

1. 分`hotfix-*`支删除事件是通过 EventBridge 规则捕获的。事件详细信息包括存储库名称和分支名称。

1. 该 EventBridge 规则调用 Lambda 函数。该 EventBridge 规则将事件信息作为输入传递给 Lambda 函数。

1. Lambda 函数处理输入以检索存储库名称和分支名称。Lambda 函数根据传递的输入确定相应的 Service Catalog 产品，然后终止该产品。

1. Service Catalog 预调配的产品终止会删除之前在该产品中创建的管道和相关资源。

**自动化和扩展**
+ 该模式包括一个 EventBridge 规则和一个 Lambda 函数，它们可以并行处理多个修补程序分支创建请求。Lambda 函数为匹配的事件规则预调配 Service Catalog 产品。
+ 管道设置通过使用提供版本控制功能的 Service Catalog 产品来处理。该解决方案还可以自动扩展，以并行处理同一应用程序的多个修补程序开发。
+ [prcreation-lambda](https://github.com/aws-samples/dynamic_hotfix_codepipeline/blob/main/pre-requisites/lambdasetup.yaml#L55) 函数可确保通过自动创建拉取请求，将这些修补程序更改合并回 `main` 和 `develop` 分支中。这种方法对于确保 `main` 和 `develop` 分支及时同步所有修复内容并避免潜在的代码回归至关重要。此过程通过确保所有长期存在的分支获得了最新的修复程序，有助于保持分支之间的一致性，并防止代码回归。

## 工具
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-tools"></a>

**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) 是一项完全托管式构建服务，可编译源代码、运行单元测试和生成部署就绪的构件。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) 是一项版本控制服务，可帮助您私下存储和管理 Git 存储库，而无需管理自己的源代码控制系统。 AWS CodeCommit 现已不再向新客户提供。的现有客户 AWS CodeCommit 可以继续照常使用该服务。有关更多信息，请参阅[如何将 AWS CodeCommit 仓库迁移到其他 Git 提供商](https://aws.amazon.com/blogs/devops/how-to-migrate-your-aws-codecommit-repository-to-another-git-provider/)。
+ [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) 是一项安全、可扩展且可靠的托管容器映像注册表服务。
+ [Amazon Elastic Container Service (Amazon ECS)](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html)是一项快速且可扩展的容器管理服务，可帮助运行、停止和管理集群上的容器。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可帮助您创建和控制加密密钥以帮助保护您的数据。
+ [AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html)帮助您集中管理已获批准的 IT 服务目录。 AWS最终用户可在遵循组织设定约束的情况下快速部署他们所需已获得批准的 IT 服务。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**其他工具**
+ [CloudFormation Linter（cfn-lint）是一款根据](https://github.com/aws-cloudformation/cfn-lint)[资源规范检查 CloudFormation YAML 或 JSON 模板的 linter。CloudFormation ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)它还会执行其他检查，例如检查资源属性的有效值以及是否遵守最佳实践。
+ [cfn-nag](https://github.com/stelligent/cfn_nag) 是一个开源工具，它通过搜索模式来识别 CloudFormation 模板中的潜在安全问题。
+ [Docker](https://www.docker.com/) 是一组平台即服务（PaaS）产品，它们使用操作系统级别的虚拟化技术在容器中交付软件。该模式使用 Docker 在本地构建和测试容器映像。
+ [Git](https://git-scm.com/docs) 是开源分布式版本控制系统。

**代码存储库**

此模式的代码可在 d GitHub [ynamic\$1hotfix\$1](https://github.com/aws-samples/dynamic_hotfix_codepipeline) codepipeline 存储库中找到。

## 最佳实践
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-best-practices"></a>

查看并调整您环境中的 IAM 角色和服务控制策略（SCP），以确保它们适当地限制访问。这对于防止任何可能覆盖此模式中包含的安全措施的行为至关重要。遵循最低权限原则，并授予执行任务所需的最低权限。有关详情，请参阅 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="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要将示例[存储库](https://github.com/aws-samples/dynamic_hotfix_codepipeline)克隆到工作地点的新目录中，请运行以下命令：<pre>git clone git@github.com:aws-samples/dynamic_hotfix_codepipeline.git</pre> | AWS DevOps | 
| 导出用于 CloudFormation 堆栈部署的环境变量。 | 定义以下环境变量，这些变量将在此模式的后面用作 CloudFormation 堆栈的输入。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html)<pre>export BucketStartName=<BucketName></pre>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html)<pre>export ProdAccount=<prodaccountnumber><br />export StageAccount=<stage/preprodaccountnumber><br />export QAAccount=<qaccountnumber><br />export ToolsAccount=<toolsaccountnumber><br />export DepRegion=<region></pre> | AWS DevOps | 

### 设置中必需的先决条件 AWS 账户
<a name="set-up-prerequisites-required-in-aws-accounts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在工具账户 CI/CD 中创建所需的资源。 | 要在工具账户中部署 CloudFormation 堆栈，请使用以下命令。（如果您不使用 QA 账户进行设置，请删除该 `QAAccount` 参数。）<pre>#InToolsAccount<br />aws cloudformation deploy \<br />    --template-file pre-requisites/pre-reqs.yaml \<br />    --stack-name prereqs \<br />    --parameter-overrides BucketStartName=${BucketStartName} \<br />    ApplicationName=${ApplicationName} ProdAccount=${ProdAccount} \<br />    StageAccount=${StageAccount} ToolsAccount=${ToolsAccount} \<br />    QAAccount=${QAAccount} \<br />    --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM --region ${DepRegion}</pre>记下 CodeCommit 存储库和 Amazon ECR 从前面的堆栈中创建的资源。在接下来的步骤中，设置管道的 `main` 分支需要用到这些参数。 | AWS DevOps | 
| 在工作负载帐户 CI/CD 中创建所需的资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | AWS DevOps | 
| 更新 S3 构件存储桶策略以允许工作负载账户访问。 | 要更新工具帐户中的 CloudFormation 堆栈先决条件，请使用以下命令为阶段和生产工作负载帐户添加所有必需的权限。（如果您不使用该 `QAAccount` 参数进行设置，请将其删除。）<pre>#InToolsAccount<br />aws cloudformation deploy \<br />    --template-file pre-requisites/pre-reqs.yaml \<br />    --stack-name prereqs \<br />    --parameter-overrides BucketStartName=${BucketStartName} \<br />    ApplicationName=${ApplicationName} ProdAccount=${ProdAccount} \<br />    StageAccount=${StageAccount} ToolsAccount=${ToolsAccount} \<br />    QAAccount=${QAAccount} PutPolicy=true \<br />    --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM --region ${DepRegion}</pre> | AWS DevOps | 

### 在工具账户中设置 Lambda 函数和 Service Catalog 资源
<a name="set-up-lam-function-and-sc-resources-in-tools-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 Service Catalog 产品组合和产品。 | 要设置 Service Catalog 产品组合和产品，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | AWS DevOps | 
| 设置 Lambda 函数。 | 此解决方案使用以下 Lambda 函数来管理修补程序工作流：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html)要使 Lambda 函数能够在通过关联 EventBridge 规则创建或删除`hotfix `分支时预置和终止 Service Catalog 产品，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | AWS DevOps | 

### 为主分支创建管道并在工作负载账户中部署应用程序
<a name="create-pipeline-for-main-branch-and-deploy-application-in-workload-accounts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 `main` 分支设置管道。 | 要为主分支设置管道，请在工具账户中运行以下命令。将 `MainProductId` 和 `MainProductArtifactId` 的参数替换为 `servicecatalogsetup` 堆栈输出中的值。<pre>#InToolsAccount<br />aws servicecatalog provision-product \<br />    --product-id <MainProductId> \<br />    --provisioning-artifact-id <MainProductArtifactId> \<br />    --provisioned-product-name "${ApplicationName}-main-pipeline" \<br />    --provisioning-parameters Key=CodeCommitRepoName,Value="${ApplicationName}-repository" Key=ECRRepository,Value="${ApplicationName}-app" \<br />    --region=${DepRegion}</pre> | AWS DevOps | 
| 使用 `main` 分支部署应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | AWS DevOps | 

### 为 hotfix-\$1 分支创建管道并部署此修补程序
<a name="create-the-pipeline-for-a-hotfix--branch-and-deploy-the-hotfix"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 `hotfix-*` 分支并提交更改。 | 要为 `hotfix-*` 分支创建管道并将修补程序部署到工作负载账户，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | AWS DevOps | 
| 删除 `hotfix-check1` 分支。 | 要删除之前创建的 `hotfix-check1` 分支，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | AWS DevOps | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理部署的资源。 | 要清理之前部署的先决条件，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html)<pre>##In Tools Account##<br />aws cloudformation delete-stack --stack-name servicecatalogsetup --region ${DepRegion}<br />aws cloudformation delete-stack --stack-name prlambdasetup --region ${DepRegion}<br />aws cloudformation delete-stack --stack-name prereqs --region ${DepRegion}</pre><pre>##In Workload Accounts##<br />aws cloudformation delete-stack --stack-name inframainstack --region ${DepRegion}</pre>有关更多信息，请参阅 Service Catalog 文档中的[删除预调配产品](https://docs.aws.amazon.com/servicecatalog/latest/userguide/enduser-delete.html)。 | AWS DevOps | 

## 问题排查
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 您提交到 CodeCommit 存储库的更改尚未部署。 | 检查 CodeBuild 日志，查看 Docker 构建操作中是否存在错误。有关详情，请参阅 [CodeBuild 文档](https://docs.aws.amazon.com/codebuild/latest/userguide/troubleshooting.html)。 | 
| 未预调配 Service Catalog 产品。 | 查看相关 CloudFormation 堆栈中是否存在失败的事件。有关详情，请参阅 [CloudFormation 文档](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html)。 | 

## 相关资源
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-resources"></a>
+ [基本 Git 命令](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-basic-git.html)
+ [配置 IAM 策略以限制向分支的推送和合并](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-conditional-branch.html#how-to-conditional-branch-create-policy)
+ [Connect 连接到 AWS CodeCommit 存储库](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)
+ [向用户授予访问权限](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/catalogs_portfolios_users.html)
+ [将 Docker 镜像推送到亚马逊 ECR 私有存储库](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)
+ [故障排查 AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/troubleshooting.html)
+ [什么是 AWS CodePipeline？](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)

## 附加信息
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions-additional"></a>

此模式专为具有 Gitflow 设置的环境而设计，该设置用于流程中的 CI/CD 开发工作流程。这些管道遵循以下部署周期：从开发开始，依次经过质量保证（QA）、预发布和生产环境。该 CI/CD 设置包括两个 git 分支，它们对环境进行了促销部署，如下所示：
+ `develop` 分支部署到开发环境。
+ `main` 分支部署到 QA、预发布和生产环境。

在这种设置中，在积极开发新功能的同时，要比通常的部署周期更快地应用修补程序或安全补丁是一项挑战。需要专用的流程来处理修补程序或安全请求，从而确保实时环境保持正常运行和安全。

但是，在下面的情况中，您可以使用其他可用选项，而无需专门的部署流程：
+ 该 CI/CD 流程配备了功能和测试等自动化 end-to-end测试，无需手动测试，并可防止部署到生产的延迟。但是，如果自动化测试没有很好地集成到 CI/CD 流程中，那么对开发人员来说，向生产环境推送一个小修复程序可能会变得复杂而繁琐。这是因为 QA 环境中可能有新功能等待批准和签署。修补程序或安全补丁无法以简单的方式同时投入到生产环境。
+ 开发团队不断将新功能部署到生产环境，从而将修补程序或安全补丁集成到每个新功能的计划部署中。换句话说，生产环境的下一次功能更新包括两个组件：增加新功能和包含修补程序或安全补丁。但是，如果部署周期不连续，则 QA 环境中可能已有多个新功能正在等待批准。管理不同的版本并确保重新应用正确的更改会变得复杂且容易出错。

**注意**  
如果您使用的是[版本 2](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipeline-types.html#:~:text=V2%20type%20pipelines%20have%20the%20same%20structure)，并在`hotfix`分支上设置了适当的触发器，则仍然需要一个专门的流程来处理计划外的请求。 AWS CodePipeline 在版本 2 中，您可以为推送或拉取请求设置触发器。执行将排队或立即执行，具体取决于管道的先前状态。但是，通过专用管道，修复程序会立即应用于生产环境，从而确保紧急问题毫不拖延地得到解决。

# 自动删除 AWS CloudFormation 堆栈和相关资源
<a name="automate-deletion-cloudformation-stacks-associated-resources"></a>

*SANDEEP SINGH 和 James Jacob，Amazon Web Services*

## Summary
<a name="automate-deletion-cloudformation-stacks-associated-resources-summary"></a>

[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 是一项广泛使用的服务，用于管理云基础设施即代码（IaC）。使用时 CloudFormation，您可以将相关资源作为一个称为*堆栈*的单元进行管理。您可通过创建、更新和删除堆栈来创建、更新和删除一组资源。

有时，您不再需要 CloudFormation 堆栈中的资源。根据资源及其配置，删除堆栈及其关联资源可能很复杂。在现实世界的生产系统中，由于相互冲突的条件或 CloudFormation 无法超越的限制，删除有时会失败或需要很长时间。可能需要仔细地计划和执行，以确保以高效、一致的方式正确删除所有资源。此模式描述了如何设置一个框架，以帮助您管理涉及以下复杂性的 CloudFormation 堆栈的删除：
+ **具有删除保护的资源** – 某些资源可能启用了删除保护。常见的示例是 [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 表和 [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)存储桶。删除保护可防止自动删除，例如通过删除 CloudFormation。如果要删除这些资源，则必须手动或以编程方式覆盖或暂时禁用删除保护。在继续操作之前，您应该仔细考虑删除这些资源的影响。
+ **具有保留策略的资源** — 某些资源，例如 AWS Key Management Service (AWS KMS) 密钥和 Amazon S3 存储桶，可能有保留策略，规定在请求删除后应保留多长时间。您应在清理策略中考虑这些政策，以始终符合组织策略和监管要求。
+ **延迟删除附加到 VPC 的 Lambda 函数** – 删除附加到虚拟私有云（VPC）的 [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 函数可能需要 5-40 分钟，具体取决于该流程中涉及的多个相互关联的依赖项。如果您在删除堆栈之前将函数从 VPC 分离，则可以将此延迟减少到 1 分钟以内。
+ **非直接创建的资源 CloudFormation** — 在某些应用程序设计中，资源可能由应用程序本身或通过 CloudFormation 堆栈置备的资源在原始堆栈之外创建。下面是两个示例：
  + CloudFormation 可能会预配置一个运行用户数据脚本的[亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) 实例。然后，此脚本可能会创建一个 [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 参数来存储与应用程序相关的数据。此参数不是通过管理的 CloudFormation。
  + CloudFormation 可能会配置一个 Lambda 函数，该函数会自动生成用于存储[ CloudWatch 日志的 Amazon 日志](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html)组。此日志组不是通过管理的 CloudFormation。

  尽管这些资源不是由直接管理的 CloudFormation，但在删除堆栈时通常需要清理它们。如果不加管理，它们可能变成孤立资源，导致不必要的资源消耗。

尽管这些护栏可能会增加复杂性，但它们是有意为之且至关重要的。 CloudFormation 在许多情况下，允许超越所有限制和不分青红皂白地删除资源可能会导致不利和不可预见的后果。但是，作为 DevOps 负责管理环境的云工程师，有时可能需要克服这些限制，尤其是在开发、测试或暂存环境中。

**目标业务成果**

通过实施此框架，您可以获得以下优势：
+ **成本管理** — 定期高效地清理临时环境，例如 end-to-end或用户验收测试环境，有助于防止资源的运行时间超过必要的时间。这可显著降低成本。
+ **安全** — 自动清理过时或未使用的资源可减少攻击面并有助于维护安全的 AWS 环境。
+ **运营效率** – 定期和自动清理可以带来以下运营优势：
  + 删除旧日志组或空 Amazon S3 存储桶的自动脚本可以通过保持环境整洁和可管理来提高运营效率。
  + 快速删除和重新创建堆栈支持设计和实现的快速迭代，由此实现更强大、更具弹性的架构。
  + 定期删除和重建环境可以帮助您识别和修复潜在的问题。这可以帮助您确保基础设施能够承受现实场景。

## 先决条件和限制
<a name="automate-deletion-cloudformation-stacks-associated-resources-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ Python 3.6 或更高版本，[已安装](https://www.python.org/downloads/)
+ 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)

**限制**
+ 命名约定用于标识应删除的资源。此模式中的示例代码使用资源名称的前缀，但您可以定义自己的命名约定。不使用此命名约定的资源将不会被识别或随后删除。

## 架构
<a name="automate-deletion-cloudformation-stacks-associated-resources-architecture"></a>

下图显示了此框架如何识别目标 CloudFormation 堆栈以及与之相关的额外资源。

![\[发现、处理和删除 CloudFormation 堆栈及其相关资源的阶段。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/ab7c3b56-3476-41a3-8ece-68915605a546/images/a7fceb1c-d624-47b3-957d-f910ef2f44d7.png)


下图显示了如下工作流：

1. **收集资源** — 自动化框架使用命名约定返回所有相关的 CloudFormation 堆栈、Amazon Elastic Container Registry (Amazon ECR) Registry 存储库、DynamoDB 表和 Amazon S3 存储桶。
**注意**  
此阶段的函数使用[分页工具](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html)，这是 Boto3 中的一项功能，它抽象了对截断的 API 结果集进行迭代的过程。这样可以确保所有资源都得到处理。要进一步优化性能，请考虑应用[服务器端](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results)筛选或考虑使用 JMESPath 来执行[客户端](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results-with-jmespath)筛选。

1. **预处理** — 自动化框架识别并解决了必须覆盖的服务限制， CloudFormation 才能允许删除资源。例如，它将 DynamoDB 表的 `DeletionProtectionEnabled` 设置更改为 `False`。在命令行界面中，对于每种资源，您都会收到一条提示，询问是否要覆盖该约束条件。

1. **删除堆栈**-自动化框架删除 CloudFormation 堆栈。在命令行界面中，您会收到一条提示，询问您是否要删除该堆栈。

1. **后处理** — 自动化框架会删除所有未 CloudFormation 作为堆栈一部分直接配置的相关资源。这些资源类型的示例包括 Systems Manager 参数和 CloudWatch 日志组。单独的函数收集这些资源，对其进行预处理，然后将其删除。在命令行界面中，对于每种资源，您都会收到一条提示，询问您是否要删除该资源。
**注意**  
此阶段的函数使用[分页工具](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html)，这是 Boto3 中的一项功能，它抽象了对截断的 API 结果集进行迭代的过程。这样可以确保所有资源都得到处理。要进一步优化性能，请考虑应用[服务器端](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results)筛选或考虑使用 JMESPath 来执行[客户端](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/paginators.html#filtering-results-with-jmespath)筛选。

**自动化和扩展**

如果您的 CloudFormation 堆栈包含示例代码中未包含的其他资源，或者堆栈存在此模式中未解决的约束条件，则可以根据自己的用例调整自动化框架。按照相同的方法收集资源、进行预处理、删除堆栈，然后进行后处理。

## 工具
<a name="automate-deletion-cloudformation-stacks-associated-resources-tools"></a>

**AWS 服务**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在和的整个 AWS 账户 生命周期中对其进行管理 AWS 区域。
+ [CloudFormation 命令行界面 (CFN-CLI)](https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/what-is-cloudformation-cli.html) 是一款开源工具，可帮助您开发 AWS 和测试第三方扩展，然后注册它们以在中使用。 CloudFormation
+ [适用于 Python (Boto3) 的 AWS SDK](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)是一个软件开发套件，可帮助您将 Python 应用程序、库或脚本与集成 AWS 服务。

**其他工具**
+ [Click](https://click.palletsprojects.com/en/stable/) 是一款 Python 工具，可帮助您创建命令行界面。
+ [Poetry](https://python-poetry.org/docs/) 是 Python 中用于管理和打包依赖项的工具。
+ [Pyenv](https://github.com/pyenv/pyenv) 是一款可以帮助您管理 Python 以及在其版本之间切换的工具。
+ [Python](https://www.python.org/) 是通用的计算机编程语言。

**代码存储库**

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

## 最佳实践
<a name="automate-deletion-cloudformation-stacks-associated-resources-best-practices"></a>
+ **标记资源以便于识别** – 实施[标记策略](https://aws.amazon.com/solutions/guidance/tagging-on-aws/)以识别针对不同环境和用途创建的资源。标签可以帮助您根据标签筛选资源，从而简化清理过程。
+ **设置资源生命周期** – 定义资源生命周期，以便在特定时间后自动删除资源。这种做法可帮助您确保临时环境不会成为永久性的成本负担。

## 操作说明
<a name="automate-deletion-cloudformation-stacks-associated-resources-epics"></a>

### 安装工具
<a name="install-tools"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps 工程师 | 
| 安装 Poetry。 | 按照[说明](https://python-poetry.org/docs/)（Poetry 文档）在目标虚拟环境中安装 Poetry。 | DevOps 工程师 | 
| 安装依赖项。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps 工程师 | 
| （可选）安装 Pyenv。 | 按照[说明](https://github.com/pyenv/pyenv#installation) (GitHub) 安装 Pyenv。 | DevOps 工程师 | 

### （可选）自定义框架
<a name="optional-customize-the-framework"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建用于收集、预处理和删除目标资源的函数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps 工程师，Python | 

### 创建示例资源
<a name="create-sample-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建堆 CloudFormation 栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | AWS DevOps | 
| 创建 Systems Manager 参数。 | 输入以下命令来创建未通过 CloudFormation配置的 Systems Manager 参数：<pre>aws ssm put-parameter \<br />  --name "/sampleforcleanup/database/password" \<br />  --value "your_db_password" \<br />  --type "SecureString" \<br />  --description "Database password for my app" \<br />  --tier "Standard" \<br />  --region "us-east-1"</pre> | AWS DevOps | 
| 创建 Amazon S3 存储桶。 | 输入以下命令以创建未通过 CloudFormation配置的 Amazon S3 存储桶：<pre>aws s3api create-bucket \<br />  --bucket samplesorcleanup-unmanagedbucket-<UniqueIdentifier> \<br />  --region us-east-1 \<br />  --create-bucket-configuration LocationConstraint=us-east-1</pre> | AWS DevOps | 

### 删除示例资源
<a name="delete-the-sample-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除 CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | AWS DevOps | 
| 验证资源删除。 | 在输出中，确认所有示例资源均已删除。有关示例查询，请参阅此模式的[其他资源](#automate-deletion-cloudformation-stacks-associated-resources-additional)部分。 | AWS DevOps | 

## 相关资源
<a name="automate-deletion-cloudformation-stacks-associated-resources-resources"></a>
+ [删除堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html)（CloudFormation 文档）
+ [故障排除 CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html)（CloudFormation 文档）
+ [授予 Lambda 函数访问 Amazon VPC 中资源的权限](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)（Lambda 文档）
+ [如何删除停留在 DELETE\$1FAILED 状态的 AWS CloudFormation 堆栈？](https://repost.aws/knowledge-center/cloudformation-stack-delete-failed) （AWS 知识中心）

## 附加信息
<a name="automate-deletion-cloudformation-stacks-associated-resources-additional"></a>

下面是 `cfncli` 命令的示例输出：

```
cfncli --region aus-east-1  dev cleanup-env --prefix-list sampleforcleanup                                                                                                                              
https://sts.us-east-1.amazonaws.com
Cleaning up: ['sampleforcleanup'] in xxxxxxxxxx:us-east-1
Do you want to proceed? [Y/n]: Y
No S3 buckets
No ECR repositories
No Lambda functions in VPC
The following DynamoDB tables will have their deletion protection removed:
sampleforcleanup-MyDynamoDBTable
Do you want to proceed with removing deletion protection from these tables? [Y/n]: Y
Deletion protection disabled for DynamoDB table 'sampleforcleanup-MyDynamoDBTable'.
The following CloudFormation stacks will be deleted:
sampleforcleanup-Stack
Do you want to proceed with deleting these CloudFormation stacks? [Y/n]: Y
Initiated deletion of CloudFormation stack: `sampleforcleanup-Stack`
Waiting for stack `sampleforcleanup-Stack` to be deleted...
CloudFormation stack `sampleforcleanup-Stack` deleted successfully.
The following ssm_params will be deleted:
/sampleforcleanup/database/password
Do you want to proceed with deleting these ssm_params? [Y/n]: Y
Deleted SSM Parameter: /sampleforcleanup/database/password
Cleaned up: ['sampleforcleanup']
```

# 使用 Terraform 在 Amazon Managed Grafana 上自动摄取和可视化 Amazon MWAA 自定义指标
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics"></a>

*Faisal Abdullah 和 Satya Vajrapu，Amazon Web Services*

## Summary
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-summary"></a>

此模式讨论如何使用 Amazon Managed Grafana 创建和监控 Amazon Managed Workflows for Apache Airflow（Amazon MWAA）摄取的自定义指标。Amazon MWAA 充当工作流程的协调器，它使用用 Python 编写脚本的有向无环图 (DAGs)。这种模式以监控自定义指标为中心，包括过去一小时内 DAGs 运行的总数、 DAGs 每小时通过和失败的计数以及这些进程的平均持续时间。此分析显示了 Amazon Managed Grafana 如何与 Amazon MWAA 集成，从而能够全面监控和洞察该环境中的工作流编排。

## 先决条件和限制
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-prereqs"></a>

**先决条件**
+  AWS 账户 具有创建和管理以下内容所需的用户权限的活跃用户 AWS 服务：
  + AWS Identity and Access Management (IAM) 角色和策略
  + AWS Lambda
  + Amazon Managed Grafana
  + Amazon Managed Workflows for Apache Airflow (Amazon MWAA)
  + Amazon Simple Storage Service（Amazon S3）
  + Amazon Timestream
+ 访问 Shell 环境，它可以是本地计算机上的终端，也可以是 [AWS CloudShell](https://docs.aws.amazon.com/cloudshell/latest/userguide/welcome.html)。
+ 安装了 Git 并安装和配置了最新版本的 AWS Command Line Interface (AWS CLI) 的 shell 环境。有关更多信息，请参阅 AWS CLI 文档 AWS CLI中的[安装或更新到最新版本](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)的。
+ 安装了以下 Terraform 版本：`required_version = ">= 1.6.1, < 2.0.0"`您可以使用 [tfswitch](https://tfswitch.warrensbox.com/) 在不同版本的 Terraform 之间切换。
+ 已在中 AWS IAM Identity Center 为您配置身份源 AWS 账户。有关更多信息，请参阅 IAM Identity Center 文档中的[在 IAM Identity Center 中确认身份源](https://docs.aws.amazon.com/singlesignon/latest/userguide/prereq-identity-sources.html)。您可以从默认 IAM Identity Center 目录的 Active Directory 或外部身份提供者 (IdP) 中进行选择，例如 Okta。有关更多信息，请参阅[相关资源](#automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-resources)。

**限制**
+ 有些 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)，然后选择相应服务的链接。

**产品版本**
+ Terraform `required_version = ">= 1.6.1, < 2.0.0"`
+ Amazon Managed Grafana 9.4 或更高版本。此模式已在版本 9.4 上进行了测试。

## 架构
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-architecture"></a>

以下架构图重点介绍了解决方案中 AWS 服务 使用的架构。

![\[自动摄取 Amazon MWAA 自定义指标的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/3458d0a9-aee1-428a-bf2f-c357bb531c64/images/b43ed8d2-94ac-4438-913b-81c7eba8f3e0.png)


上图中分步介绍了以下工作流：

1. Amazon MWAA 中的自定义指标源 DAGs 于在环境中执行的指标。指标以 CSV 文件格式上传到 Amazon S3 存储桶。以下内容 DAGs 使用 Amazon MWAA 的数据库查询功能：
   + `run-example-dag` – 此 DAG 包含定义一个或多个任务的示例 Python 代码。它每 7 分钟运行一次，并打印日期。打印日期后，DAG 会包含一项使执行的任务睡眠或暂停特定持续时间的任务。
   + `other-sample-dag` – 此 DAG 每 10 分钟运行一次，并打印日期。打印日期后，DAG 会包含一项使执行的任务睡眠或暂停特定持续时间的任务。
   + `data-extract` – 此 DAG 每小时运行一次，查询 Amazon MWAA 数据库并收集指标。收集完指标后，此 DAG 会将其写入到 Amazon S3 存储桶，以便进一步处理和分析。

1. 为了简化数据处理，Lambda 函数在被 Amazon S3 事件触发时运行，这样便于将指标加载到 Timestream 中。

1. Timestream 作为数据来源集成到 Amazon Managed Grafana 中，来自 Amazon MWAA 的所有自定义指标都存储在那里。

1. 用户可以查询数据并构造自定义控制面板，以可视化关键绩效指标，深入了解 Amazon MWAA 中的工作流编排。

## 工具
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-tools"></a>

**AWS 服务**
+ [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)帮助您集中管理对所有应用程序 AWS 账户 和云应用程序的单点登录 (SSO) 访问权限。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。在这种模式下， AWS Lambda 运行 Python 代码以响应 Amazon S3 事件并自动管理计算资源。
+ [Amazon Managed Grafana](https://docs.aws.amazon.com/grafana/latest/userguide/what-is-Amazon-Managed-Service-Grafana.html) 是一种完全托管式数据可视化服务，您可以使用该服务查询、关联和可视化您的指标、日志和跟踪，并发出提醒。此模式使用 Amazon Managed Grafana 创建用于指标可视化和提醒的控制面板。
+ [Amazon Managed Workflows for Apache Airflow（Amazon MWAA）](https://docs.aws.amazon.com/mwaa/latest/userguide/what-is-mwaa.html)是 Apache Airflow 的托管式编排服务，让您能够更轻松地在云中大规模设置和操作数据管道。[Apache Airflow](https://airflow.apache.org/) 是一种开源工具，用于以编程方式编写、调度和监视统称为工作流的各种流程和任务序列。在这种模式中，示例 DAGs 和指标提取器 DAG 部署在 Amazon MWAA 中。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。在这种模式中，Amazon S3 用于以 CSV 格式存储 DAGs、脚本和自定义指标。
+ [Amazon Timestream](https://docs.aws.amazon.com/timestream/latest/developerguide/what-is-timestream.html) for LiveAnalytics 是一个快速、可扩展、完全托管、专门构建的时间序列数据库，可轻松存储和分析每天数万亿个时间序列数据点。Timestream LiveAnalytics 还与用于数据收集、可视化和机器学习的常用服务集成。在此模式中，它用于摄取生成的 Amazon MWAA 自定义指标。

**其他工具**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款基础设施即代码（IaC）工具，可帮助您使用代码来预调配和管理云基础设施和资源。此模式使用 Terraform 模块在 AWS中自动预调配基础设施。

**代码存储库**

此模式的代码可在 [visualize-amazon-mwaa-custom-metrics-](https://github.com/aws-samples/visualize-amazon-mwaa-custom-metrics-grafana) grafana 存储库 GitHub 中找到。`stacks/Infra` 文件夹包含以下内容：
+ 所有资源的 Terraform 配置文件 AWS 
+ `grafana` 文件夹中的 Grafana 控制面板 .json 文件
+ 文件夹中的 Apache A DAGs irflow 的亚马逊托管工作流程 `mwaa/dags`
+ Lambda 代码，用于解析 .csv 文件并将指标存储在 Timestream 数据库的 `src` 文件夹中
+ `templates` 文件夹中的 IAM 策略 .json 文件

## 最佳实践
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-best-practices"></a>

Terraform 必须存储有关您的托管基础设施和配置的状态，这样它才能将现实世界的资源映射到您的配置。默认情况下，Terraform 将状态存储在本地名为 `terraform.tfstate` 的文件中。确保 Terraform 状态文件的安全性和完整性至关重要，因为它可以保持基础设施的当前状态。有关更多信息，请参阅 Terraform 文档中的[远程状态](https://developer.hashicorp.com/terraform/language/state/remote)。

## 操作说明
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-epics"></a>

### 使用 Terraform 部署基础设施
<a name="deploy-the-infrastructure-using-terraform"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署基础设施。 | 要部署该解决方案基础设施，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | AWS DevOps | 

### 验证已部署的基础设施资源
<a name="validate-the-deployed-infrastructure-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证 Amazon MWAA 环境。 | 要验证 Amazon MWAA 环境，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | AWS DevOps，数据工程师 | 
| 验证 DAG 计划。 | 要查看每个 DAG 时间表，请转到 **Airflow UI** 中的**时间表**选项卡。以下 DAGs 每项都有预先配置的计划，该计划在 Amazon MWAA 环境中运行并生成自定义指标：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html)您还可以在**运行**列下查看每个 DAG 是否成功运行。 | AWS 数据工程师 DevOps | 

### 配置 Amazon Managed Grafana 环境
<a name="configure-the-gra-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置对 Amazon Managed Grafana 工作区的访问权限。 | Terraform 脚本创建了所需的 Amazon Managed Grafana 工作区、控制面板和指标页面。要配置访问权限以便于您查看它们，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | AWS DevOps | 
| 安装 Amazon Timestream 插件。 | Amazon MWAA 自定义指标已加载到 Timestream 数据库中。您可以使用 Timestream 插件通过 Amazon Managed Grafana 控制面板对指标进行可视化。要安装 Timestream 插件，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html)有关更多信息，请参阅 Amazon Managed Grafana 文档中的[使用插件扩展您的工作区](https://docs.aws.amazon.com/grafana/latest/userguide/grafana-plugins.html#manage-plugins)。 | AWS DevOps， DevOps 工程师 | 

### 在 Amazon Managed Grafana 控制面板中可视化自定义指标
<a name="visualize-the-custom-metrics-in-the-gra-dashboard"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看 Amazon Managed Grafana 控制面板。 | 要查看摄取到 Amazon Managed Grafana 工作区的指标，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html)该控制面板指标页面显示以下信息：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | AWS DevOps | 
| 自定义 Amazon Managed Grafana 控制面板。 | 要自定义控制面板以便将来进一步增强，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html)或者，此仪表板的源代码可在[GitHub 存储库`stacks/infra/grafana`](https://github.com/aws-samples/visualize-amazon-mwaa-custom-metrics-grafana/blob/main/stacks/infra/grafana/dashboard.json)文件夹中的`dashboard.json`文件中找到。 | AWS DevOps | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 暂停 Amazon MWAA DAG 运行。 | 要暂停 DAG 运行，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | AWS DevOps，数据工程师 | 
| 从 Amazon S3 存储桶中删除对象。 | 要删除 Amazon S3 存储桶 **mwaa-events-bucket-\$1 和 **mwaa-metrics-bucket-\$1****，请按照 Amazon S3 文档中[删除存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/delete-bucket.html)中有关使用 Amazon S3 控制台的说明进行操作。 | AWS DevOps | 
| 销毁由 Terraform 创建的资源。 | 要销毁由 Terraform 创建的资源以及关联的本地 Terraform 状态文件，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | AWS DevOps | 

## 问题排查
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| `null_resource.plugin_mgmt (local-exec): aws: error: argument operation: Invalid choice, valid choices are:` |  AWS CLI 将您的版本升级到[最新版本](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。 | 
| 加载数据来源错误 - `Fetch error: 404 Not Found Instantiating…` | 这是间歇性错误。等待几分钟，然后刷新您的数据来源以查看列出的 Timestream 数据来源。 | 

## 相关资源
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-resources"></a>

**AWS 文档**
+ [用于生成控制面板和可视化的 Amazon Managed Grafana](https://docs.aws.amazon.com/prescriptive-guidance/latest/implementing-logging-monitoring-cloudwatch/amg-dashboarding-visualization.html)
+ [将亚马逊托管 Grafana 配置为使用 Okta](https://docs.aws.amazon.com/grafana/latest/userguide/AMG-SAML-providers-okta.html)
+ [AWS IAM Identity Center 与您的亚马逊托管 Grafana 工作区配合使用](https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG-SSO.html)
+ [ DAGs 在 Amazon 上使用 MWAA](https://docs.aws.amazon.com/mwaa/latest/userguide/working-dags.html)

**AWS 视频**
+ 使用 Amazon Managed Grafana 配置 IAM Identity Center 进行身份验证，如下面的[视频](https://www.youtube.com/watch?v=XX2Xcz-Ps9U)所示。




[https://www.youtube-nocookie.com/embed/XX2Xcz-Ps9U？ 控件=0](https://www.youtube-nocookie.com/embed/XX2Xcz-Ps9U?controls=0)
+ 如果 IAM Identity Center 不可用，您还可以使用 Okta 之类的外部身份提供者（IdP）来集成 Amazon Managed Grafana 身份验证，如下面的[视频](https://www.youtube.com/watch?v=Z4JHxl2xpOg)所示。




[https://www.youtube-nocookie.com/embed/Z4 JHxl2xp Og？ 控件=0](https://www.youtube-nocookie.com/embed/Z4JHxl2xpOg?controls=0)

## 附加信息
<a name="automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics-additional"></a>

您可以为您的 Amazon MWAA 环境创建全面的监控和提醒解决方案，从而实现主动管理并对潜在问题或异常情况做出快速响应。Amazon Managed Grafana 包括以下功能：

**提醒** – 您可以根据预定义的阈值或条件在 Amazon Managed Grafana 中配置提醒。设置电子邮件通知，以便在某些指标超过或低于指定阈值时提醒相关的利益相关者。有关更多信息，请参阅 Amazon Managed Grafana 文档中的 [Grafana 提醒](https://docs.aws.amazon.com/grafana/latest/userguide/alerts-overview.html)。

**集成** — 您可以将 Amazon Managed Grafana 与各种第三方工具（ OpsGenie例如 PagerDuty、或 Slack）集成，以增强通知功能。例如，您可以设置 webhook 或与集成， APIs 以便根据在 Amazon Managed Grafana 中生成的警报在这些平台上触发事件和通知。此外，此模式还提供了用于创建 AWS 资源的[GitHub 存储库](https://github.com/aws-samples/visualize-amazon-mwaa-custom-metrics-grafana)。您可以进一步将此代码与您的基础设施部署工作流集成。

# 使用 AWS CodePipeline 和 AWS 自动部署堆栈集 CodeBuild
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild"></a>

*Thiyagarajan Mani、Mihir Borkar 和 Raghu Gowda，Amazon Web Services*

## Summary
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-summary"></a>

在持续集成和持续交付（满足此要求的CI/CD) processes, you might want to deploy applications automatically into all your existing AWS accounts and into new accounts that you add to your organization in AWS Organizations. When you architect a CI/CD解决方案）中，AWS 的[委托堆栈集管理员](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-delegated-admin.html)功能 CloudFormation 非常有用，因为它通过限制对管理账户的访问来实现一层安全保护。但是，AWS CodePipeline 使用服务托管权限模型将应用程序部署到多个账户和区域。您必须使用 AWS Organizations 管理账户使用堆栈集进行部署，因为 AWS CodePipeline 不支持委托堆栈集管理员功能。

此模式介绍了如何解决此限制。该模式使用 AWS CodeBuild 和自定义脚本通过 AWS 自动部署堆栈集 CodePipeline。它可自动执行以下应用程序部署活动：
+ 将应用程序作为堆栈集部署到现有组织单位中 (OUs)
+ 将应用程序的部署扩展到其他 OUs 区域和区域 
+ 从所有或特定区域 OUs 或区域中移除已部署的应用程序

## 先决条件和限制
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-prereqs"></a>

**先决条件**

在按照此模式中的步骤操作之前：
+ 在 AWS Organizations 管理账户创建组织。有关说明，请参阅 [AWS Organizations 文档](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_create.html)。
+ 在 AWS Organizations 之间启用可信访问权限并 CloudFormation 使用服务托管权限。有关说明，请参阅 CloudFormation 文档中的[通过 AWS Organizations 启用可信访问](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-enable-trusted-access.html)。

**限制**

此模式提供的代码具有以下限制： 
+ 您只能为一个应用程序部署单个 CloudFormation 模板；目前不支持多个模板部署。
+ 定制当前实施需要 DevOps 专业知识。
+ 此模式不使用 AWS Key Management System (AWS KMS) 密钥。但是，您可以通过重新配置此模式中包含的 CloudFormation 模板来启用此功能。

## 架构
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-architecture"></a>

![\[CI/CD 管道自动化架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a5c47de7-9039-415d-a9e5-9de0d4c3a260/images/2dbca422-7f32-4f9c-a4aa-1f95b484b772.png)


此 CI/CD 部署管道架构可处理以下内容：
+ 通过将堆栈集部署责任委托给作为应用程序部署堆栈集管理员的专用 CI/CD 账户，限制对管理账户的直接访问。
+ 每当在 OU 下创建并映射新账户时，使用服务管理的权限模型自动部署应用程序。
+ 确保环境级别所有账户的应用程序版本一致性。
+ 在存储库和管道级别使用多个审核阶段，为已部署的应用程序提供额外的安全和治理层。
+ 克服了当前的限制， CodePipeline 即在中使用自定义的部署脚本 CodeBuild 来自动部署或移除堆栈集和堆栈实例。有关自定义脚本实现的 API 调用的流量控制和层次结构的说明，请参阅[其他信息](#automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-additional)部分。
+ 为开发、测试和生产环境创建单独的堆栈集。此外，您还可以创建在每个阶段将多个 OUs 和区域组合在一起的堆栈集。例如，您可以在开发部署阶段将沙盒 OUs和开发结合起来。
+ 支持将应用程序部署到账户子集或列表中或从中排除 OUs。

**自动化和扩展**

您可以使用此模式提供的代码为您的应用程序创建 AWS CodeCommit 存储库和代码管道。然后，您可以将它们作为堆栈集部署至 OU 级别的多个账户中。该代码还自动执行组件，例如用于通知审批者的 Amazon Simple Notiﬁcation Service (Amazon SNS) 主题、所需 AWS Identity and Access Management (IAM) 角色以及要在管理账户中应用的服务控制策略（SCP）。

## 工具
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-tools"></a>

**AWS 服务**
+ [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 CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html) 可自动部署到亚马逊弹性计算云 (Amazon EC2) 或本地实例、AWS Lambda 函数或亚马逊弹性容器服务 (Amazon ECS) 服务。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可帮助您快速建模和配置软件发布的不同阶段，并自动执行持续发布软件变更所需的步骤。
+ [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html) 是一项账户管理服务，使您可将多个 AWS 账户整合到您所创建的组织中并进行集中管理。
+ [Amazon Simple Notiﬁcation Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可帮助您协调和管理发布者与客户端（包括 Web 服务器和电子邮件地址）之间的消息交换。

**代码存储库**

此模式的代码可在 GitHub [automated-code-pipeline-stackset-](https://github.com/aws-samples/automated-code-pipeline-stackset-deployment) deployment 存储库中找到。有关文件夹结构和其他详细信息，请参见存储库的[自述文件](https://github.com/aws-samples/automated-code-pipeline-stackset-deployment/blob/main/README.md)。

## 最佳实践
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-best-practices"></a>

在 OU 级别部署应用程序时，此模式限制对管理账户的直接访问。向管道和存储库流程添加多个审批阶段有助于为使用此方法部署的应用程序和组件提供额外的安全性和治理。

## 操作说明
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-epics"></a>

### 在 AWS Organizations 中配置账户
<a name="configure-accounts-in-aws-organizations"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启用管理账户中的所有功能。 | 按照 [AWS Organizations 文档](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html)中的说明为您的组织启用管理账户中的所有功能。 | AWS 管理员、平台管理员 | 
| 创建一个 CI/CD 账户。 | 在 AWS Organizations 中，在您的组织中创建一个专用 CI/CD 账户，然后分配一个团队来拥有和控制该账户的访问权限。 | AWS 管理员 | 
| 添加委托管理员。 | 在管理账户中，将您在上一步中创建的 CI/CD 账户注册为委派堆栈集管理员。有关说明，请参阅 A [WS CloudFormation 文档](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-delegated-admin.html)。 | AWS 管理员、平台管理员 | 

### 创建应用程序存储库和 CI/CD 管道
<a name="create-an-application-repository-and-ci-cd-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆代码存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | AWS DevOps | 
| 创建 SNS 主题。 | 您可以使用 GitHub 存储库中提供的`sns-template.yaml`模板来创建 SNS 主题和配置批准请求的订阅。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | AWS DevOps | 
| 为 CI/CD 组件创建 IAM 角色。 | 您可以使用 GitHub 存储库中提供的`cicd-role-template.yaml`模板来创建 CI/CD 组件所需的 IAM 角色和策略。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | AWS DevOps | 
| 为您的应用程序创建 CodeCommit 存储库和代码管道。 | 您可以使用 GitHub 存储库中提供的`cicd-pipeline-template.yaml`模板为应用程序创建 CodeCommit 存储库和代码管道。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | AWS DevOps | 

### 部署堆栈集
<a name="deploy-a-stack-set"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆应用程序存储库。 | 您之前使用的 CI/CD 管道模板会创建示例应用程序存储库和代码管道。若要克隆并验证存储库，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | 应用程序开发人员、数据工程师 | 
| 添加应用程序构件。 | 使用 CloudFormation 模板更新应用程序存储库。此解决方案仅支持部署单个 CloudFormation 模板。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | 应用程序开发人员、数据工程师 | 
| 更新部署配置文件。 | 更新 `deployment_config.json` 文件：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html)此模式通过将环境名称添加到您在部署配置文件中提供的堆栈集名称来为每个环境创建单独的堆栈集。 | 应用程序开发人员、数据工程师 | 
| 提交更改和部署堆栈集。 | 提交您在应用程序模板中指定的更改，并将堆栈集逐步合并并部署到多个环境中：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild.html) | 应用程序开发人员、数据工程师 | 

## 问题排查
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 部署失败，以下情况除外：*将模板参数文件的名称更改为-parameter-.json，不允许使用默认名称 <application name><evn>* |  CloudFormation 模板参数文件必须遵循指定的命名约定。更新参数文件名并重试。 | 
| 部署失败，以下情况除外：*将 CloudFormation 模板名称更改为.yml，不允许使用默认 template.yml 或 template.yaml* <application name> |  CloudFormation 模板名称必须遵循指定的命名约定。更新文件名和重试。 | 
| 部署失败，以下情况除外：*找不到适用于 \$1环境名称\$1 环境的有效 CloudFormation 模板及其参数文件* | 检查 CloudFormation 模板的文件命名约定及其指定环境的参数文件。 | 
| 部署失败，以下情况除外：*部署配置文件中提供的部署操作无效。有效的选项是部署和删除。* | 您在部署配置文件中为 `deployment_action` 参数指定了无效值。该参数有两个有效值：`deploy` 和 `delete`。`deploy` 用于创建和更新堆栈集及其关联堆栈实例。`delete` 仅当您想要移除整个堆栈集和关联堆栈实例时使用。 | 

## 相关资源
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-resources"></a>
+ GitHub [automated-code-pipeline-stackset-部署存储库](https://github.com/aws-samples/automated-code-pipeline-stackset-deployment)
+ [启用企业中的所有功能](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_org_support-all-features.html)（AWS Organizations 文档）
+ [注册委托管理员](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-delegated-admin.html)（AWS CloudFormation 文档）
+ [服务托管堆栈集的账户级别目标](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/account-level-targets.html)（AWS CloudFormation 文档）

## 附加信息
<a name="automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-additional"></a>

**流程图**

以下流程图介绍了自定义脚本实现的 API 调用的流程控制和层次结构，以自动化堆栈集部署。

![\[Python脚本实现的流程控制和 API 调用\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a5c47de7-9039-415d-a9e5-9de0d4c3a260/images/1898883a-62b7-40c2-8f08-9f2a9dda8404.png)


** 部署配置文件示例**

**创建新堆栈集**

以下部署配置文件创建了一个新的堆栈集，该堆栈集`sample-stack-set`在三个 AWS 区域`us-east-1`中名为 OUs。

```
{
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

**将现有堆栈集部署至其他 OU**

如果您部署了上一个示例中所示的配置，并且想要将堆栈集部署到开发环境 `dev-org-unit-2` 中名为的其他 OU，则部署配置文件可能如下所示。

```
{
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1", "dev-org-unit-2"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

**将现有堆栈集部署至其他 AWS 区域**

如果您部署了上一个示例中所示的配置，并且想要将堆栈集部署到开发环境中的其他 AWS 区域 (`us-east-2`) OUs （`dev-org-unit-1`和`dev-org-unit-2`），则部署配置文件可能如下所示。

**注意**  
 CloudFormation 模板中的资源必须有效且特定于区域。

```
{
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1", "dev-org-unit-2"], 
                                        "regions": ["us-east-1", "us-east-2"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

**从 OU 或 AWS 区域移除堆栈实例**

假设已经部署了上一个示例中显示的部署配置。以下配置文件将堆栈实例从 OU `dev-org-unit-2` 的两个区域中移除。

```
{
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1"],
                                        "regions": ["us-east-1", "us-east-2"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"],
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"],
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

以下配置文件将两者的堆栈实例从开发环境 OUs 中的 AWS 区域`us-east-1`中删除。   

```
{
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1", "dev-org-unit-2"], 
                                        "regions": ["us-east-2"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

**删除整个堆栈集**

以下部署配置文件将删除整个堆栈集及其所有关联的堆栈实例。

```
{
     "deployment_action": "delete",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1", "dev-org-unit-2"], 
                                        "regions": ["us-east-2"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

****将账户排除在部署之外**

 以下部署配置文件将作为 OU `dev-org-unit-1` 一部分的账户 `111122223333` 排除在部署之外。

```
 {
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": ["111122223333"],
                                        "filter_type": "DIFFERENCE"
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

**将应用程序部署至 OU 中的一部分账户**

以下部署配置文件仅将应用程序部署到 OU `dev-org-unit-1` 中的三个账户（`111122223333`、`444455556666`、和 `777788889999`）。

```
 {
     "deployment_action": "deploy",
     "stack_set_name": "sample-stack-set",
     "stack_set_desciption": "this is a sample stack set",
    "deployment_targets": {
                            "dev": {
                                        "org_units": ["dev-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": ["111122223333", "444455556666", "777788889999"],
                                        "filter_type": "INTERSECTION"
                                    },
                            "test": {
                                        "org_units": ["test-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    },                            
                            "prod": {
                                        "org_units": ["prod-org-unit-1"], 
                                        "regions": ["us-east-1"],
                                        "filter_accounts": [],
                                        "filter_type": ""
                                    }                            
                          },
     "cft_capabilities": ["CAPABILITY_IAM", "CAPABILITY_NAMED_IAM"],
     "auto_deployement": "True",
     "retain_stacks_on_account_removal": "True",
     "region_deployment_concurrency": "PARALLEL"
 }
```

# 使用云托管人和 AWS CDK 将适用于 Systems Manager 的 AWS 托管策略自动附加到 EC2 实例配置文件
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk"></a>

*Ali Asfour 和 Aaron Lennon，Amazon Web Services*

## Summary
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-summary"></a>

您可以将亚马逊弹性计算云 (Amazon EC2) 实例与 AWS Systems Manager 集成，以自动执行操作任务并提供更多的可见性和控制力。要与 Systems Manager 集成， EC2 实例必须安装一个 [AWS Systems Manager 代理 (SSM 代理)](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html)，并在其实例配置文件上附加一个 A `AmazonSSMManagedInstanceCore` WS 身份和访问管理 (IAM) 策略。 

但是，如果您想确保所有 EC2 实例配置文件都附加了`AmazonSSMManagedInstanceCore`策略，则在更新没有 EC2 实例配置文件的新实例或 EC2 具有实例配置文件但没有`AmazonSSMManagedInstanceCore`策略的实例时可能会遇到困难。在多个 Amazon Web Services（AWS）账户和 AWS 区域 中添加此策略也可能很困难。

这种模式通过在 AWS 账户中部署三项[云托管人](https://cloudcustodian.io/)策略来帮助解决这些困难：
+ 第一个 Cloud Custodian 策略会检查是否有实例配置文件但没有该`AmazonSSMManagedInstanceCore`策略的现有 EC2 实例。然后附上 `AmazonSSMManagedInstanceCore` 策略。 
+ 第二个 Cloud Custodian 策略会检查没有 EC2 实例配置文件的现有实例，并添加附加了该`AmazonSSMManagedInstanceCore`策略的默认实例配置文件。
+ 第三项云托管人策略在您的账户中创建 [AWS Lambda](https://cloudcustodian.io/docs/aws/lambda.html) 函数，以监控实例和实例配置 EC2 文件的创建。这样可以确保在创建 EC2 实例时自动附加`AmazonSSMManagedInstanceCore`策略。

这种模式使用 [AWS DevOps](https://aws.amazon.com/devops/) 工具将云托管人策略持续大规模部署到多账户环境，无需配置单独的计算环境。 

## 先决条件和限制
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-prereqs"></a>

**先决条件**
+ 两个或以上活跃 AWS 账户。一个账户是*安全账户*，其他账户是*成员账户*。
+ 在安全账户中预调配 AWS 资源的权限。此模式使用[管理员权限](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html)，但您应根据贵组织的要求和策略授予权限。
+ 能够从安全账户向成员账户分派 IAM 角色并创建所需 IAM 角色。有关更多信息，请参阅 IAM 文档中的[使用 IAM 角色跨 AWS 账户委派访问权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html)。
+ 
**重要**  
已安装和配置 AWS 命令行界面（AWS CLI）。出于测试目的，您可以使用 `aws configure` 命令或设置环境变量来配置 AWS CLI。：不建议在生产环境中这样做，我们建议仅向该账户授予访问的最低权限。有关更多信息，请参阅 IAM 文档中的[授予最低权限许可](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)。
+ 将 `devops-cdk-cloudcustodian.zip` 文件（附件）下载到本地计算机中。
+ 熟悉 Python。
+ 已安装并配置所需工具（Node.js、AWS Cloud Development Kit（AWS CDK）和 Git）。您可以使用 `install-prerequisites.sh` 文件中的 `devops-cdk-cloudcustodian.zip` 文件来****安装这些工具。****确保以根权限运行此文件。 

**限制**
+ 尽管这种模式可以在生产环境中使用，但请确保所有 IAM 角色和策略都符合贵组织的要求和政策。 

**软件包版本**
+ 云托管人版本 0.9 或更高版本
+ TypeScript 版本 3.9.7 或更高版本
+ Node.js 版本 14.15.4 或更高版本
+ `npm` 版本 7.6.1 或更高版本
+ AWS CDK 版本 1.96.0 或更高版本

## 架构
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-architecture"></a>

![\[AWS CodePipeline workflow with CodeCommit, CodeBuild, and deployment to member accounts.\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/169a7bde-789e-4ebd-b4ca-80eb28ac9927/images/8ec0b6b4-d4b0-42e5-833d-24d1e6098fd9.png)


 

下图显示了如下工作流：

1. 云托管人策略被推送到安全账户中的 AWS CodeCommit 存储库。Amazon E CloudWatch vents 规则会自动启动 AWS CodePipeline 管道。

1. 该管道从中 CodeCommit 获取最新代码，并将其发送到 AWS 处理的持续集成和持续交付 (CI/CD) 管道的持续集成部分。 CodeBuild

1. CodeBuild 执行完整的 DevSecOps 操作，包括对 Cloud Custodian 策略进行策略语法验证，并在`--dryrun`模式下运行这些策略以检查识别了哪些资源。

1. 如果没有错误，则下一个任务会提醒管理员查看更改并批准向成员账户部署。

**技术堆栈**
+ AWS CDK
+ CodeBuild
+ CodeCommit
+ CodePipeline
+ IAM
+ Cloud Custodian 

**自动化和扩缩**

除了使用 CodePipeline AWS 堆栈部署 AWS 资源外，AWS CDK pipelines 模块还提供了一个 CI/CD 管道 CodeBuild，该管道用于协调源代码的构建和测试。 CloudFormation 您可以对贵组织中的所有成员账户和区域使用此模式。您还可以扩展 `Roles creation` 堆栈以在成员账户中部署其他 IAM 角色。 

## 工具
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-tools"></a>
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一个软件开发框架，用于在代码中定义云基础设施并通过 AWS CloudFormation 进行配置。
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它使您能够使用命令行 Shell 中的命令与 Amazon Web Services 交互。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管的云端构建服务。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) 是一项版本控制服务，您可以使用它来私下存储和管理资产。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 是一项持续交付服务，您可以使用它对发布软件所需的步骤进行建模、可视化和自动化。
+ [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 是一项 Web 服务，可帮助您安全地控制对 AWS 资源的访问。
+ [云托管人](https://cloudcustodian.io/)是一种工具，可将大多数组织用于管理其公共云账户的数十种工具和脚本统一到一个开源工具中。
+ [Node.js](https://nodejs.org/en/) 是一个基于谷歌浏览器 V8 JavaScript 引擎构建的 JavaScript 运行时。

**代码**

有关此模式中使用的模块、账户函数、文件和部署命令的详细列表，请参阅 `devops-cdk-cloudcustodian.zip` 文件（附件）中的 `README` 文件。

## 操作说明
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-epics"></a>

### 使用 AWS CDK 设置管线
<a name="set-up-the-pipeline-with-aws-cdk"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 CodeCommit 存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.html)有关这方面的更多信息，请参阅 AWS CodeCommit 文档中的[创建 CodeCommit 存储库](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html)。 | 开发者版 | 
| 安装所需工具。 | 使用该 `install-prerequisites.sh` 文件在 Amazon Linux 上安装所有必需的工具。这不包括 AWS CLI，因为它是预安装的。有关这方面的更多信息，请参阅 AWS CDK 文档中的 [AWS CDK 入门](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html#getting_started_prerequisites)的[先决条件](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)部分。 | 开发者版 | 
| 安装所需 AWS CDK 软件包。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.html)以下软件包是 AWS CDK 的必需并且包含在 `requirements.txt` 文件中：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.html) | 开发者版 | 

### 配置环境
<a name="configure-your-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新所需变量。 | 打开 CodeCommit 存储库根文件夹中的`vars.py`文件并更新以下变量：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.html) | 开发者版 | 
| 使用成员账户信息更新 account.yml 文件。 | 要对多个账户运行 [c7n-org Cloud Custodian](https://cloudcustodian.io/docs/tools/c7n-org.html) 工具，必须将 `accounts.yml` 配置文件放在存储库的根目录中。以下是适用于 AWS 的一个示例云托管人配置文件：<pre>accounts:<br />- account_id: '123123123123'<br />  name: account-1<br />  regions:<br />  - us-east-1<br />  - us-west-2<br />  role: arn:aws:iam::123123123123:role/CloudCustodian<br />  vars:<br />    charge_code: xyz<br />  tags:<br />  - type:prod<br />  - division:some division<br />  - partition:us<br />  - scope:pci</pre> | 开发者版 | 

### 引导 AWS 账户
<a name="bootstrap-the-aws-accounts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 引导安全账户。 | 运行以下命令，使用 `cloudcustodian_stack` 应用程序引导 `deploy_account`：<pre>cdk bootstrap -a 'python3 <br />cloudcustodian/cloudcustodian_stack.py</pre> | 开发者版 | 
| 选项 1 – 自动引导成员账户。 | 如果在 `vars.py` 文件中将 `cdk_bootstrap_member_accounts` 变量设置为 `True`，则管线会自动引导 `member_accounts` 变量中指定的账户。如果需要，您可以使用可从安全账户分派且具有引导 AWS CDK 所需权限的 IAM 角色更新 `*cdk_bootstrap_role*`。管线会自动引导添加到 `member_accounts ` 变量中的新账户，以便可以部署所需角色。 | 开发者版 | 
| 选项 2 – 手动引导成员账户。 | 尽管我们不建议使用这种方法，但您可以将 `cdk_bootstrap_member_accounts` 的值设置为 `False`，然后通过运行以下命令手动执行此步骤：<pre>$ cdk bootstrap -a 'python3 cloudcustodian/member_account_roles_stack.py' \<br /><br />--trust {security_account_id} \<br /><br />--context assume-role-credentials:writeIamRoleName={role_name} \<br /><br />--context assume-role-credentials:readIamRoleName={role_name} \<br /><br />--mode=ForWriting \<br /><br />--context bootstrap=true \<br /><br />--cloudformation-execution-policies arn:aws:iam::aws:policy/AdministratorAccess</pre>请务必使用可从安全账户分派且具有引导 AWS CDK 所需权限的 IAM 角色的名称更新 `{security_account_id}` 和 `{role_name}` 值。您也可以使用其他方法来引导成员账户，例如，使用 AWS CloudFormation。有关更多信息，请参阅 AWS CDK 文档中的[引导](https://docs.aws.amazon.com/cdk/latest/guide/bootstrapping.html)。 | 开发者版 | 

### 部署 AWS CDK 堆栈
<a name="deploy-the-aws-cdk-stacks"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在成员账户中创建 IAM 角色。 | 运行以下命令以部署 `member_account_roles_stack` 堆栈并在成员账户中创建 IAM 角色：<pre>cdk deploy --all -a 'python3 cloudcustodian/member_account_roles_stack.py' --require-approval never</pre> | 开发者版 | 
| 部署云托管人管线堆栈。 | 运行以下命令以创建部署到安全账户的云托管人 `cloudcustodian_stack.py` 管线：<pre>cdk deploy -a 'python3 cloudcustodian/cloudcustodian_stack.py'</pre> | 开发者版 | 

## 相关资源
<a name="automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk-resources"></a>
+ [AWS CDK 入门](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)

## 附件
<a name="attachments-169a7bde-789e-4ebd-b4ca-80eb28ac9927"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/169a7bde-789e-4ebd-b4ca-80eb28ac9927/attachments/attachment.zip)

# 使用 AWS CDK 自动为微服务构建 CI/CD 管道和 Amazon ECS 集群
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk"></a>

*Varsha Raju，Amazon Web Services*

## Summary
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-summary"></a>

此模式描述了如何自动创建持续集成和持续交付（CI/CD) pipelines and underlying infrastructure for building and deploying microservices on Amazon Elastic Container Service (Amazon ECS). You can use this approach if you want to set up proof-of-concept CI/CD pipelines to show your organization the benefits of CI/CD, microservices, and DevOps. You can also use this approach to create initial CI/CD管道），然后您可以根据组织的要求对其进行自定义或更改。 

此示例方法构建了生产环境和非生产环境，每个环境都有一个虚拟私有云（VPC）和一个 Amazon ECS 集群（配置为在两个可用区中运行）。这些环境由您的所有微服务共享，然后您可以为每个微服务创建一个 CI/CD 管道。这些 CI/CD 管道从 AWS 的源存储库提取更改 CodeCommit，自动生成更改，然后将其部署到您的生产和非生产环境中。当管道成功完成其所有阶段后，您可以使用 URLs 在生产和非生产环境中访问该微服务。

## 先决条件和限制
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-prereqs"></a>

**先决条件**
+ 一个活跃的 Amazon Web Services（AWS）账户。
+ 包含 `starter-code.zip` 文件（附件）的现有 Amazon Simple Storage Service (Amazon S3) 存储桶。
+ AWS Cloud Development Kit (AWS CDK)，已在您的账户中安装并配置。有关这方面的更多信息，请参阅 AWS CDK 文档中的 [AWS CDK 入门](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)。
+ Python 3 和 `pip`，已安装并配置。有关这方面的更多信息，请参阅 [Python 文档](https://www.python.org/)。
+ 熟悉 AWS CDK、AWS、AWS、AW CodePipeline S CodeBuild、 CodeCommit亚马逊弹性容器注册表 (Amazon ECR) Container Registry、Amazon ECS 和 AWS Fargate。
+ 熟悉 Docker。
+ 对 CI/CD 和的理解 DevOps。

**限制**
+ 适用一般的 AWS 账户限制。有关这方面的更多信息，请参阅 AWS 一般参考文档中的 [AWS 服务限额](https://docs.aws.amazon.com/general/latest/gr/aws_service_limits.html)。

**产品版本**
+ 使用 Node.js 版本 16.13.0 和 AWS CDK 版本 1.132.0 测试此代码。

## 架构
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-architecture"></a>

![\[AWS 云 architecture diagram showing CI/CD pipeline and deployment to production and non-production VPCs.\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/05ac2cad-408e-433f-8150-0a2b71f63cfd/images/6fa3dbef-88de-4b3f-ae41-dfa90256a058.png)


下图显示了如下工作流：

1. 应用程序开发人员将代码提交到 CodeCommit 存储库。

1. 管道已启动。

1. CodeBuild 构建 Docker 镜像并将其推送到亚马逊 ECR 存储库

1. CodePipeline 将新映像部署到非生产 Amazon ECS 集群中的现有 Fargate 服务。

1. Amazon ECS 将映像从 Amazon ECR 存储库提取至非生产 Fargate 服务。

1. 通过非生产 URL 执行测试。

1. 发布经理批准生产部署。

1. CodePipeline 将新映像部署到生产 Amazon ECS 集群中的现有 Fargate 服务

1. Amazon ECS 将映像从 Amazon ECR 存储库提取至生产 Fargate 服务。

1. 生产用户通过生产 URL 访问功能。

**技术堆栈**
+ AWS CDK
+ CodeBuild
+ CodeCommit 
+ CodePipeline
+ Amazon ECR 
+ Amazon ECS 
+ Amazon VPC

**自动化和扩缩**

您可以使用此模式的方法为部署在共享 AWS CloudFormation 堆栈中的微服务创建管道。自动化功能可以在每个 VPC 中创建多个 Amazon ECS 集群，还可以为部署在共享 Amazon ECS 集群中的微服务创建管道。但是，这要求您提供新资源信息作为管道堆栈输入。

## 工具
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-tools"></a>
+ [AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/home.html) — AWS Cloud Development Kit (AWS CDK) 是一个软件开发框架，用于在代码中定义云基础设施并通过 AWS 进行配置。 CloudFormation
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) — AWS CodeBuild 是一项完全托管的云端构建服务。 CodeBuild 编译您的源代码、运行单元测试并生成可随时部署的工件。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) — AWS CodeCommit 是一项版本控制服务，可让您在 AWS 云中私下存储和管理 Git 存储库。 CodeCommit 您无需管理自己的源代码控制系统或担心扩展其基础架构。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) — AWS CodePipeline 是一项持续交付服务，可用于对发布软件所需的步骤进行建模、可视化和自动化。您可以快速建模和配置软件发布过程的不同阶段。 CodePipeline 自动执行持续发布软件更改所需的步骤。
+ [Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) – Amazon Elastic Container Service (Amazon ECS) 是一项高度可扩展的快速容器管理服务，可用于运行、停止和管理集群上的容器。您可以在由 AWS Fargate 管理的无服务器基础架构上运行任务和服务。或者，为了更好地控制您的基础设施，您可以在托管的 Amazon Elastic Compute Cloud (Amazon EC2) 实例集群上运行任务和服务。
+ [Docker](https://www.docker.com/) - Docker 有助于开发人员打包、交付和运行任何应用程序，将其作为轻量级、便携且自给自足的容器。

**代码**

此模式代码可在 `cicdstarter.zip` 和 `starter-code.zip` 文件（附件）中找到。

## 操作说明
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 AWS CDK 设置工作目录。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html) | AWS DevOps，云基础设施 | 

### 创建共享基础设施
<a name="create-the-shared-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建共享基础设施。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html) | AWS DevOps，云基础设施 | 
| 监控 AWS CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html) | AWS DevOps，云基础设施 | 
| 测试 AWS CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html)请务必记录两个安全组 IDs 的， VPCs 并记录两个安全组 IDs 中的默认安全组的安全组 VPCs。 | AWS DevOps，云基础设施 | 

### 为微服务创建 CI/CD 管道
<a name="create-a-ci-cd-pipeline-for-a-microservice"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为微服务创建基础设施。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html)您也可以使用目录中的 `cdk.json` 文件为这两个命令提供值。 | AWS DevOps，云基础设施 | 
| 监控 AWS CloudFormation 堆栈。 | 打开 AWS CloudFormation 控制台并监控`myservice1-cicd-stack`堆栈的进度。最终状态将更改为 `CREATE_COMPLETE`*。* | AWS DevOps，云基础设施 | 
| 测试 AWS CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html) |  | 
| 使用管道。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html) | AWS DevOps，云基础设施 | 
| 对每项微服务重复此操作说明。 | 重复此长篇故事中的任务，为每个微服务创建 CI/CD 管道。 | AWS DevOps，云基础设施 | 

## 相关资源
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-resources"></a>
+ [使用带 AWS CDK 的 Python](https://docs.aws.amazon.com/cdk/latest/guide/work-with-cdk-python.html) 
+ [AWS CDK Python 参考](https://docs.aws.amazon.com/cdk/api/latest/python/index.html)
+ [使用 AWS CDK 创建 AWS Fargate 服务](https://docs.aws.amazon.com/cdk/latest/guide/ecs_example.html)

## 附加信息
<a name="automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk-additional"></a>

**`cdk synth` **命令

```
cdk synth --context aws_account=<aws_account_number> --context aws_region=<aws_region> --context vpc_nonprod_id=<id_of_non_production VPC> --context vpc_prod_id=<id_of_production_VPC> --context ecssg_nonprod_id=< default_security_group_id_of_non-production_VPC> --context ecssg_prod_id=<default_security_group_id_of_production_VPC> --context code_commit_s3_bucket_for_code=<S3 bucket name> --context code_commit_s3_object_key_for_code=<Object_key_of_starter_code> --context microservice_name=<name_of_microservice>
```

**`cdk deploy `command**

```
cdk deploy --context aws_account=<aws_account_number> --context aws_region=<aws_region> --context vpc_nonprod_id=<id_of_non_production_VPC> --context vpc_prod_id=<id_of_production_VPC> --context ecssg_nonprod_id=< default_security_group_id_of_non-production_VPC> --context ecssg_prod_id=<default_security_group_id_of_production_VPC> --context code_commit_s3_bucket_for_code=<S3 bucket name> --context code_commit_s3_object_key_for_code=<Object_key_of_starter_code> --context microservice_name=<name_of_microservice> 
```

## 附件
<a name="attachments-05ac2cad-408e-433f-8150-0a2b71f63cfd"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/05ac2cad-408e-433f-8150-0a2b71f63cfd/attachments/attachment.zip)

# 使用 GitHub Actions 和 Terraform 构建 Docker 镜像并将其推送到 Amazon ECR
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform"></a>

*Ruchika Modi，Amazon Web Services*

## Summary
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-summary"></a>

此模式说明了如何创建可重复使用 GitHub 的工作流程来构建 Dockerfile 并将生成的映像推送到亚马逊弹性容器注册表 (Amazon ECR) Container Registry (Amazon ECR)。该模式使用 Terraform 和 Actions 自动执行 Dockerfiles 的构建过程。 GitHub 这最大限度地减少了人为错误的可能性，并大大缩短了部署时间。

向 GitHub 存储库的主分支 GitHub 推送操作会启动资源的部署。该工作流程根据 GitHub 组织和存储库名称的组合创建唯一的 Amazon ECR 存储库。然后，它将 Dockerfile 映像推送到 Amazon ECR 存储库。

## 先决条件和限制
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 一个活跃的 GitHub 账户。
+ 存储[GitHub 库](https://docs.github.com/en/get-started/quickstart/create-a-repo)。
+ [已安装并配置](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) 1 或更高版本的 Terraform。
+ [Terraform 后端](https://developer.hashicorp.com/terraform/language/settings/backends/s3)的 Amazon Simple Storage Service（Amazon S3）存储桶。
+ 用于 Terraform 状态锁定和一致性的 [Amazon DynamoDB](https://www.googleadservices.com/pagead/aclk?sa=L&ai=DChcSEwjO95K9xqCCAxW-KIMDHfOvD7IYABADGgJzZg&gclid=EAIaIQobChMIzveSvcagggMVviiDAx3zrw-yEAAYASADEgJYWfD_BwE&ohost=www.google.com&cid=CAASJuRoKjv_llGjIU3liZ4T2IRecPqw0dVHSvjZ7bee1lvcc36K_lO_&sig=AOD64_1b294pq65HiFN-T1YxQAuXmRu_hw&adurl&ved=2ahUKEwjhiY29xqCCAxUgzjgGHRu6CAIQqyQoAnoECAkQDQ) 表。该表必须有一个名为 `LockID`、类型为 `String` 的分区键。如果未进行此配置，则状态锁定将被禁用。
+ 有权为 Terraform 设置 Amazon S3 后端的 AWS Identity and Access Management（IAM）角色。有关配置说明，请参阅 [Terraform 文档](https://developer.hashicorp.com/terraform/language/settings/backends/s3#assume-role-configuration)。

**限制**

此可重复使用的代码仅通过 GitHub 操作进行了测试。

## 架构
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-architecture"></a>

**目标技术堆栈**
+ Amazon ECR 存储库
+ GitHub 行动
+ Terraform

**目标架构**

![\[创建可重复使用的工作 GitHub 流程以构建 Dockerfile 并将映像推送到 Amazon ECR 的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/c39c110e-cbe5-459e-a0aa-de27e884fb10/images/298e0e16-3054-49b7-8695-db510e0df2df.png)


下图说明了以下内容：

1. 用户将 Dockerfile 和 Terraform 模板添加到存储库中。 GitHub 

2. 这些新增内容启动了 GitHub 操作工作流程。

3. 该工作流检查 Amazon ECR 存储库是否存在。否则，它将根据 GitHub 组织和存储库名称创建存储库。

4. 该工作流构建 Dockerfile 并将映像推送到 Amazon ECR 存储库。

## 工具
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-tools"></a>

**Amazon 服务**
+ [Amazon Elastic Container Registry（Amazon ECR）](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)是一项安全、可扩展且可靠的托管容器注册表服务。

**其他工具**
+ [GitHub 操作](https://docs.github.com/en/actions)已集成到 GitHub 平台中，可帮助您在 GitHub 仓库中创建、共享和运行工作流程。您可以使用 GitHub Actions 来自动执行构建、测试和部署代码等任务。
+ [Terraform](https://developer.hashicorp.com/terraform/intro) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地基础架构。

**代码存储库**

此模式的代码可在 GitHub [Docker ECR 操作工作流](https://github.com/aws-samples/docker-ecr-actions-workflow)存储库中找到。
+ 创建 GitHub 操作时，Docker 工作流程文件将保存在此存储库的`/.github/workflows/`文件夹中。此解决方案的工作流位于 [workflow.yaml](https://github.com/aws-samples/docker-ecr-actions-workflow/blob/main/.github/workflows/workflow.yaml) 文件中。
+ `e2e-test` 文件夹提供了示例 Dockerfile 以供参考和测试。

## 最佳实践
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-best-practices"></a>
+ 有关编写 Dockerfile 的最佳实践，请参阅 [Docker 文档](https://docs.docker.com/develop/develop-images/dockerfile_best-practices/)。
+ 对 [Amazon ECR 使用 VPC 端点](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html)。VPC 终端节点由 AWS 提供支持 PrivateLink，该技术使您能够 APIs 通过私有 IP 地址私密访问 Amazon ECR。对于使用 Fargate 启动类型的 Amazon ECS 任务，VPC 端点让任务能够从 Amazon ECR 中提取私有映像，而无需为任务分配公共 IP 地址。

## 操作说明
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-epics"></a>

### 设置 OIDC 提供商和存储库 GitHub
<a name="set-up-the-oidc-provider-and-github-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置 OpenID Connect。 | 创建 OpenID Connect（OIDC）提供者。您将在此操作中所用的 IAM 角色的信任策略中使用此提供商。有关说明，请参阅文档[中的在亚马逊 Web Services 中配置 OpenID Connect](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)。 GitHub  | AWS 管理员、AWS DevOps、常规 AWS | 
| 克隆 GitHub 存储库。 | 将 GitHub [Docker ECR 操作工作流](https://github.com/aws-samples/docker-ecr-actions-workflow)存储库克隆到您的本地文件夹：<pre>$git clone https://github.com/aws-samples/docker-ecr-actions-workflow</pre> | DevOps 工程师 | 

### 自定义 GitHub 可重复使用的工作流程并部署 Docker 镜像
<a name="customize-the-github-reusable-workflow-and-deploy-the-docker-image"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 自定义启动 Docker 工作流的事件。 | 此解决方案的工作流位于 [workflow.yaml](https://github.com/aws-samples/docker-ecr-actions-workflow/blob/main/.github/workflows/workflow.yaml) 中。此脚本当前配置为在收到 `workflow_dispatch` 事件时部署资源。您可以自定义此配置，将事件更改为 `workflow_call` 并且从另一个父工作流调用该工作流。 | DevOps 工程师 | 
| 自定义工作流。 | w [orkflow.yaml](https://github.com/aws-samples/docker-ecr-actions-workflow/blob/main/.github/workflows/workflow.yaml) 文件被配置为创建动态、可重复使用的工作流程。 GitHub 您可以编辑此文件以自定义默认配置，或者如果您使用`workflow_dispatch`事件手动启动部署，则可以从 Actions 控制台传递输入值。 GitHub [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform.html) | DevOps 工程师 | 
| 部署 Terraform 模板。 | 该工作流程会根据您配置的事件自动部署用于创建 Amazon ECR 存储库的 Terraform 模板。 GitHub 这些模板在 [Github 存储库的根目录](https://github.com/aws-samples/docker-ecr-actions-workflow/tree/main)下以 `.tf` 文件形式提供。 | AWS DevOps， DevOps 工程师 | 

## 问题排查
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 将 Amazon S3 和 DynamoDB 配置为 Terraform 远程后端时出现问题或错误。 | 按照 [Terraform 文档](https://developer.hashicorp.com/terraform/language/settings/backends/s3)中的说明为远程后端配置在 Amazon S3 和 DynamoDB 资源上设置所需的权限。 | 
| 无法通过 `workflow_dispatch` 事件运行或启动工作流。 | 只有工作流也在主分支上进行了配置时，配置为从 `workflow_dispatch` 事件部署的工作流才会运行。 | 

## 相关资源
<a name="build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform-resources"></a>
+ [重复使用工作流程](https://docs.github.com/en/actions/using-workflows/reusing-workflows)（GitHub 文档）
+ [触发工作流程](https://docs.github.com/en/actions/using-workflows/triggering-a-workflow)（GitHub 文档）

# 使用 AWS CodeCommit、AWS 和 AWS Device Farm 构建和测试 iOS 应用程序 CodePipeline
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm"></a>

*Abdullahi Olaoye，Amazon Web Services*

## Summary
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-summary"></a>

此模式概述了创建持续集成和持续交付 (CI/CD) 管道的步骤，该管道使用 AWS 在 AWS CodePipeline 上的真实设备上构建和测试 iOS 应用程序。该模式使用 AWS CodeCommit 来存储应用程序代码，使用 Jenkins 开源工具来构建 iOS 应用程序，使用 AWS Device Farm 在真实设备上测试构建的应用程序。这三个阶段是使用 AWS 在管道中共同编排的。 CodePipeline

这种模式基于 AWS DevOps 博客上的 “使用 AW [S 和移动服务构建和测试 iOS DevOps 和 iPadOS 应用程序](https://aws.amazon.com/blogs/devops/building-and-testing-ios-and-ipados-apps-with-aws-devops-and-mobile-services/)” 一文。有关详细说明，请参阅此博客文章。

## 先决条件和限制
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户
+ 一个 Apple 开发人员账户
+ 编译服务器 (macOS)
+ [Xcode](https://developer.apple.com/xcode/) 版本 11.3（已在编译服务器上安装和设置）
+ AWS 命令行界面（AWS CLI）已在工作站上[安装](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv1.html)并[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ [Git](https://git-scm.com/docs) 基础知识

**限制**
+ 应用程序编译服务器必须运行 macOS。
+ 生成服务器必须具有公有 IP 地址，因此 CodePipeline 可以远程连接到该服务器以启动构建。

## 架构
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-architecture"></a>

**源技术堆栈**
+ 本地 iOS 应用程序构建过程，涉及在物理设备上使用模拟器或手动测试

**目标技术堆栈**
+ 用于 CodeCommit 存储应用程序源代码的 AWS 存储库
+ 使用 Xcode 构建应用程序的 Jenkins 服务器
+ 用于在真实设备上测试应用程序的 AWS Device Farm 设备池

**目标架构**

当用户向源存储库提交更改时，管道 (AWS CodePipeline) 会从源存储库获取代码，启动 Jenkins 构建，然后将应用程序代码传递给 Jenkins。构建完成后，管道会检索构建构件并启动 AWS Device Farm 作业，根据设备池测试应用程序。

 

![\[CI/CD 管道使用 AWS CodePipeline 在真实设备上构建和测试 iOS 应用程序。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/06fbd82f-4aed-441c-818c-5f89f56af78e/images/0ae3d7b6-b40c-44ef-9580-8c8266c3d841.png)


## 工具
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-tools"></a>
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 是一项完全托管的持续交付服务，可帮助您自动执行发布管道，实现快速可靠的应用程序和基础设施更新。 CodePipeline 每次发生代码更改时，都会根据您定义的发布模型自动执行发布过程的构建、测试和部署阶段。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) 是一项完全托管的源代码控制服务，可托管基于 Git 的安全存储库。它使团队可以轻松地在安全且高度可扩展的生态系统中就代码进行协作。 CodeCommit 无需操作自己的源代码控制系统或担心扩展其基础架构。
+ [AWS Device Farm](https://docs.aws.amazon.com/devicefarm/latest/developerguide/welcome.html) 是一项应用程序测试服务，可让您通过在各种桌面浏览器和真实移动设备上测试网页和移动应用程序来提高其质量，而无需预调配和管理任何测试基础设施。
+ [Jenkins](https://www.jenkins.io/) 是一款开源自动化服务器，它使开发人员能够构建、测试和部署其软件。

## 操作说明
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在运行 macOS 的编译服务器上安装 Jenkins。 | Jenkins 将用于构建应用程序，因此您必须首先将其安装至编译服务器上。要获取有关此任务和后续任务的详细说明，请参阅本模式末尾的 “[相关](#build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-resources)资源” 部分中的 AWS 博客文章 “[使用 AWS DevOps 和移动服务以及其他资源构建和测试 iOS 和 iPadOS 应用程序](https://aws.amazon.com/blogs/devops/building-and-testing-ios-and-ipados-apps-with-aws-devops-and-mobile-services/)”。 | DevOps | 
| 配置 Jenkins。 | 按屏幕上的说明进行配置 Jenkins。 | DevOps | 
| 安装适用于 Jenkins 的 AWS CodePipeline 插件。 | 为了让 Jenkins 与 AWS CodePipeline 服务进行交互，此插件必须安装在 Jenkins 服务器上。 | DevOps | 
| 创建一个 Jenkins 自由式项目。 | 在 Jenkins 中创建一个自由式项目。配置项目以指定触发器和其他构建配置选项。 | DevOps | 

### 配置 AWS Device Farm
<a name="configure-aws-device-farm"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Device Farm 项目。 | 打开 AWS Device Farm 控制台。创建一个项目和一个设备池进行测试。有关说明，请参见博客文章。 | 开发者版 | 

### 配置源存储库
<a name="configure-the-source-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 CodeCommit 存储库。 | 创建一个存储源代码的存储库。 | DevOps | 
| 将应用程序代码提交至存储库。 | Connect 连接到您创建的 CodeCommit 存储库。将代码从本地计算机推送至存储库。 | DevOps | 

### 配置管道
<a name="configure-the-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 AWS 中创建管道 CodePipeline。 | 打开 AWS CodePipeline 控制台，然后创建管道。管道协调了流程的所有阶段。 CI/CD 有关说明，请参阅 AWS 博客文章使用 AW [S 和移动服务构建和测试 iOS DevOps 和 iPadOS 应用程序](https://aws.amazon.com/blogs/devops/building-and-testing-ios-and-ipados-apps-with-aws-devops-and-mobile-services/)。 | DevOps | 
| 向管道中添加测试阶段。 | 要添加测试阶段并将其与 AWS Device Farm 集成，请编辑该管道。 | DevOps | 
| 启动管道。 | 要启动管道和 CI/CD 流程，请选择 “**发布更改**”。 | DevOps | 

### 查看应用程序测试结果
<a name="view-application-test-results"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看测试结果。 | 在 AWS Device Farm 控制台，选择您创建的项目，然后查看测试结果。控制台将显示每项测试详细信息。 | 开发者版 | 

## 相关资源
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm-resources"></a>

**Step-by-step 此模式的说明**
+ 使用 AW@@ [S 和移动服务构建和测试 iOS DevOps 和 iPadOS 应用程序](https://aws.amazon.com/blogs/devops/building-and-testing-ios-and-ipados-apps-with-aws-devops-and-mobile-services/)（AWS DevOps 博客文章）

**配置 AWS Device Farm**
+ [AWS Device Farm 控制台](https://console.aws.amazon.com/devicefarm)

**配置源存储库**
+ [创建 AWS CodeCommit 存储库](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-repository.html)
+ [连接到 AWS CodeCommit 存储库](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)

**配置管道**
+ [AWS CodePipeline 控制台](https://console.aws.amazon.com/codesuite/codepipeline/home)

**其他资源**
+ [AWS CodePipeline 文档](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)
+ [AWS CodeCommit 文档](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html)
+ [AWS Device Farm 文档](https://docs.aws.amazon.com/devicefarm/latest/developerguide/welcome.html)
+ [Jenkins 文档](https://www.jenkins.io/doc/)
+ [在 macOS 上安装 Jenkins](https://www.jenkins.io/download/weekly/macos/)
+ [适用于 Jenkins 的 AWS CodePipeline 插件](https://plugins.jenkins.io/aws-codepipeline/)
+ [Xcode 安装](https://developer.apple.com/xcode/)
+ AWS CLI [安装](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv1.html)和[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ [Git 文档](https://git-scm.com/docs)

# 为在 Amazon EKS 上运行的应用程序配置双向 TLS 身份验证
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks"></a>

*Mahendra Revanasiddappa，Amazon Web Services*

## Summary
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-summary"></a>

基于证书的传输层安全性协议（TLS）是一个可选的 TLS 组件，可在服务器和客户端之间提供双向对等身份验证。使用双向 TLS，客户端必须在会话协商过程中提供 X.509 证书。服务器使用此证书来识别和验证客户端。

双向 TLS 是物联网 (IoT) 应用的常见要求，可用于[开放银行](https://docs.aws.amazon.com/wellarchitected/latest/financial-services-industry-lens/open-banking.html)等 business-to-business应用或标准。

此模式描述如何使用 NGINX 入口控制器为运行在 Amazon Elastic Kubernetes Service（Amazon EKS）集群上的应用程序配置双向 TLS。您可以通过注释入口资源来为 NGINX 入口控制器启用内置的双向 TLS 功能。有关 NGINX 控制器上双向 TLS 注释的更多信息，请参阅 Kubernetes 文档中的[客户端证书身份验证](https://kubernetes.github.io/ingress-nginx/user-guide/nginx-configuration/annotations/#client-certificate-authentication)。

**重要**  
此模式使用自签名证书。我们建议您只在测试集群中使用此功能，而不要在生产环境中使用。如果您想在生产环境中使用此模式，则可以使用 [AWS 私有证书颁发机构（AWS Private CA）](https://docs.aws.amazon.com/privateca/latest/userguide/PcaWelcome.html)或您现有的公有密钥基础设施（PKI）标准来颁发私有证书。

## 先决条件和限制
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-prereqs"></a>

**先决条件**
+ 一个 Amazon Web Services（AWS）有效账户。
+ 现有 Amazon EKS 集群。
+ AWS 命令行界面（AWS CLI）版本 1.7 或更高版本，已在 macOS、Linux 或 Windows 上安装并配置。
+ 已安装并配置的 kubectl 命令行实用程序，以便访问 Amazon EKS 集群。有关这方面的更多信息，请参阅 Amazon EKS 文档中的[安装 kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)。
+ 用于测试应用程序的现有域名系统（DNS）名称。

**限制**
+ 此模式使用自签名证书。我们建议您只在测试集群中使用此功能，而不要在生产环境中使用。

## 架构
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-architecture"></a>

![\[为在 Amazon EKS 上运行的应用程序配置双向 TLS 身份验证\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/ae2761e3-7ed2-4c2a-ba54-a4ddce8a1e7e/images/cefc60f9-2f29-4052-b7ae-df4eb6395e1c.png)


**技术堆栈**
+ Amazon EKS
+ Amazon Route 53
+ Kubectl

## 工具
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-tools"></a>
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) 可帮助您在 AWS 上运行 Kubernetes，而无需安装或维护您自己的 Kubernetes 控制面板或节点。
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一种可用性高、可扩展性强的 DNS Web 服务。
+ [Kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html) 是命令行实用程序，用于与 Amazon EKS 集群交互。

## 操作说明
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-epics"></a>

### 生成自签名证书
<a name="generate-the-self-signed-certificates"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  生成 CA 密钥和证书。 | 通过运行以下命令生成证书颁发机构（CA）密钥和证书。<pre>openssl req -x509 -sha256 -newkey rsa:4096 -keyout ca.key -out ca.crt -days 356 -nodes -subj '/CN=Test Cert Authority'</pre> | DevOps 工程师 | 
| 生成服务器密钥和证书，并使用 CA 证书进行签名。 | 通过运行以下命令生成服务器密钥和证书，并使用 CA 证书进行签名。<pre>openssl req -new -newkey rsa:4096 -keyout server.key -out server.csr -nodes -subj '/CN= <your_domain_name> ' && openssl x509 -req -sha256 -days 365 -in server.csr -CA ca.crt -CAkey ca.key -set_serial 01 -out server.crt</pre>请确认将 `<your_domain_name>` 替换为现有域名。 | DevOps 工程师 | 
|  生成客户端密钥和证书，并使用 CA 证书进行签名。 | 通过运行以下命令生成客户端密钥和证书，并使用 CA 证书进行签名。<pre>openssl req -new -newkey rsa:4096 -keyout client.key -out client.csr -nodes -subj '/CN=Test' && openssl x509 -req -sha256 -days 365 -in client.csr -CA ca.crt -CAkey ca.key -set_serial 02 -out client.crt</pre> | DevOps 工程师 | 

### 部署 NGINX 入口控制器
<a name="deploy-the-nginx-ingress-controller"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将 NGINX 入口控制器部署到 Amazon EKS 集群中。 | 使用以下命令部署 NGINX 入口控制器。<pre>kubectl apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/controller-v1.7.0/deploy/static/provider/aws/deploy.yaml</pre> | DevOps 工程师 | 
|  验证 NGINX 入口控制器服务正在运行。 | 使用以下命令验证 NGINX 入口控制器服务正在运行。<pre>kubectl get svc -n ingress-nginx</pre>请确认服务地址字段包含网络负载均衡器的域名。 | DevOps 工程师 | 

### 在 Amazon EKS 集群中创建命名空间来测试双向 TLS
<a name="create-a-namespace-in-the-amazon-eks-cluster-to-test-mutual-tls"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 Amazon EKS 集群中创建命名空间。 | 通过运行以下命令在 Amazon EKS 集群中创建名为 `mtls` 的命名空间。<pre>kubectl create ns mtls</pre>这将部署示例应用程序来测试双向 TLS。 | DevOps 工程师 | 

### 为示例应用程序创建部署和服务
<a name="create-the-deployment-and-service-for-the-sample-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 mtls 命名空间中创建 Kubernetes 部署和服务。 | 创建一个名为 `mtls.yaml`的文件。将以下代码粘贴到该文件中。<pre>kind: Deployment<br />apiVersion: apps/v1<br />metadata:<br />  name: mtls-app<br />  labels:<br />    app: mtls<br />spec:<br />  replicas: 1<br />  selector:<br />    matchLabels:<br />      app: mtls<br />  template:<br />    metadata:<br />      labels:<br />        app: mtls<br />    spec:<br />      containers:<br />      - name: mtls-app<br />        image: hashicorp/http-echo<br />        args:<br />          - "-text=mTLS is working"<br /><br /><br />---<br /><br />kind: Service<br />apiVersion: v1<br />metadata:<br />  name: mtls-service<br />spec:<br />  selector:<br />    app: mtls<br />  ports:<br />    - port: 5678 # Default port for image</pre> 通过运行以下命令在 `mtls` 命名空间中创建 Kubernetes 部署和服务。<pre>kubectl create -f mtls.yaml -n mtls</pre> | DevOps 工程师 | 
| 验证已创建 Kubernetes 部署。 | 运行以下命令验证部署是否已创建，且有一个容器组（pod）处于可用状态。<pre>kubectl get deploy -n mtls</pre> | DevOps 工程师 | 
| 验证是否已创建 Kubernetes 服务。 | 通过运行以下命令验证是否已创建 Kubernetes 服务。<pre>kubectl get service -n mtls</pre> | DevOps 工程师 | 

### 在 mtls 命名空间中创建密钥
<a name="create-a-secret-in-the-mtls-namespace"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建入口资源的密钥。 | 运行以下命令，使用您之前创建的证书为 NGINX 入口控制器创建密钥。<pre>kubectl create secret generic mtls-certs --from-file=tls.crt=server.crt --from-file=tls.key=server.key --from-file=ca.crt=ca.crt -n mtls </pre>您的密钥有一个服务器证书供客户端识别服务器，还有一个 CA 证书供服务器验证客户端证书。 | DevOps 工程师 | 

### 在 mtls 命名空间中创建入口资源
<a name="create-the-ingress-resource-in-the-mtls-namespace"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 mtls 命名空间中创建入口资源。 | 创建一个名为 `ingress.yaml`的文件。将以下代码粘贴到文件中（将 `<your_domain_name>` 替换为现有域名）。<pre>apiVersion: networking.k8s.io/v1<br />kind: Ingress<br />metadata:<br />  annotations:<br />    nginx.ingress.kubernetes.io/auth-tls-verify-client: "on"<br />    nginx.ingress.kubernetes.io/auth-tls-secret: mtls/mtls-certs<br />  name: mtls-ingress<br />spec:<br />  ingressClassName: nginx<br />  rules:<br />  - host: "*.<your_domain_name>"<br />    http:<br />      paths:<br />      - path: /<br />        pathType: Prefix<br />        backend:<br />          service:<br />            name: mtls-service<br />            port:<br />              number: 5678<br />  tls:<br />  - hosts:<br />    - "*.<your_domain_name>"<br />    secretName: mtls-certs</pre>通过运行以下命令以在 `mtls` 命名空间中创建入口资源。<pre>kubectl create -f ingress.yaml -n mtls</pre>这意味着 NGINX 入口控制器可以将流量路由到示例应用程序。 | DevOps 工程师 | 
| 验证入口资源是否已创建。 | 通过运行以下命令验证是否已创建入口资源。<pre>kubectl get ing -n mtls</pre>请确认入口资源的地址显示为 NGINX 入口控制器创建的负载均衡器。 | DevOps 工程师 | 

### 配置 DNS 以将主机名指向负载均衡器
<a name="configure-dns-to-point-the-hostname-to-the-load-balancer"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建指向 NGINX 入口控制器的负载均衡器的 CNAME 记录。 | 登录 AWS 管理控制台，打开 Amazon Route 53 控制台，然后创建将 `mtls.<your_domain_name>` 指向 NGINX 入口控制器的负载均衡器的规范名称（CNAME）记录。有关更多信息，请参阅 Route 53 文档中的[使用 Route 53 控制台创建记录](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html)。 | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在没有证书的情况下测试双向 TLS 设置。 | 运行如下命令。<pre>curl -k https://mtls.<your_domain_name> </pre>您应该收到“400 未发送必需的 SSL 证书”错误响应。 | DevOps 工程师 | 
| 在有证书的情况下测试双向 TLS 设置。 | 运行如下命令。<pre>curl -k https://mtls.<your_domain_name> --cert client.crt --key client.key</pre>您应该收到“mTLS 正在运行”的响应。 | DevOps 工程师 | 

## 相关资源
<a name="configure-mutual-tls-authentication-for-applications-running-on-amazon-eks-resources"></a>
+ [通过使用 Amazon Route 53 控制台创建记录](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html)
+ [在 Amazon EKS 上使用带有 NGINX 入口控制器的网络负载均衡器](https://aws.amazon.com/blogs/opensource/network-load-balancer-nginx-ingress-controller-eks/)
+ [客户证书认证](https://kubernetes.github.io/ingress-nginx/examples/auth/client-certs/)

# 使用自动创建 Amazon WorkSpaces 应用程序资源 AWS CloudFormation
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation"></a>

*Ram Kandaswamy，Amazon Web Services*

## Summary
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-summary"></a>

此模式提供了使用[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)模板在中自动创建 [Amazon A WorkSpaces pp](https://aws.amazon.com/workspaces/applications/) lication AWS 云 s 资源的代码示例和步骤。该模式向您展示如何使用 CloudFormation 堆栈自动创建 WorkSpaces 应用程序资源，包括映像生成器、映像、队列实例和堆栈。您可以使用桌面或 WorkSpaces 应用程序交付模式，在 HTML5兼容的浏览器上将应用程序流式传输给最终用户。

## 先决条件和限制
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 接受 WorkSpaces 应用程序条款和条件
+  WorkSpaces [应用程序资源的基础知识，例如[队列和堆栈以及映](https://docs.aws.amazon.com/appstream2/latest/developerguide/managing-stacks-fleets.html)像生成器](https://docs.aws.amazon.com/appstream2/latest/developerguide/managing-image-builders.html)

**限制**
+ 创建 WorkSpaces 应用程序实例后，您无法修改与该实例关联的 [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)(IAM) 角色。
+ 创建 WorkSpaces 应用镜像生成器实例后，您无法修改该映像生成器实例的属性（例如[子网](https://docs.aws.amazon.com/vpc/latest/userguide/configure-subnets.html#subnet-basics)或[安全组](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html)）。

## 架构
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-architecture"></a>

下图向您展示了如何使用 CloudFormation 模板自动创建 WorkSpaces 应用程序资源。

![\[自动创建 WorkSpaces 应用程序资源的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/4f0205f5-5b91-4832-9f0f-2135ae866226/images/cb578939-d9af-4f60-93c9-286881df4c3a.png)


下图显示了如下工作流：

1. 您可以根据此模式的 “[其他信息](#automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-additional)” 部分中的 YAML 代码创建 CloudFormation 模板。

1. 该 CloudFormation 模板创建了一个 CloudFormation 测试堆栈。

   1. （可选）您可以使用 WorkSpaces 应用程序创建映像生成器实例。

   1. （可选）您可以使用自定义软件创建 Windows 映像。

1.  CloudFormation 堆栈创建 WorkSpaces 应用程序队列实例和堆栈。

1. 您可以在 HTML5兼容的浏览器上将 WorkSpaces 应用程序资源部署给最终用户。

## 工具
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-tools"></a>
+ [Amazon A WorkSpaces ](https://docs.aws.amazon.com/appstream2/latest/developerguide/what-is-appstream.html) pplications 是一项完全托管的应用程序流服务，可让您随时随地即时访问您的桌面应用程序。 WorkSpaces 应用程序管理托管和运行应用程序所需的 AWS 资源，自动扩展，并按需向用户提供访问权限。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您对资源进行建模和设置，快速一致地配置 AWS 资源，并在资源的整个生命周期中对其进行管理。您可以使用模板来描述资源及其依赖关系，然后将它们作为堆栈一起启动和配置，而不必单独管理资源。您可以跨多个 AWS 账户 和 AWS 区域管理和配置堆栈。

## 最佳实践
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-best-practices"></a>
+ **正确配置映像生成器的网络访问权限 — 使用 NAT 网关进行**仅限出站互联网访问，在具有适当互联网访问权限的虚拟私有云 (VPC) 子网中启动映像生成器。

  在创建映像之前，测试与所需资源（例如应用程序服务器、数据库和许可服务器）的网络连接。验证 VPC 路由表是否允许连接到所有必需的网络资源。有关更多信息，请参阅 WorkSpaces 应用程序文档中的[互联网接入](https://docs.aws.amazon.com/appstream2/latest/developerguide/internet-access.html)。
+ **根据服务配额主动监控队列容量** — WorkSpaces 应用程序实例类型和大小配额按每个 AWS 账户、每个 AWS 区域。如果您在同一区域有多个实例集使用相同的实例类型和大小，则该区域所有实例集中的实例总数必须小于或等于适用的配额。有关更多信息，请参阅 WorkSpaces 应用程序文档中的[队列故障排除](https://docs.aws.amazon.com/appstream2/latest/developerguide/troubleshooting-fleets.html)。
+ **部署队列之前，在 Image Builder 测试模式下测试应用程序 — 在创建映像并部署到队列**之前，请务必在 Image Builder 测试模式下验证应用程序。测试模式模拟最终用户对舰队实例的有限权限。有关更多信息，请参阅 WorkSpaces 应用程序文档中的[映像生成器故障排除](https://docs.aws.amazon.com/appstream2/latest/developerguide/troubleshooting-image-builder.html#troubleshooting-07)。

## 操作说明
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-epics"></a>

### （可选）创建 WorkSpaces 应用程序镜像
<a name="optional-create-a-aas2-image"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装自定义软件和创建映像。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation.html)考虑使用 Windows AppLocker 功能进一步锁定图像。 | AWS DevOps，云架构师 | 

### 部署 CloudFormation 模板
<a name="deploy-the-cfn-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新 CloudFormation 模板。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation.html) | AWS 系统管理员、云管理员、云架构师、常规 AWS、AWS 系统管理员 | 
| 使用模板创建 CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation.html) | 应用程序所有者、AWS 系统管理员、Windows 工程师 | 

## 问题排查
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 各种问题 | 有关更多信息，请参阅 WorkSpaces 应用程序文档中的[故障排除](https://docs.aws.amazon.com/appstream2/latest/developerguide/troubleshooting.html)。 | 

## 相关资源
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-resources"></a>

**参考**
+ [开始使用 Amazon WorkSpaces 应用程序：使用示例应用程序进行设置](https://docs.aws.amazon.com/appstream2/latest/developerguide/getting-started.html)
+ [创建 Amazon WorkSpaces 应用程序队列和堆栈](https://docs.aws.amazon.com/appstream2/latest/developerguide/set-up-stacks-fleets.html)

**教程和视频**
+ [Amazon WorkSpaces 应用程序用户工作流程](https://www.youtube.com/watch?v=hVGQ87-Uhrc)
+ [如何将旧版 Windows Forms 应用程序迁移到亚马逊 WorkSpaces 应用程序](https://www.youtube.com/watch?v=CIImtS2iVbg)
+ [AWS re: Invent 2018：使用亚马逊 WorkSpaces 应用程序安全交付桌面应用程序 (01) BAP2](https://www.youtube.com/watch?v=xNIyc_inOhM)

## 附加信息
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-additional"></a>

以下代码是一个模板示例，您可以使用该 CloudFormation 模板自动创建 WorkSpaces 应用程序资源。

```
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  SubnetIds:
    Type: 'List<AWS::EC2::Subnet::Id>'
  testSecurityGroup:
    Type: 'AWS::EC2::SecurityGroup::Id'
  ImageName:
    Type: String
Resources:
  
  AppStreamFleet:
    Type: 'AWS::AppStream::Fleet'
    Properties:
      ComputeCapacity:
        DesiredInstances: 5
      InstanceType: stream.standard.medium
      Name: appstream-test-fleet
      DisconnectTimeoutInSeconds: 1200
      FleetType: ON_DEMAND
      IdleDisconnectTimeoutInSeconds: 1200
      ImageName: !Ref ImageName
      MaxUserDurationInSeconds: 345600
      VpcConfig:
        SecurityGroupIds:
          - !Ref testSecurityGroup
        SubnetIds: !Ref SubnetIds
  AppStreamStack:
    Type: 'AWS::AppStream::Stack'
    Properties:
      Description: AppStream stack for test
      DisplayName: AppStream test Stack
      Name: appstream-test-stack
      StorageConnectors:
        - ConnectorType: HOMEFOLDERS
      UserSettings:
        - Action: CLIPBOARD_COPY_FROM_LOCAL_DEVICE
          Permission: ENABLED
        - Action: CLIPBOARD_COPY_TO_LOCAL_DEVICE
          Permission: ENABLED
        - Action: FILE_DOWNLOAD
          Permission: ENABLED
        - Action: PRINTING_TO_LOCAL_DEVICE
          Permission: ENABLED
  AppStreamFleetAssociation:
    Type: 'AWS::AppStream::StackFleetAssociation'
    Properties:
      FleetName: appstream-test-fleet
      StackName: appstream-test-stack
    DependsOn:
      - AppStreamFleet
      - AppStreamStack
```

# 使用 Firelens 日志路由器为 Amazon ECS 创建自定义日志解析器
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router"></a>

*Varun Sharma，Amazon Web Services*

## Summary
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-summary"></a>

Firelens 是适用于 Amazon Elastic Container Service （Amazon ECS）和 AWS Fargate 的日志路由器。您可以使用 Firelens 将容器日志从 Amazon ECS 路由到亚马逊 CloudWatch 和其他目的地（例如 [Splunk](https://www.splunk.com/) 或 S [um](https://www.sumologic.com/) o Logic）。Firelens 使用 [Fluentd](https://www.fluentd.org/) 或 [Fluent Bit](https://fluentbit.io/) 作为日志记录代理，这意味着您可以使用 [Amazon ECS 任务定义参数](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html)来路由日志。

通过选择在源级别解析日志，您可以分析您的日志记录数据并执行查询，从而更加高效和有效地响应操作问题。由于不同的应用程序具有不同的日志模式，因此您需要使用自定义解析器来构建日志，以便在最终目的地更轻松地进行搜索。

此模式使用带有自定义解析器的 Firelens 日志路由器 CloudWatch 从 Amazon ECS 上运行的示例 Spring Boot 应用程序推送日志。然后，您可以使用 Amazon CloudWatch Logs Insights 根据自定义解析器生成的自定义字段筛选日志。

## 先决条件和限制
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-prereqs"></a>

**先决条件**
+ 活跃 Amazon Web Services (AWS) account
+ AWS 命令行界面（AWS CLI）已在本地计算机上安装和配置。
+ 已在本地计算机上安装并配置的 Docker。
+ Amazon Elastic Container Registry (Amazon ECR) 上现有的基于 Spring Boot 的容器化应用程序。 

## 架构
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-architecture"></a>

![\[使用 Firelens 日志路由器将日志 CloudWatch 从 Amazon ECS 上运行的应用程序推送到。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e82b4992-c4e0-4af5-b87e-cb0b1c1ed8c9/images/ef60e087-965a-40e9-9f80-35edbda2befe.png)


**技术堆栈**
+ CloudWatch
+ Amazon ECR
+ Amazon ECS
+ Fargate
+ Docker
+ Fluent Bit

## 工具
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-tools"></a>
+ [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) - Amazon Elastic Container Registry (Amazon ECR) 是一项由 AWS 托管的容器映像注册表服务，该服务安全可靠，且可扩展。
+ [Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html) - Amazon Elastic Container Service (Amazon ECS) 是一项高度可扩展的快速容器管理服务，可轻松在集群上运行、停止和管理容器。
+ [AWS 身份识别和访问管理(IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) - IAM 是一项 Web 服务，用于安全控制 Amazon Web Services 的访问。
+ [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) - AWS 命令行界面（AWS CLI）是一种开源工具，可让您使用命令行 Shell 中的命令与 Amazon Web Services 交互。
+ [Docker](https://www.docker.com/) - Docker 是用于开发、发布和运行应用程序的开放平台。

**代码**

此模式附加了以下文件：
+ `customFluentBit.zip` - 包含用于添加自定义解析和配置的文件。
+ `firelens_policy.json` - 包含用于创建 IAM policy 的策略文档。
+ `Task.json` - 包含 Amazon ECS 的示例任务定义。

## 操作说明
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-epics"></a>

### 创建自定义 Fluent Bit 映像
<a name="create-a-custom-fluent-bit-image"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon ECR 存储库。 | 登录 AWS 管理控制台，打开 Amazon ECR 控制台，然后创建一个名为 `fluentbit_custom` 的存储库。有关此内容的更多信息，请参阅 Amazon ECR 文档中的[创建存储库](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)。 | 系统管理员、开发人员 | 
| 解压 customFluentBit .zip 压缩包。 |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.html) |  | 
| 创建自定义 Docker 映像。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.html)有关更多信息，请参阅 Amazon ECR 文档中的[推送 Docker 映像](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)。  | 系统管理员、开发人员 | 

### 设置 Amazon ECS 集群
<a name="set-up-the-amazon-ecs-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon ECS 集群。 | 按照 Amazon ECS 文档中[创建集群](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create_cluster.html)的*仅联网模板*部分中的说明创建 Amazon ECS 集群。请确认选择**创建 VPC** 来为您的 Amazon ECS 集群创建新的虚拟私有云（VPC）。 | 系统管理员、开发人员 | 

### 设置 Amazon ECS 任务
<a name="set-up-the-amazon-ecs-task"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  设置 Amazon ECS 任务执行 IAM 角色。 | 使用 `AmazonECSTaskExecutionRolePolicy` 托管策略创建 Amazon ECS 任务执行 IAM 角色。有关此内容的更多信息，请参阅 Amazon ECS 文档中的 [Amazon ECS 任务执行 IAM 角色](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_execution_IAM_role.html)。请确认记录 IAM 角色的 Amazon 资源名称（ARN）。 | 系统管理员、开发人员 | 
|  将 IAM policy 附加到 Amazon ECS 任务执行 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.html) | 系统管理员、开发人员 | 
| 设置 Amazon ECS 任务定义。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.html)有关此内容的更多信息，请参阅 Amazon ECS 文档中的[创建任务定义](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create-task-definition.html)。 | 系统管理员、开发人员 | 

### 运行 Amazon ECS 任务
<a name="run-the-amazon-ecs-task"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 运行 Amazon ECS 任务。 | 在 Amazon ECS 控制台上，选择**集群**，选择您之前创建的集群，然后运行独立任务。有关此内容的更多信息，请参阅 Amazon ECS 文档中的[运行独立任务](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs_run_task.html)。 | 系统管理员、开发人员 | 

### 验证日 CloudWatch 志
<a name="verify-the-cloudwatch-logs"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证日志。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router.html) | 系统管理员、开发人员 | 

## 相关资源
<a name="create-a-custom-log-parser-for-amazon-ecs-using-a-firelens-log-router-resources"></a>
+ [Amazon ECS 的 Docker 基本信息](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/docker-basics.html) 
+ [AWS Fargate 上的 Amazon ECS](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html) 
+ [配置基本服务参数](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/basic-service-params.html) 

## 附件
<a name="attachments-e82b4992-c4e0-4af5-b87e-cb0b1c1ed8c9"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/e82b4992-c4e0-4af5-b87e-cb0b1c1ed8c9/attachments/attachment.zip)

# 使用 GitHub Actions 和 Terragrunt 创建由 API 驱动的资源编排框架
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt"></a>

*Tamilselvan P、Abhigyan Dandriyal、Sandeep Gawande 和 Akash Kumar，Amazon Web Services*

## Summary
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-summary"></a>

这种模式利用 Ac GitHub tions 工作流程通过标准化的 JSON 负载自动配置资源，无需手动配置。这个自动化管道管理着完整的部署生命周期，并且可以与各种前端系统无缝集成，从自定义用户界面组件到 ServiceNow。该解决方案极具灵活性，允许用户通过其首选接口与系统进行交互，同时保持标准化流程。

为满足不同的组织要求，我们可以调整这个可配置的管道架构。示例实施侧重于 Amazon Virtual Private Cloud（Amazon VPC）和 Amazon Simple Storage Service（Amazon S3）预调配。此模式会对整个组织的请求进行标准化并提供一致的集成点，从而有效地应对常见的云资源管理挑战。利用这一方法，使团队可以更轻松地请求和管理资源，同时确保实现标准化。

## 先决条件和限制
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 有权访问已配置存储库的活跃 GitHub 账户

**限制**
+ 新资源需要手动将 `terragrunt.hcl` 文件添加到存储库配置中。
+ 有些 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="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-architecture"></a>

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

![\[使用 GitHub 操作和 Terraform 自动配置资源的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/bff5d70e-e8f1-454a-94bc-60e8cc16e69f/images/d4a768c8-4e11-493c-85ed-f4bf7e76ce60.png)


架构图显示了以下操作：

1. 用户向 GitHub 操作提交 JSON 有效负载，从而触发自动化管道。

1.  GitHub 操作管道根据有效载荷规格从 Terragrunt 和 Terraform 存储库中检索所需的资源代码。

1. 管道使用指定 AWS 账户 ID 担任相应的 AWS Identity and Access Management (IAM) 角色。然后，管道将资源部署到目标，并使用特定于账户的 Amazon S3 存储桶 AWS 账户 和 Amazon DynamoDB 表管理 Terraform 状态。

每个角色都 AWS 账户 包含用于安全访问的 IAM 角色、一个用于 Terraform 状态存储的 Amazon S3 存储桶和一个用于状态锁定的 DynamoDB 表。这种设计实现了跨 AWS 账户的受控自动化资源部署。部署过程通过每个账户中的专用 Amazon S3 存储桶和 IAM 角色保持适当的状态管理和访问控制。

## 工具
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-tools"></a>

**AWS 服务**
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一项完全托管式 NoSQL 数据库服务，可提供快速、可预测、可扩展的性能。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [Amazon Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。该虚拟网络类似于您在数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。

**其他工具**
+ GitHub A@@ [c](https://docs.github.com/en/actions) tions 是一个持续集成和持续交付 (CI/CD) 平台，与 GitHub 存储库紧密集成。您可以使用 GitHub Actions 来自动执行构建、测试和部署管道。
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。
+ [Terragrunt](https://terragrunt.gruntwork.io/docs/getting-started/overview/) 是一款编排工具，它扩展了 Terraform 和 OpenTofu Terraform 的功能。该工具可管理通用基础设施模式的应用方式，从而更轻松地扩展和维护大型基础设施资产。

**代码存储库**

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

## 最佳实践
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-best-practices"></a>
+ 使用存储 GitHub 库密钥存储 AWS 凭证和敏感数据，以实现安全访问。
+ 将 OpenID Connect (OIDC) 提供程序配置为 GitHub 操作代入 IAM 角色，避免使用静态证书。
+ 遵循最低权限原则，并授予执行任务所需的最低权限。有关详情，请参阅 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="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-epics"></a>

### 创建和配置存储库
<a name="create-and-configure-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 初始化 GitHub 存储库。 | 要初始化 GitHub 存储库，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 工程师 | 
| 配置 IAM 角色和权限。 | 要配置 IAM 角色和权限，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 工程师 | 
| 设置 GitHub 机密和变量。 | 有关如何在存储库中设置存储库密钥和变量的说明，请参阅 GitHub 文档中的[为仓库创建配置变量](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-variables#creating-configuration-variables-for-a-repository)。 GitHub 配置以下变量：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 工程师 | 
| 创建存储库结构。 | 要创建存储库结构，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 工程师 | 

### 触发管道并验证结果
<a name="trigger-the-pipeline-and-validate-results"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 curl 执行管道。 | 要使用 [curl](https://curl.se/) 执行管道，请执行以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html)有关管道执行流程的更多信息，请参阅[其他信息](#create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-additional)。 | DevOps 工程师 | 
| 验证管道执行的结果 | 要验证结果，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html)您还可以使用在存储库中创建的 `output.json` 文件来交叉验证已创建的资源，其中该文件与 `terragrunt.hcl` 文件位于同一资源内。 | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 提交清理请求。 | 要删除不再需要的资源，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 工程师 | 

## 相关资源
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-resources"></a>

**AWS 博客**
+ [使用 IAM 角色将 GitHub 操作与中的操作关联起来 AWS](https://aws.amazon.com/blogs/security/use-iam-roles-to-connect-github-actions-to-actions-in-aws/)

**AWS 服务 文档**
+ [IAM 角色创建](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create.html)
+ [使用 Amazon CloudTrail 日志监控 CloudWatch 日志文件](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/monitor-cloudtrail-log-files-with-cloudwatch-logs.html)
+ [Amazon S3 的安全最佳实践](https://docs.aws.amazon.com/AmazonS3/latest/userguide/security-best-practices.html)

**GitHub resources**
+ [创建存储库分派事件](https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#create-a-repository-dispatch-event)
+ [创建 web 挂钩](https://docs.github.com/en/webhooks/using-webhooks/creating-webhooks#payload)
+ [对 GitHub 存储库实施严格的访问控制](https://docs.github.com/en/get-started/learning-about-github/access-permissions-on-github)
+ [定期审计存储库访问权限](https://docs.github.com/en/organizations/keeping-your-organization-secure/managing-security-settings-for-your-organization)
+ [ CI/CD 正在进行安全检查](https://github.com/marketplace/actions/checkov-github-action)
+ [对账户使用多重身份验证 GitHub ](https://docs.github.com/en/authentication/securing-your-account-with-two-factor-authentication-2fa/configuring-two-factor-authentication)

## 附加信息
<a name="create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt-additional"></a>

**管道执行过程**

以下是管道执行的步骤：

1. **验证 JSON 有效载荷格式** - 确保传入的 JSON 配置结构正确且包含所有必需的参数

1. **担任指定的 IAM 角色**-进行身份验证并担任操作所需的 IAM 角色 AWS 

1. **下载所需的 Terraform 和 Terragrunt 代码** - 检索指定版本的资源代码和依赖项

1. **执行资源部署**-应用配置以在目标环境中部署或更新 AWS 资源

**用于 VPC 创建的示例有效载荷**

以下是创建 Terraform 后端状态存储桶的示例代码：

```
state_bucket_name = "${local.payload.ApplicationName}-${local.payload.EnvironmentId}-tfstate"
```

```
lock_table_name = "${local.payload.ApplicationName}-${local.payload.EnvironmentId}-tfstate-lock"
```

以下是使用 Amazon VPC 创建 VPC 的示例有效载荷，其中 `vpc_cidr` 定义了 VPC 的 [CIDR 数据块](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-cidr-blocks.html)规格。Terraform 状态存储桶映射到 `terraform` 文件中定义的变量。`ref` 参数包含要执行的代码的分支名称。

```
{
    "ref": "main",
    "inputs": {
        "RequestParameters": {
            "RequestId": "1111111",
            "RequestType": "create",
            "ResourceType": "vpc",
            "AccountId": "1234567890",
            "AccountAlias": "account-alias",
            "RegionId": "us-west-2",
            "ApplicationName": "myapp",
            "DivisionName": "division-name",
            "EnvironmentId": "dev",
            "Suffix": "poc"
        },
        "ResourceParameters": [
            {
                "VPC": {
                    "vpc_cidr": "10.0.0.0/16"
                }
            }
        ]
    }
}
```

`RequestParameters` 可用于跟踪管道部分中的请求状态，且 `tfstate` 基于此信息创建。以下参数包含元数据和控制信息：
+ `RequestId` - 请求的唯一标识符。
+ `RequestType` – 操作类型（创建、更新或删除）
+ `ResourceType`– 要预调配的资源类型
+ `AccountId`— AWS 账户 部署目标
+ `AccountAlias`— 的友好名字 AWS 账户
+ `RegionId`— AWS 区域 用于资源部署
+ `ApplicationName` – 应用程序的名称
+ `DivisionName`– 组织部门
+ `EnvironmentId` – 环境（例如，开发和生产）
+ `Suffix`– 资源的附加标识符

`ResourceParameters`包含特定于资源的配置，该配置映射到 Terraform 文件中定义的变量。任何需要传递给 Terraform 模块的自定义变量都应包含在中。`ResourceParameters`对于 Amazon VPC，参数 `vpc_cidr` 是强制的。

# 使用操作为 Terraform 托管的基础架构创建自动拉 AWS 取请求 GitHub
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure"></a>

*Matt Padgett、Ashish Bhatt、Ashwin Divakaran、Sandip Gangapadhyay 和 Prafful Gupta，Amazon Web Services*

## Summary
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-summary"></a>

此模式提供了一个自动化实用程序，旨在消除在管理跨多个 Terraform 存储库的更改时所涉及的手动重复工作。许多组织使用 Terraform 存储库来管理其基础设施即代码（IaC），通常有数百个独立存储库，分别代表不同的环境、服务或团队等待。大规模管理这些存储库是一项重大的运营挑战。诸如更新参数、升级模块版本或应用配置更改之类的例行任务通常需要每天在多个存储库中多次创建和管理拉取请求 (PRs)。

即使是简单的更改，这种重复的手动过程也非常耗时且容易出错。工程师必须始终在所有目标存储库中应用相同的更改，并制定有意义的公关标题和描述。此外，他们通常必须与 Jira 等外部工具交互才能获取或纳入问题跟踪参考。这些任务虽然必不可少，但却是无差别的繁重工作，会消耗宝贵的工程时间并降低整体效率。该工作流中缺乏自动化会造成摩擦，减慢交付速度，并增加负责维护大规模 Terraform 基础设施的团队的认知负担。

**解决方案概述**

为了应对这一挑战，此模式提供了一种完全由配置驱动的实用程序，从而允许用户在结构化配置文件中定义所需的更改。此文件使用明确定义的架构来指定目标存储库、模块、参数和值。

完成配置后，该实用程序将自动执行以下步骤：

1. **读取用户定义的配置**，确定更改的范围和性质

1. 在每个目标存储库中，**创建一个新分支**，并应用所需的更新

1. 为每次更改**生成 PR**，确保所有存储库之间的一致性

1. **发送 Slack 通知**（可选），提醒利益相关者直接链接到已创建的 PRs

通过自动执行这些重复性任务，该实用程序可显著减少与管理大规模基础设施更新相关的时间、精力和风险。这样一来，团队能够专注于更高价值的工程工作，同时有助于确保变更得到一致的应用并且可以在所有存储库中进行跟踪。

## 先决条件和限制
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ Python 版本 3.8 或更高版本。
+  GitHub 个人访问令牌 (PAT)。有关更多信息，请参阅 GitHub 文档中的[创建个人访问令牌（经典）](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-personal-access-token-classic)。
+  GitHub PAT 可以访问您的目标存储库，以便该实用程序可以执行诸如创建分支和拉取请求之类的操作。有关更多信息，请参阅此模式的 GitHub [代码存储库](https://github.com/aws-samples/sample-terraform-pr-automation-utility?tab=readme-ov-file#repository-access-verification)。

**限制**
+ **配置复杂性**是首要难题。自动化的有效性受其配置文件功能的限制。尽管该系统可以有效地处理标准更改，但复杂的基础设施修改可能需要手动干预，而且某些边缘情况仍不在自动处理的范围。
+ **安全和访问**是重要的考虑因素，尤其是在管理 GitHub 访问令牌和 API 速率限制时。Organizations 必须谨慎地在自动化需求与安全的凭证存储和管理之间取得平衡，确保适当的访问控制，同时保持运营效率。
+ **验证约束**形成了另一个明显的限制，因为自动化系统验证业务逻辑和特定环境要求的能力有限。复杂的依赖关系和跨服务交互通常需要人工监督，因为自动验证无法完全捕获所有上下文差异细节和业务规则。
+ 在处理大规模基础设施更改时，会出现**扩缩和性能**问题。系统必须在 GitHub API 限制内运行，同时管理多个存储库。在庞大的基础架构中进行资源密集型操作可能会造成性能瓶颈，因此需要精心谨慎地进行管理。
+ **集成边界**限制了系统的灵活性，因为它主要是为与特定工具（如 GitHub 和 Slack）配合使用而设计的。若组织使用不同的工具，则可能需要定制解决方案，不过此模式的工作流自定义选项仅限于支持的集成点。

## 架构
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-architecture"></a>

下图显示了此解决方案的工作流和组件。

![\[使用 GitHub 操作创建自动拉取请求的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e211359a-03b1-4e69-b152-eb7c09bdb01a/images/6cee0660-5b44-4abe-970c-c0a3c830a9aa.png)


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

1. 开发者通过指定 Terraform 存储库来触发 GitHub 操作。

1. 自动化实用程序读取定义的配置。

1. 自动化实用程序还会拉取提供的 Terraform 存储库。

1. 自动化实用程序会创建一个新分支并在本地更新 Terraform 模板。

1. 自动化实用程序将新分支推送到存储库并创建新 PR。

1. 自动化实用程序使用包含 PR 链接的 Slack 通知来通知开发人员，并启用 Terraform 模板进行部署。 AWS 云 

## 工具
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-tools"></a>
+ [GitHub](https://docs.github.com/)是一个开发者平台，开发人员可以使用它来创建、存储、管理和共享他们的代码。
+ GitHub A@@ [c](https://docs.github.com/en/actions) tions 是一个持续集成和持续交付 (CI/CD) 平台，与 GitHub 存储库紧密集成。您可以使用 GitHub Actions 来自动执行构建、测试和部署管道。
+ [HashiCorp Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具，可帮助您创建和管理云和本地资源。
+ Salesforce 推出的 [Slack](https://slack.com/help/articles/115004071768-What-is-Slack-) 是一款人工智能驱动的对话式平台，可提供聊天和视频协作，自动执行无代码流程，并支持信息共享。

**代码存储库**

此模式的代码可在使用 A [c GitHub tions 存储库的 GitHub 自动 Terraform 基础设施更新工作流程](https://github.com/aws-samples/sample-terraform-pr-automation-utility?tab=readme-ov-file)中找到。

## 最佳实践
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-best-practices"></a>
+ 有效的**更改管理**对于成功实施至关重要。对于大规模更改，组织应采用逐步推进策略。保持一致的分支命名惯例和 PR 描述，并确保对所有更改进行全面的记录。
+ 必须严格实施**安全控件**，重点是最低权限访问原则和安全的凭证管理。启用分支保护规则，以防止未经授权的更改。定期进行安全审计，以维护系统的完整性。
+ 强大的**测试协议**应包括在持续集成和持续部署（CI/CD）管道中自动`terraform plan`执行。该协议还应包括提交前的验证检查，以及针对关键更改的专属审查环境。这种多层测试方法即有助于尽早发现问题，又能确保基础设施的稳定性。
+ **监控策略**需要包括全面的警报机制、详细的 success/failure 指标跟踪以及针对失败操作的自动重试机制。该策略有助于确保运营可见性，并能够对出现的任何问题做出快速响应。
+ **配置标准**应强调所有配置的版本控制，保持模块化以实现可重用性和可扩展性。清晰的架构和示例文档有助于团队有效地了解和使用自动化系统。

## 操作说明
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-epics"></a>

### 安装和设置
<a name="installation-and-setup"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置存储库。 | 要设置存储库，请运行以下命令：<pre># Clone the automation tool repository<br />git clone https://github.com/aws-samples/sample-terraform-pr-automation-utility<br />cd sample-terraform-pr-automation-utility<br /><br /># Copy example configuration<br />cp config.example.yaml config.yaml<br /></pre> | AWS DevOps | 
| 安装依赖项。 | 要安装和验证 Python 依赖项，请运行以下命令：<pre># Install Python dependencies<br />pip3 install -r requirements.txt<br /><br /># Verify installation<br />python3 -c "import github; import hcl2; import yaml; import requests; print('All packages installed successfully')"<br /></pre> | AWS DevOps | 
| 配置令 GitHub 牌。 | 要配置 GitHub 令牌并验证其是否有效，请运行以下命令：<pre># Set GitHub token environment variable<br />export GITHUB_TOKEN="your_github_token_here"<br /><br /># Verify token works<br />curl -H "Authorization: token $GITHUB_TOKEN" https://api.github.com/user<br /></pre> | AWS DevOps | 

### 为 Terraform 更改设置配置文件
<a name="set-up-configuration-file-for-terraform-changes"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 `config.yaml` 文件 | 要定义目标存储库和所需的更改，请按照以下方式编辑 `config.yam`l 文件：<pre>repositories:<br />  - owner: "your-org"<br />    repo: "your-terraform-repo"<br />    files:<br />      - path: "variables.tf"<br />        changes:<br />          variables:<br />            - app_version:<br />                default:<br />                  update:<br />                    - from: ["1.0.0"]<br />                      to: "1.1.0"<br /><br />settings:<br />  pr_title_template: "Infrastructure Update - {{timestamp}}"<br />  slack:<br />    username: "Terraform Bot"<br />    icon_emoji: ":terraform:"<br />    notify_on_success: true<br />    notify_on_error: true<br />    notify_batch_summary: true<br /></pre> | AWS DevOps | 

### 测试和评估
<a name="test-and-validate"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 执行预检测试。 | 在生产存储库上运行配置之前，请务必先对其进行测试。使用以下命令：<pre># 1. Test configuration syntax<br />python3 -c "from main import get_config_content; get_config_content()"<br /><br /># 2. Run in dry-run mode first<br />DRY_RUN=true python3 main.py<br /><br /># 3. Test with minimal configuration<br /># Use a simple config.yaml with just one repository and one change</pre> | AWS DevOps | 
| 验证存储库访问权限。 | 要验证令 GitHub 牌是否可以访问存储库，请运行以下命令：<pre># Test GitHub token access<br />curl -H "Authorization: token $GITHUB_TOKEN" \<br />  https://api.github.com/repos/owner/repo-name<br /><br /># Should return repository information, not 404</pre> | AWS DevOps | 

### 运行自动化实用程序
<a name="run-the-automation-utility"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 GitHub 操作界面运行自动化实用程序。 | 要使用 GitHub 操作界面运行自动化实用程序，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-automated-pull-requests-for-terraform-managed-aws-infrastructure.html) | AWS DevOps | 
| （备选）从命令行运行自动化实用程序。 | 如果您愿意，可以从命令行运行自动化实用程序，而不必使用 GitHub 操作界面。使用以下命令：<pre># Run actual automation<br />python3 main.py</pre> | AWS DevOps | 

### 验证 PRs 和更改
<a name="validate-prs-and-changes"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看已创建 PRs 和更改。 | 要监控工作 GitHub 流程执行的结果，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-automated-pull-requests-for-terraform-managed-aws-infrastructure.html) | AWS DevOps | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| （可选）清理 PRs。 | 关闭已放弃或不必要 PRs。 | AWS DevOps | 

## 相关资源
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-resources"></a>

**AWS 规范性指导**
+ [使用 Terraform 作为 IaC 的工具 AWS 云](https://docs.aws.amazon.com/prescriptive-guidance/latest/choose-iac-tool/terraform.html)

**GitHub 文档**
+ [关于拉取请求](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests)
+ [管理您的个人访问令牌](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens)
+ [了解 GitHub 动作](https://docs.github.com/en/actions/get-started/understand-github-actions)
+ [操作快速入 GitHub 门](https://docs.github.com/en/actions/get-started/quickstart)

# 自动为 Java 和 Python 项目创建动态 CI 管道
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically"></a>

*Aromal Raj Jayarajan、Vijesh Vijayakumaran Nair、MAHESH RAGHUNANDANAN 和 Amarnath Reddy，Amazon Web Services*

## Summary
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-summary"></a>

此模式说明如何使用 AWS 开发人员工具自动为 Java 和 Python 项目创建动态持续集成（CI）管道。

随着技术堆栈的多样化和开发活动的增加，创建和维护在整个组织中保持一致的 CI 管道可能会变得困难。通过在 AWS Step Functions 中自动执行该流程，您可以确保 CI 管道的使用和方法保持一致。

为了自动创建动态 CI 管道，此模式使用以下变量输入：
+ 编程语言（仅限 Java 或 Python）
+ 管道名称
+ 所需管道阶段

**注意**  
Step Functions 使用多个 AWS 服务编排管道创建。有关此解决方案中使用的 Amazon Web Services 的更多信息，请参阅此模式的**工具**部分。

## 先决条件和限制
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 部署此解决方案的同一 AWS 区域 中的 Amazon S3 存储桶
+ 一个 AWS Identity and Access Management (IAM) [委托人](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html)，拥有创建此解决方案所需资源所需的 AWS CloudFormation 权限

**限制**
+ 此模式仅支持 Java 和 Python 项目。
+ 在此模式中预置的 IAM 角色遵循最低权限原则。必须根据您的 CI 管道需要创建的特定资源更新 IAM 角色的权限。

## 架构
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-architecture"></a>

**目标技术堆栈**
+ AWS CloudFormation
+ AWS CodeBuild
+ AWS CodeCommit
+ AWS CodePipeline
+ IAM
+ Amazon Simple Storage Service（Amazon S3）
+ AWS Systems Manager
+ AWS Step Functions
+ AWS Lambda
+ Amazon DynamoDB

**目标架构**

下图显示了使用 AWS 开发人员工具自动为 Java 和 Python 项目创建动态 CI 管道的示例工作流程。

![\[使用 AWS 工具自动为 Java 和 Python 项目创建动态 CI 管道的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/bef2ccb8-68b3-4c0f-9ee7-4b93e9422d9c/images/b5ed003f-cf16-4130-8bfb-2bc2cb9a0d33.png)


下图显示了如下工作流：

1. AWS 用户以 JSON 格式提供用于创建 CI 管道的输入参数。此输入将启动一个 Step Functions 工作流（*状态机*），该工作流使用 AWS 开发人员工具创建 CI 管道。

1. Lambda 函数读取名为 **input-reference** 的文件夹，该文件夹存储在 Amazon S3 存储桶中，然后生成 **buildspec.yml** 文件。此生成的文件定义了 CI 管道阶段，并存储回存储参数引用的同一 Amazon S3 存储桶中。

1. Step Functions 会检查 CI 管道创建工作流程的依赖关系是否存在任何更改，并根据需要更新依赖关系堆栈。

1. Step Functions 在 CloudFormation 堆栈中创建 CI 管道资源，包括 CodeCommit 存储库、 CodeBuild 项目和 CodePipeline 管道。

1.  CloudFormation 堆栈将所选技术堆栈（Java 或 Python）的示例源代码和 **buildspec.yml** 文件复制到存储库。 CodeCommit 

1. CI 管道运行时详细信息存储在 DynamoDB 表中。

**自动化和扩缩**
+ 此模式仅供在单个开发环境中使用。需要更改配置才能跨多个开发环境使用。
+ 要添加对多个 CloudFormation 堆栈的支持，您可以创建其他 CloudFormation 模板。有关更多信息，请参阅 CloudFormation 文档 CloudFormation中的 [AWS 入门](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/GettingStarted.html)。

## 工具
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-tools"></a>

**工具**
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一项无服务器编排服务，可让您搭配使用 AWS Lambda 函数和其他 Amazon Web Services 来构建业务关键型应用程序。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，而无需预置或管理服务器。它仅在需要时运行您的代码，并且能自动扩缩，因此您只需为使用的计算时间付费。
+ [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) 可帮助您快速建模和配置软件发布的不同阶段，并自动执行持续发布软件变更所需的步骤。
+ [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) 可帮助您创建和控制加密密钥，以帮助保护您的数据。
+ [Amazon Simple Storage Service(Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可帮助您设置 AWS 资源，快速一致地配置这些资源，并在 AWS 账户和区域的整个生命周期中对其进行管理。
+ [Amazon DynamoDB](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Introduction.html) 是一项完全托管式 NoSQL 数据库服务，可提供快速、可预测、可扩展的性能。
+ [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) 提供安全的分层存储，用于配置数据管理和密钥管理。

**代码**

此模式的代码可在 GitHub [automated-ci-pipeline-creation](https://github.com/aws-samples/automated-ci-pipeline-creation)存储库中找到。存储库包含创建此模式中概述的目标架构所需的 CloudFormation 模板。

## 最佳实践
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-best-practices"></a>
+ 请勿在 CloudFormation 模板或 Step Functions 操作配置中直接输入令牌或密码等凭据（*机密*）。如果这样做，该信息将显示在 DynamoDB 日志中。相反，请使用 AWS Secrets Manager 来设置和存储密钥。然后，根据需要在 CloudFormation 模板和 Step Functions 操作配置中引用 Secrets Manager 中存储的密钥。有关更多信息，请参阅 Secrets Manager 文档中的[什么是 AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html)。
+ 为存储在 Amazon S3 中的 CodePipeline 项目配置服务器端加密。有关更多信息，请参阅 CodePipeline 文档中的[为存储在 Amazon S3 中的项目配置服务器端加密](https://docs.aws.amazon.com/codepipeline/latest/userguide/S3-artifact-encryption.html)。 CodePipeline
+ 在配置 IAM 角色时应用最低权限。有关更多信息，请参阅 IAM 文档中的[应用最低权限许可](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)。
+ 确保您的 Amazon S3 存储桶不可公开访问。有关更多信息，请参阅 [Amazon S3 文档中的为您的 S3 存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/configuring-block-public-access-bucket.html)配置阻止公有访问设置。
+ 确保您为 Amazon S3 存储桶激活版本控制。有关更多信息，请参阅 Amazon S3 文档中的[在 S3 存储桶中使用版本控制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html)。
+ 配置 IAM policy 时使用 IAM Access Analyzer。该工具提供可操作的建议，以帮助您编写安全且实用的 IAM policy。有关更多信息，请参阅 IAM 文档中的[使用 AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html)。
+ 如果可能，请在配置 IAM policy 时定义特定的访问条件。
+ 激活 Amazon CloudWatch 日志以进行监控和审计。有关更多信息，请参阅[什么是 Amazon CloudWatch 日志？](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) 在 CloudWatch 文档中。

## 操作说明
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-epics"></a>

### 配置先决条件
<a name="configure-the-prerequisites"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon S3 存储桶。 | 创建 Amazon S3 存储桶（或使用现有存储桶）来存储解决方案所需的 CloudFormation 模板、源代码和输入文件。有关更多信息，请参阅 [Amazon S3 文档中的步骤 1](https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-bucket.html)：创建您的第一个 S3 存储桶。Amazon S3 存储桶必须位于您要将解决方案部署到的同一 AWS 区域中。 | AWS DevOps | 
| 克隆 GitHub 存储库。 | 在终端窗口中运行以下命令来克隆 GitHub [automated-ci-pipeline-creation](https://github.com/aws-samples/automated-ci-pipeline-creation)存储库：<pre>git clone https://github.com/aws-samples/automated-ci-pipeline-creation.git</pre>有关更多信息，请参阅 GitHub 文档[中的克隆存储库](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository)。 | AWS DevOps | 
| 将解决方案模板文件夹从克隆的 GitHub 存储库上传到您的 Amazon S3 存储桶。 | 复制克隆的 **Solution-Templates** 文件夹中的内容，并将其上传到您创建的 Amazon S3 存储桶中。有关更多信息，请参阅 Amazon S3 文档中的[上传数据](https://docs.aws.amazon.com/AmazonS3/latest/userguide/upload-objects.html)。请确认仅上传 **Solution-Templates** 文件夹的内容。您只能在 Amazon S3 存储桶的根级别上传文件。 | AWS DevOps | 

### 部署解决方案
<a name="deploy-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用克隆存储库中的 template.yml 文件创建 CloudFormation 堆栈来部署解决方案。 GitHub  | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html)您在创建堆栈时，该堆栈会在**堆栈**页面列出，其状态为 **CREATE\$1IN\$1PROGRESS**。请确保等待堆栈的状态更改为 **CREATE\$1COMPLETE**，然后再完成此模式中的其余步骤。 | AWS 管理员，AWS DevOps | 

### 测试设置
<a name="test-the-setup"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 运行您创建的步骤函数。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html)**JSON 格式**<pre>{<br />  "details": {<br />    "tech_stack": "Name of the Tech Stack (python/java)",<br />    "project_name": "Name of the Project that you want to create with",<br />    "pre_build": "Choose the step if it required in the buildspec.yml file i.e., yes/no",<br />    "build": "Choose the step if it required in the buildspec.yml file i.e., yes/no",<br />    "post_build": "Choose the step if it required in the buildspec.yml file i.e., yes/no",<br />    "reports": "Choose the step if it required in the buildspec.yml file i.e., yes/no",<br />  }<br />}</pre>**Java JSON 输入示例**<pre>{<br />  "details": {<br />    "tech_stack": "java",<br />    "project_name": "pipeline-java-pjt",<br />    "pre_build": "yes",<br />    "build": "yes",<br />    "post_build": "yes",<br />    "reports": "yes"<br />  }<br />}</pre>**Python JSON 输入示例**<pre>{<br />  "details": {<br />    "tech_stack": "python",<br />    "project_name": "pipeline-python-pjt",<br />    "pre_build": "yes",<br />    "build": "yes",<br />    "post_build": "yes",<br />    "reports": "yes"<br />  }<br />}</pre> | AWS 管理员，AWS DevOps | 
| 确认 CI 管道的 CodeCommit 存储库已创建。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html) | AWS DevOps | 
| 检查 CodeBuild 项目资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html) | AWS DevOps | 
| 验证 CodePipeline 阶段。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html) | AWS DevOps | 
| 确认 CI 管道已成功运行。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html) | AWS DevOps | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除中的资源堆栈 CloudFormation。 | 在中删除 CI 管道的资源堆栈 CloudFormation。有关更多信息，请参阅 CloudFormation 文档中的在 [AWS CloudFormation 控制台上删除堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html)。请确认删除名为 **<project\$1name>-stack** 的堆栈。 | AWS DevOps | 
| 在 Amazon S3 中删除 CI 管道的依赖关系，然后 CloudFormation。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html)确保删除名为的堆栈**pipeline-creation-dependencies-stack**。 | AWS DevOps | 
| 删除 Amazon S3 模版存储桶。 | 删除您在此模式的**配置先决条件**部分中创建的 Amazon s3 存储桶，该存储桶存储此解决方案的模板。有关更多信息，请参阅 Amazon S3 文档中的[删除存储桶](https://docs.aws.amazon.com/AmazonS3/latest/userguide/delete-bucket.html)。 | AWS DevOps | 

## 相关资源
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-resources"></a>
+ [创建使用 Lambda 的 Step Functions 状态机](https://docs.aws.amazon.com/step-functions/latest/dg/tutorial-creating-lambda-state-machine.html)（AWS Step Functions 文档）
+ [AWS Step Funct WorkFlow ions 工作室](https://docs.aws.amazon.com/step-functions/latest/dg/workflow-studio.html)（AWS Step Functions 文档）
+ [DevOps 还有 AWS](https://aws.amazon.com/devops/)
+ [AWS 是如何 CloudFormation 运作的？](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-whatis-howdoesitwork.html) （AWS CloudFormation 文档）
+ [包含 CI/CD AWS CodeCommit、AWS CodeBuild CodeDeploy、AWS 和 AWS CodePipeline](https://aws.amazon.com/blogs/devops/complete-ci-cd-with-aws-codecommit-aws-codebuild-aws-codedeploy-and-aws-codepipeline/)（AWS 博客文章）
+ [IAM 和 AWS STS 配额、名称要求和字符限制](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-quotas.html)（IAM 文档）

# 使用 Terraf CloudWatch orm 部署 Synthetics 加那利群岛
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform"></a>

*Dhrubajyoti Mukherjee 和 Jean-Francois Landreau，Amazon Web Services*

## Summary
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-summary"></a>

重要的是要从客户的角度验证系统的运行状况，并确认客户能够连接。当客户不经常调用端点时，这就更加困难了。[Amaz CloudWatch on Synthetics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html) 支持创建加那利群岛，它可以测试公共和私有终端节点。通过使用金丝雀，即使系统未在使用中，您也可以知道该系统的状态。这些金丝雀要么是 Node.js Puppeteer 脚本，要么是 Python Selenium 脚本。

此模式描述了如何使用 HashiCorp Terraform 部署用于测试私有端点的金丝雀。它嵌入了一个用于测试 URL 是否返回 `200-OK` 的 Puppeteer 脚本。然后，可以将 Terraform 脚本与部署私有端点的脚本集成。您也可以修改解决方案以监控公有端点。

## 先决条件和限制
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-prereqs"></a>

**先决条件**
+ 具有虚拟私有云（VPC）和私有子网的有效 Amazon Web Services（AWS）账户
+ 可从私有子网访问的端点的 URL
+ 部署环境中安装了 Terraform

**限制**

当前的解决方案适用于以下 S CloudWatch ynthetics 运行时版本：
+ syn-nodejs-puppeteer-3.4
+ syn-nodejs-puppeteer-3.5
+ syn-nodejs-puppeteer-3.6
+ syn-nodejs-puppeteer-3.7

随着新的运行时系统版本的发布，您可能需要更新当前解决方案。您还需要修改解决方案以跟上安全更新的步伐。

**产品版本**
+ Terraform 1.3.0

## 架构
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-architecture"></a>

Amaz CloudWatch on Synthetics 以 CloudWatch Lambda 和亚马逊简单存储服务 (Amazon S3) 为基础。亚马逊 CloudWatch 提供了一个用于创建加那利群岛的向导和一个显示金丝雀运行状态的控制面板。Lambda 函数运行脚本。Amazon S3 存储了金丝雀运行的日志和屏幕截图。

此模式通过部署在目标子网中的亚马逊弹性计算云 (Amazon EC2) 实例模拟私有终端节点。Lambda 函数需要在部署私有端点的 VPC 中使用弹性网络接口。

![\[描述如图所示。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/73ed0103-ec45-4653-bb29-f402a88f0c64/images/39aaed0f-f259-4f2a-98fb-8e3a340d0b02.png)


此图显示以下内容：

1. Synthetics 金丝雀启动金丝雀 Lambda 函数。

1. 金丝雀 Lambda 函数连接到弹性网络接口。

1. 金丝雀 Lambda 函数监控端点的状态。

1. Synthetics 金丝雀将运行数据推送到 S3 存储桶和 CloudWatch 指标。

1. 根据指标启动 CloudWatch 警报。

1.  CloudWatch 警报会启动亚马逊简单通知服务 (Amazon SNS) Simple Notification Service 主题。

## 工具
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-tools"></a>

**AWS 服务**
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可帮助您实时监控您的 AWS 资源和在 AWS 上运行的应用程序的指标。
+ [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 服务器和电子邮件地址）之间的消息交换。
+ [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 可扩展基础设施的优势。此模式使用 VPC 端点和弹性网络接口。

**其他服务**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一种开源基础设施即代码 (IaC) 工具，可帮助您使用代码来配置和管理云基础架构和资源。这种模式使用 Terraform 来部署基础设施。
+ [Puppeteer](https://pptr.dev/) 是一个 Node.js 库。Synt CloudWatch hetics 运行时使用 Puppeteer 框架。

**代码**

该解决方案可在 GitHub [云 watch-synthetics-canary-terraform](https://github.com/aws-samples/cloudwatch-synthetics-canary-terraform)存储库中找到。有关更多信息，请参阅*其他信息*部分。

## 操作说明
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-epics"></a>

### 实施监控私有 URL 的解决方案
<a name="implement-the-solution-for-monitoring-a-private-url"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 收集监控私有 URL 的要求。 | 收集完整的 URL 定义：域名、参数和标头。要与 Amazon S3 和亚马逊进行私密通信 CloudWatch，请使用 VPC 终端节点。请注意端点如何访问 VPC 和子网。考虑一下金丝雀运行的频率。 | 云架构师、网络管理员 | 
| 修改现有解决方案以监控私有 URL。 | 修改 `terraform.tfvars` 文件：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-cloudwatch-synthetics-canaries-by-using-terraform.html) | 云架构师 | 
| 部署和操作解决方案。 | 要部署该解决方案，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-cloudwatch-synthetics-canaries-by-using-terraform.html) | 云架构师、 DevOps 工程师 | 

## 问题排查
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 删除预调配的资源会导致卡顿。 | 按顺序手动删除金丝雀 Lambda 函数、相应的弹性网络接口和安全组。 | 

## 相关资源
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-resources"></a>
+ [使用 Synthetics 监控](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)
+ 使用 [Amazon S CloudWatch ynthetics 监控 API Gateway 终端节点](https://aws.amazon.com/blogs/mt/monitor-api-gateway-endpoints-with-amazon-cloudwatch-synthetics/)（博客文章）

## 附加信息
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-additional"></a>

**存储库构件**

存储库构件采用如下结构。

```
.
├── README.md
├── main.tf
├── modules
│   ├── canary
│   └── canary-infra
├── terraform.tfvars
├── tf.plan
└── variable.tf
```

该 `main.tf` 文件包含核心模块，它部署了两个子模块：
+ `canary-infra` 部署了金丝雀所需基础设施。
+ `canary` 部署了金丝雀。

解决方案的输入参数位于 `terraform.tfvars` 文件中。您可以使用以下代码示例创建一个金丝雀。

```
module "canary" {
    source = "./modules/canary"
    name   = var.name
    runtime_version = var.runtime_version
    take_screenshot = var.take_screenshot
    api_hostname = var.api_hostname
    api_path = var.api_path
    reports-bucket = module.canary_infra.reports-bucket
    role = module.canary_infra.role
    security_group_id = module.canary_infra.security_group_id
    subnet_ids = var.subnet_ids
    frequency = var.frequency
    alert_sns_topic = var.alert_sns_topic
}
```

相应的 .var 文件如下。

```
name   = "my-canary"
runtime_version = "syn-nodejs-puppeteer-3.7"
take_screenshot = false
api_hostname = "mydomain.internal"
api_path = "/path?param=value"
vpc_id = "vpc_id"
subnet_ids = ["subnet_id1"]
frequency = 5
alert_sns_topic = "arn:aws:sns:eu-central-1:111111111111:yyyyy"
```

**清理解决方案**

如果您在开发环境中对此进行测试，则可以清理解决方案以避免累积成本。

1. 在 AWS 管理控制台 上，导航到 Amazon S3 控制台。清空解决方案创建的 Amazon S3 存储桶。如果需要，请务必备份数据。

1. 在开发环境中，从 `cloudwatch-synthetics-canary-terraform` 目录中运行该 `destroy` 命令。

   ```
   terraform destroy
   ```

# 部署 ChatOps 解决方案来管理 SAST 扫描结果，方法是在聊天应用程序中使用 Amazon Q Developer 自定义操作和 CloudFormation
<a name="deploy-chatops-solution-to-manage-sast-scan-results"></a>

*Anand Bukkapatnam Tirumala，Amazon Web Services*

## Summary
<a name="deploy-chatops-solution-to-manage-sast-scan-results-summary"></a>

这种模式提供了一个全面的解决方案，它在聊天应用程序中使用 Amazon Q Developer 来简化对报告的静态应用程序安全测试 (SAST) 扫描失败的 SonarQube管理。这种创新的方法将自定义操作和通知集成到一个对话界面中，从而在开发团队内部实现高效的协作和决策流程。

在当今快节奏的软件开发环境中，高效管理 SAST 扫描结果对于保持代码质量和安全性至关重要。但是，许多组织面临着以下重大挑战：
+ 由于通知系统效率低下，对关键漏洞的感知有所延迟
+ 审批工作脱节导致决策过程缓慢
+ 无法对 SAST 扫描失败做出即时、可行的响应
+ 围绕安全调查发现的沟通和协作断断续续
+ 为安全工具手动设置基础设施既耗时又容易出错

这些问题通常会导致安全风险增加、发布延迟和团队工作效率降低。为了有效地应对这些挑战，需要一种能够简化 SAST 结果管理、增强团队协作和自动执行基础设施预调配的解决方案。

该解决方案的主要特征包括：
+ **自定义通知** – 实时提醒和通知直接发送到团队聊天频道，确保及时了解 SAST 扫描漏洞或失败并对此采取措施。
+ **对话式审批** – 利益攸关方可以在聊天界面中无缝启动和完成 SAST 扫描结果的审批工作流，从而加速决策过程。
+ **自定义操作** – 团队可以根据 SAST 扫描结果定义和执行自定义操作，例如在质量门失败时自动触发电子邮件，从而增强对安全问题的响应能力。
+ **集中式协作** – 所有与 SAST 扫描相关的讨论、决策和操作都在统一的聊天环境中进行，从而促进团队成员之间的协作和知识共享。
+ **基础设施即代码 (IaC)** — 整个解决方案采用 AWS CloudFormation 模板封装，可实现更快、更可靠的基础架构配置，同时减少手动设置错误。

## 先决条件和限制
<a name="deploy-chatops-solution-to-manage-sast-scan-results-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ 一个 AWS Identity and Access Management (IAM) 角色，有权创建和管理与[工具](#deploy-chatops-solution-to-manage-sast-scan-results-tools)中 AWS 服务 列出的资源相关联的资源。
+ 一个 Slack 工作区。
+ 聊天应用程序中的 Amazon Q 开发者版已作为插件添加到所需的 Slack 工作区。有关更多信息，请参阅 Slack 文档中的[将应用程序添加到 Slack 工作区](https://slack.com/intl/en-in/help/articles/202035138-Add-apps-to-your-Slack-workspace)。请记下成功注册 AWS 管理控制台 后的 Slack 工作区 ID，如图所示。
+ 聊天应用程序客户端中配置的 Amazon Q Developer，工作区 ID 随时可供在 CloudFormation 控制台中输入。有关说明，请参阅《*聊天应用程序中的 Amazon Q 开发者版管理员指南*》中的[配置 Slack 客户端](https://docs.aws.amazon.com/chatbot/latest/adminguide/slack-setup.html#slack-client-setup)。
+ 在 Amazon Simple Email Service（Amazon SES）中创建并验证的源电子邮件账户，用于发送审批电子邮件。有关设置说明，请参阅 *Amazon Simple Email Service 开发人员指南*中的[创建和验证电子邮件身份](https://docs.aws.amazon.com/ses/latest/dg/creating-identities.html#verify-email-addresses-procedure)。
+ 用于接收审批通知的目标电子邮件地址。此地址可以是共享收件箱，也可以是特定团队分发列表。
+ 可从您的访问的操作 SonarQube 实例 AWS 账户。有关更多信息，请参阅[SonarQube 安装说明](https://docs.sonarsource.com/sonarqube/latest/setup-and-upgrade/install-the-server/introduction/)。
+ 一种 SonarQube[用户令牌](https://docs.sonarsource.com/sonarqube-server/latest/user-guide/managing-tokens/)，具有通过管道触发和创建项目的权限。

**限制**
+ 在此解决方案中，创建自定义操作按钮是一个手动过程。
+ 有些 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-chatops-solution-to-manage-sast-scan-results-architecture"></a>

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

![\[使用 Amazon Q 开发者版为发布管理部署自动代码质量保证的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/198312ed-e379-49a7-b706-8e79e2142f21/images/a977924c-957e-4f91-99d6-ed790e343ea6.png)


此图显示了自动代码质量保证工作流：

1. 代码准备和上传：
   + 开发人员将代码库压缩为 .zip 文件。
   + 开发人员将该 .zip 文件手动上传到指定的 Amazon Simple Storage Service（Amazon S3）存储桶。

1. Amazon S3 事件触发器和 AWS Step Functions 编排：
   + Amazon S3 上传事件触发 Step Functions 工作流。
   + Step Functions 使用编排 SAST 扫描。 SonarQube
   + 该工作流会监控 AWS CodeBuild 作业状态以确定后续操作。如果 CodeBuild 成功（质量门通过），则工作流程终止。如果 CodeBuild 失败，则调用 AWS Lambda 函数进行诊断。有关更多详细信息，请参阅本部分后面的 **AWS Step Functions 逻辑**。

1. AWS CodeBuild 处决：
   + 该 CodeBuild 作业对上传的代码库执行 SonarQube 扫描。
   + 扫描构件存储在单独的 Amazon S3 存储桶中，以供审计和分析之用。

1. 失效分析（Lambda 函数）：
   +  CodeBuild 失败时，会触发 `CheckBuildStatus` Lambda 函数。
   +  CodeBuild 成功后，该过程即告终止，无需采取进一步行动。

1. Lambda 函数分析失效原因（质量门失败或其他问题）
   + `CheckBuildStatus` 函数创建包含详细失效信息的自定义有效载荷。
   + `CheckBuildStatus` 函数将自定义有效载荷发布到 Amazon Simple Notification Service（Amazon SNS）主题。

1. 通知系统：
   + Amazon SNS 将有效载荷转发给聊天应用程序中的 Amazon Q 开发者版，以实现 Slack 集成。

1. Slack 集成：
   + 聊天应用程序中的 Amazon Q 开发者版在指定的 Slack 频道中发布通知。

1. 审批流程：
   + 审批者会在 Slack 通知中查看失败详细信息。
   + 审批者可以使用 Slack 中的**审批**按钮启动审批。

1. 审批处理程序：
   + 审批 Lambda 函数可处理来自 Slack 的审批操作。
   + 审批函数会将自定义消息发布到 Amazon SES。

1. 消息已生成：
   + 审批函数会生成一条用于通知开发人员的自定义消息。

1. 开发人员通知：
   + Amazon SES 会向开发人员发送一封包含后续步骤或所需操作的电子邮件。

该工作流结合了手动代码上传与自动质量检查，通过 Slack 提供即时反馈，并在必要时允许人工干预，从而确保稳健而灵活的代码审查流程。

**AWS Step Functions  ** 逻辑

如前面的架构图所示，如果质量门 SonarQube 失败，则工作流程将转到 `CheckBuildStatus` Lambda 函数。`CheckBuildStatus` 函数会在 Slack 频道上触发通知。每个通知都包含有关建议的后续步骤的信息。以下是通知类型：
+ **应用程序在代码安全扫描中失败** — 当上传的代码未通过 SonarQube 安全扫描时，用户会收到此通知。用户可以选择**审批**来接受构建。但是，该通知建议用户注意代码质量可能不佳和安全风险等情况。这些通知包含以下详细信息：
  + 后续步骤：错误：质量门状态：失败 – 通过提供的 URL 查看详细信息。
  + 按照提供的 URL 上的文档所述对漏洞进行分类。
  + CodeBuild 有关详细信息，请访问所提供的 URL。
+ **应用程序扫描管道因某些其他原因而失败** – 当管道因代码安全扫描失败以外的其他原因而失败时，用户会收到此通知。这些通知包含以下详细信息：
  + 有关后续步骤，请转到提供的链接，以进一步排查问题。

要查看通知在 Slack 频道中显示的屏幕截图，请前往 GitHub chatops-slack [存储库中的资产文件夹](https://github.com/aws-samples/chatops-slack/tree/main/assets)。

下图显示了未通过质量门检查后 Step Functions 步骤状态的示例。

![\[未通过质量门检查后 AWS Step Functions 步骤状态的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/198312ed-e379-49a7-b706-8e79e2142f21/images/40b7ebf0-2518-4413-9717-0bfb7559adde.png)


## 工具
<a name="deploy-chatops-solution-to-manage-sast-scan-results-tools"></a>

**AWS 服务**
+ [聊天应用程序中的 Amazon Q](https://docs.aws.amazon.com/chatbot/latest/adminguide/what-is.html) Developer 使您能够使用 Amazon Chime、Microsoft Teams 和 Slack 聊天频道来监控和响应应用程序中的操作事件。 AWS *终止支持通知：* AWS 将于 2026 年 2 月 20 日终止对 Amazon Chime 服务的支持。2026 年 2 月 20 日之后，您将无法再访问 Amazon Chime 控制台或 Amazon Chime 应用程序资源。有关更多信息，请访问该[博客文章](https://aws.amazon.com/blogs/messaging-and-targeting/update-on-support-for-amazon-chime/)。这不会影响 [Amazon Chime SDK](https://aws.amazon.com/chime/chime-sdk/) 服务的可用性。
+ [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) 是一项完全托管式构建服务，可编译源代码、运行单元测试和生成部署就绪的构件。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 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 Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) 可帮助您将代码中的硬编码凭证（包括密码）替换为对 Secrets Manager 进行的 API 调用，以便以编程方式检索此密钥。
+ [Amazon Simple Email Service（Amazon SES）](https://docs.aws.amazon.com/ses/latest/dg/Welcome.html)可帮助您通过使用您自己的电子邮件地址和域发送和接收电子邮件。
+ [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 Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html)是一项无服务器编排服务，可帮助您组合 AWS Lambda 功能和其他功能 AWS 服务 来构建关键业务应用程序。

**其他工具**
+ Salesforce 推出的 [Slack](https://slack.com/help/articles/115004071768-What-is-Slack-) 是一款人工智能驱动的对话式平台，可提供聊天和视频协作，自动执行无代码流程，并支持信息共享。
+ [SonarQube](https://docs.sonarsource.com/sonarqube/latest/user-guide/user-account/generating-and-using-tokens/)是一款本地分析工具，旨在检测 30 多种语言、框架和 IaC 平台中的编码问题。

**代码存储库**

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

## 最佳实践
<a name="deploy-chatops-solution-to-manage-sast-scan-results-best-practices"></a>
+ **CloudFormation 堆栈管理**-如果您在 CloudFormation 堆栈执行过程中遇到任何故障，我们建议您删除失败的堆栈。然后，使用正确的参数值重新创建。这种方法支持干净利落的部署，并且有助于避免潜在的冲突或部分实施。
+ **共享收件箱电子邮件配置** – 配置 `SharedInboxEmail` 参数时，请使用所有相关开发人员都可以访问的通用分发列表。这种方法提高了透明度，并且有助于将重要的通知传达给相关的团队成员。
+ **生产审批工作流** – 对于生产环境，限制对用于构建审批的 Slack 频道的访问权限。只有指定的审批者才能成为该频道的成员。这种做法可以维持清晰明确的责任链，并通过限制可审批关键更改的人员来增强安全性。
+ **IAM 权限** – 遵循最低权限原则，并授予执行任务所需的最低权限。有关详情，请参阅 IAM 文档中的[授予最低权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv)和[安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPracticesAndUseCases.html)。

## 操作说明
<a name="deploy-chatops-solution-to-manage-sast-scan-results-epics"></a>

### 执行初始设置
<a name="perform-initial-setup"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要克隆此模式的 [chatops-slack](https://github.com/aws-samples/chatops-slack) 存储库，请使用以下命令。`git clone "git@github.com:aws-samples/chatops-slack.git"` | AWS DevOps、构建主管、 DevOps 工程师、云管理员 | 
| 创建包含 Lambda 代码的 .zip 文件。 | 为和`ApprovalEmail`功能的 AWS Lambda 函数代码创建.zip 文件。`CheckBuildStatus`要创建 `notification.zip` 和 `approval.zip`，请使用以下命令。<pre>cd chatops-slack/src</pre><pre>chmod -R 775 *</pre><pre>zip -r approval.zip approval</pre><pre>zip -r notification.zip notification</pre> | AWS DevOps、构建主管、 DevOps 工程师、云管理员 | 

### 部署 pre-requisite.yml 堆栈文件
<a name="deploy-the-pre-requisite-yml-stack-file"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 执行 `pre-requisite.yml` 堆栈文件。 | `pre-requisite.yml` CloudFormation 堆栈文件会部署在您执行堆`app-security.yml`栈文件之前所需的初始资源。要执行 `pre-requisite.yml` 文件，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html) | AWS 管理员、AWS DevOps、构建主管、 DevOps 工程师 | 
| 将 .zip 文件上传到 Amazon S3 存储桶中。 | 将之前创建的 `notification.zip` 和 `approval.zip` 文件上传到名为 `S3LambdaBucket` 的 Amazon S3 存储桶。`app-security.yml` CloudFormation 堆栈文件用于`S3LambdaBucket`配置 Lambda 函数。 | AWS DevOps，构建主管， DevOps 工程师，AWS 系统管理员 | 

### 执行 app-security.yml 堆栈文件
<a name="execute-the-app-security-yml-stack-file"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 执行 `app-security.yml` 堆栈文件。 | `app-security.yml` 堆栈文件可为通知和审批系统部署剩余的基础设施。要执行 `app-security.yml` 文件，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html) | AWS DevOps、AWS 系统管理员、 DevOps 工程师、构建主管 | 
| 测试通知设置。 | 要测试通知设置，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html)成功送达测试消息后，您应该会在 Slack 频道上看到一条通知。有关更多信息，请参阅《*Amazon Q 开发者聊天应用程序管理员指南*》中的 “[测试从 AWS 服务 Slack 发送的通知](https://docs.aws.amazon.com/chatbot/latest/adminguide/slack-setup.html#test-notifications-slack)”。 | AWS DevOps、AWS 系统管理员、 DevOps 工程师、构建主管 | 

### 设置审批流程
<a name="set-up-approval-flow"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置自定义 Lambda 操作。 | 要设置自定义 AWS Lambda 操作，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html) | AWS 管理员、AWS DevOps、构建主管、 DevOps 工程师、Slack 管理员 | 
| 验证审批流程。 | 要验证审批流程是否按预期运行，请在 Slack 中选择**审批**按钮。Slackbot 应在消息会话中发送一条通知，其中包含确认字符串**审批电子邮件已成功发送**。 | AWS 管理员、AWS DevOps、 DevOps 工程师、Slack 管理员 | 

## 问题排查
<a name="deploy-chatops-solution-to-manage-sast-scan-results-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| Slack 配置错误 | 有关对与 Slack 配置错误相关的问题进行故障排除的信息，请参阅《*聊天应用程序中的 Amazon Q 开发者版管理员指南*》中的 Amazon Q 开发者版问题排查。 | 
| 扫描因某些其他原因而失败 | 此错误表示代码构建任务已失败。要对问题进行故障排除，请转到消息中的链接。代码构建任务失败可能包含以下原因：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html) | 

## 相关资源
<a name="deploy-chatops-solution-to-manage-sast-scan-results-resources"></a>

**AWS 文档**
+ [配置 Slack 客户端](https://docs.aws.amazon.com/chatbot/latest/adminguide/slack-setup.html#slack-client-setup)
+ [创建自定义操作](https://docs.aws.amazon.com/chatbot/latest/adminguide/custom-actions.html#creating-custom-actions)
+ [创建电子邮件地址身份](https://docs.aws.amazon.com/ses/latest/dg/creating-identities.html#verify-email-addresses-procedure)[程序](https://docs.aws.amazon.com/ses/latest/dg/creating-identities.html#verify-email-addresses-procedure)
+ [教程：开始使用 Slack](https://docs.aws.amazon.com/chatbot/latest/adminguide/slack-setup.html)

**其他资源**
+ [将应用程序添加到 Slack 工作区](https://slack.com/intl/en-in/help/articles/202035138-Add-apps-to-your-Slack-workspace)（Slack 文档）
+ [生成和使用令牌](https://docs.sonarsource.com/sonarqube/latest/user-guide/user-account/generating-and-using-tokens/)（SonarQube 文档）
+ [服务器安装简介](https://docs.sonarsource.com/sonarqube/latest/setup-and-upgrade/install-the-server/introduction/)（SonarQube 文档）

## 附加信息
<a name="deploy-chatops-solution-to-manage-sast-scan-results-additional"></a>

此解决方案强调了聊天应用程序中的 Amazon Q 开发者版自定义操作，可供发布管理之用。但是，您可以根据自己的特定使用案例修改 Lambda 代码并在此基础上进行构建，从而重复使用该解决方案。

** CloudFormation 堆栈文件的参数**

下表显示了 CloudFormation 堆栈文件的参数及其描述`pre-requisite.yml`。


| 
| 
| **键** | **描述** | 
| --- |--- |
| `StackName` |  CloudFormation 堆栈的名称。 | 
| `S3LambdaBucket` | 您上传 Lambda 代码的 Amazon S3 存储桶的名称。此名称必须全局唯一。 | 
| `SonarToken` | [先决条件](#deploy-chatops-solution-to-manage-sast-scan-results-prereqs)中所述的 SonarQube 用户令牌。 | 

下表显示了 CloudFormation 堆栈文件的参数及其描述`app-security.yml`。


| 
| 
| **键** | **描述** | 
| --- |--- |
| `CKMSKeyArn` | 在此堆栈中创建的 IAM 角色和 Lambda 函数中使用的 AWS KMS key 亚马逊资源名称 (ARN)。 | 
| `CKMSKeyId` | 在此堆栈中创建的 Amazon SNS 主题中使用的 AWS KMS key ID。 | 
| `EnvironmentType` | 用于部署应用程序扫描管道的客户端环境的名称。从允许值的下拉列表中选择环境名称。 | 
| `S3LambdaBucket` | 包含 `approval.zip` 和 `notification.zip` 文件的 Amazon S3 存储桶的名称。 | 
| `SESEmail` | 在 Amazon SES 中注册的电子邮件身份的名称，如[先决条件](#deploy-chatops-solution-to-manage-sast-scan-results-prereqs)中所述。此身份是源电子邮件地址。 | 
| `SharedInboxMail` | 扫描通知所发送到的目标电子邮件地址。 | 
| `SlackChannelId` | 您想要向其发送通知的 Slack 频道的频道 ID。要查找频道 ID，请在 Slack 应用程序的**频道详细信息**中右键单击频道名称。频道 ID 位于底部。 | 
| `SlackWorkspaceId` | [先决条件](#deploy-chatops-solution-to-manage-sast-scan-results-prereqs)中所述的 Slack 工作区 ID。**要查找 Slack 工作空间 ID，请登录，在聊天应用程序控制台中打开 Amazon Q Developer，然后选择**已配置的客户端**、Slack、Wor **kspace** ID。 AWS 管理控制台** | 
| `StackName` |  CloudFormation 堆栈的名称。 | 
| `SonarFileDirectory` | 包含 `sonar.project.<env>.properties` 文件的目录。 | 
| `SonarFileName` | `sonar.project.<env>properties` 文件的名称。 | 
| `SourceCodeZip` | 包含 `sonar.project.<env>properties` 文件和源代码的 .zip 文件的名称。 | 

# 通过 Terraform 在 Amazon Bedrock 上使用 CrewAI 框架部署代理式系统
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework"></a>

*Vanitha Dontireddy，Amazon Web Services*

## Summary
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-summary"></a>

此模式演示了如何使用与 [Amazon Bedrock](https://aws.amazon.com/bedrock/?nc1=h_ls) 和 [Terraform](https://registry.terraform.io/) 集成的 [CrewAI](https://www.crewai.com/) 框架来实施可扩展的多代理人工智能系统。利用该解决方案，组织将能够通过基础设施即代码（IaC）创建、部署和管理复杂的人工智能代理工作流。在此模式中，了解 CrewAI 多代理编排功能可与 Amazon Bedrock 基础模型和 Terraform 基础设施自动化相结合。因此，团队可以构建生产就绪型人工智能系统，因此只需最少的人工监督即可处理复杂的任务。该模式实施了企业级安全性、可扩展性和运营最佳实践。

## 先决条件和限制
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-prereqs"></a>

**先决条件**
+  AWS 账户 拥有适当权限[访问 Amazon Bedrock 基础](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html)模型的活跃人士
+ [已安装](https://developer.hashicorp.com/terraform/install) Terraform 版本 1.5 或更高版本
+ [已安装](https://www.python.org/downloads/) Python 版本 3.9 或更高版本
+ [已安装](https://docs.crewai.com/installation) CrewAI 框架

**限制**
+ 代理交互受到模型上下文窗口的限制。
+ 对于大规模部署而言，Terraform 状态管理注意事项同样适用此模式。
+ 有些 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-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-architecture"></a>

在此模式中，会发生以下交互：
+ Amazon Bedrock 通过其基础模型套件为特工情报奠定了基础 (FMs)。它可为人工智能代理提供自然语言处理（NLP）、推理和决策能力，同时还能保持高可用性和可扩展性。
+ CrewAI 框架是创建和管理人工智能代理的核心编排层。它可以处理代理通信协议、任务委派和工作流管理，同时还能与 Amazon Bedrock 集成。
+ Terraform 通过代码管理整个基础设施堆栈，包括计算资源、网络、安全组和 AWS Identity and Access Management (IAM) 角色。它可确保跨环境部署时保持一致性和版本受控。Terraform 部署创建了以下内容：
  + AWS Lambda 运行 CrewaI 应用程序的函数
  + Amazon Simple Storage Service（Amazon S3）存储桶，可用于编码和报告
  + IAM 角色，具有适当的权限
  + 亚马逊 CloudWatch 日志
  + 由亚马逊计划执行 EventBridge

下图阐明了使用 Amazon Bedrock 和 Terraform 部署 CrewAI 多代理系统的架构。

![\[使用 Terraform 和 Amazon Bedrock 部署 CrewAI 多代理系统的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/b46069e9-4c38-405f-b0f0-310eabb06b06/images/b3296b17-e388-46ba-8d71-2ec7ce3ed3e0.png)


下图显示了如下工作流：

1. 用户克隆存储库。

1. 用户运行命令`terraform apply`来部署 AWS 资源。

1. Amazon Bedrock 模型配置包括指定用于配置 CrewAI 代理的基础模型（FM）。

1. 已建立 EventBridge 规则，根据定义的计划触发 Lambda 函数。

1. 当触发（通过计划或手动触发）时，Lambda 函数将初始化并担任具有访问权限和 A AWS 服务 mazon Bedrock 权限的 IAM 角色。

1. CrewAI 框架从 YAML 文件加载代理配置，并创建专门的人工智能代理（*AWS 基础设施安全审计*团队）。Lambda 函数按顺序执行这些代理来扫描 AWS 资源、分析安全漏洞并生成全面的审计报告。

1. CloudWatch 日志从 Lambda 函数中捕获详细的执行信息，保留期为 365 天，并且 AWS Key Management Service (AWS KMS) 加密以满足合规性要求。通过这些日志，可以了解代理活动、错误跟踪和性能指标，从而能够对安全审计流程进行有效的监控和问题排查。

1. 安全审计报告将自动生成并存储在指定的 Amazon S3 存储桶中。自动设置有助于保持一致的安全监控，同时最大限度地减少运营开销。

初始部署后，该工作流程无需人工干预即可为您的 AWS 基础架构提供持续的安全审计和报告。

**人工智能代理概述**

此模式会创建多个人工智能代理，其中每个代理都具有唯一的角色、目标和工具：
+ **安全分析师代理**收集和分析 AWS 资源信息。
+ **渗透测试器代理**可识别 AWS 资源中的漏洞。
+ **合规专家代理**复杂根据合规性标准检查配置。
+ **报告编写者代理**负责将调查发现汇编成综合报告。

这些代理协作完成一系列任务，利用他们的集体技能执行安全审计并生成综合报告。（`config/agents.yaml` 文件概述了该团队中每个代理的能力和配置。）

安全分析处理包含以下操作：

1. 安全分析师代理会检查收集到的有关 AWS 资源的相关数据，例如：
   + Amazon Elastic Compute Cloud（Amazon EC2）实例和安全组
   + Amazon S3 存储桶和配置
   + IAM 角色、策略和权限
   + 虚拟私有云（VPC）配置和网络设置
   + Amazon RDS 数据库和安全设置
   + Lambda 函数和配置
   + 审计范围 AWS 服务 内的其他

1. 渗透测试器代理可识别潜在漏洞。

1. 代理通过 CrewAI 框架开展协作，以共享调查发现。

报告生成包含以下操作：

1. 报告编写者代理汇编所有其他代理的调查发现。

1. 安全问题按服务、严重性和合规性影响进行分类。

1. 就每个已发现的问题生成补救建议。

1. 将以 Markdown 格式创建一份综合安全审计报告，并上传到指定的 Amazon S3 存储桶。保留历史报告，以进行合规性跟踪和安全态势改进。

日志记录和监控活动包括：
+ CloudWatch 日志会捕获执行细节和任何错误。
+ 记录 Lambda 执行指标以供监控之用。

**注意**  
的代码来自 GitHub [3P-agentic\$1F `aws-security-auditor-crew` rameworks 存储库，该存储库可在示例](https://github.com/aws-samples/3P-Agentic-Frameworks/blob/main/crewai/aws-security-auditor-crew/README.md)集合中找到。 AWS 

**可用性和扩缩**

您可以将可用代理数量扩展到四个以上的核心代理。要使用其他专业代理进行扩展，请考虑以下新的代理类型：
+ *威胁情报专家*代理可以执行以下操作：
  + 监控外部威胁源并建立与内部调查发现的关联
  + 提供与您的基础设施的相关的新威胁的上下文
  + 根据野外的活动利用情况，确定漏洞的优先级
+ *合规性框架*代理人可以专注于特定的监管领域，例如：
  + 支付卡行业数据安全标准（PCI DSS）合规性代理
  + 1996 年版健康保险流通与责任法案（HIPAA）合规性代理
  + 系统和组织控制（SOC 2）合规性代理
  + 《通用数据保护条例》（GDPR）合规性代理

通过深思熟虑地扩展可用代理，该解决方案可以提供更深入、更专业的安全见解，同时保持大型 AWS 环境的可扩展性。有关实施方法、工具开发和扩展注意事项的更多信息，请参阅[其他信息](#deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-additional)。

## 工具
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-tools"></a>

**AWS 服务**
+ [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html) 是一项完全托管的人工智能服务，可通过统一的 API 提供高性能基础模型 (FMs) 以供使用。
+ [Amazon CloudWatch Lo](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) gs 可帮助您集中所有系统和应用程序的日志， 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 Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [适用于 Python (Boto3) 的 AWS SDK](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)是一个软件开发套件，可帮助您将 Python 应用程序、库或脚本与集成 AWS 服务。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。在此模式中，它可为代理构件和状态管理提供对象存储。

**其他工具**
+ [CrewAI](https://www.crewai.com/open-source) 是一个基于 Python 的开源框架，可用于构建多代理人工智能系统。
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。

**代码存储库**

此模式的代码可在 GitHub [deploy-crewai-agents-terraform](https://github.com/aws-samples/deploy-crewai-agents-terraform.git)存储库中找到。

## 最佳实践
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-best-practices"></a>
+ 搭配 Amazon DynamoDB 锁定使用 Amazon S3 后端，对 Terraform 实施适当的状态管理。有关更多信息，请参阅*使用 Terraform AWS 提供程序的最佳实践*[中的后端](https://docs.aws.amazon.com/prescriptive-guidance/latest/terraform-aws-provider-best-practices/backend.html)最佳实践。
+ 使用工作区来分隔开发、暂存和生产环境。
+ 遵循最低权限原则，并授予执行任务所需的最低权限。有关详情，请参阅 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)。
+ 通过 CloudWatch 日志启用详细的日志记录和监控。
+ 为代理操作实施重试机制和错误处理。

## 操作说明
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-epics"></a>

### 部署 CrewAI 框架
<a name="deploy-crewai-framework"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 要在本机计算机上克隆此模式的存储库，请运行以下命令：<pre>git clone "git@github.com:aws-samples/deploy-crewai-agents-terraform.git"<br />cd deploy-crewai-agents-terraform</pre> | DevOps 工程师 | 
| 编辑环境变量。 | 要编辑环境变量，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html) | DevOps 工程师 | 
| 创建基础设施。 | 要创建基础设施，请运行以下命令：<pre>cd terraform</pre><pre>terraform init</pre><pre>terraform plan</pre>仔细审查执行计划。如果计划的更改可以接受，则请运行以下命令：<pre>terraform apply --auto-approve</pre> | DevOps 工程师 | 

### 访问 CrewAI 代理
<a name="access-crewai-agents"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 访问代理。 |  AWS 基础设施安全审计和报告团队中的代理是作为 Lambda 函数部署的。要访问代理，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html) | DevOps 工程师 | 
| （可选）配置代理的手动执行。 | 代理配置为按每日时间表自动运行（世界标准时间午夜）。但是，您可以使用以下步骤手动触发：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html)有关更多详细信息，请参阅 Lambda 文档中的[在控制台中测试 Lambda 函数](https://docs.aws.amazon.com/lambda/latest/dg/testing-functions.html)。 | DevOps 工程师 | 
| 访问代理日志，以进行调试。 | CrewAI 代理在 Lambda 环境中运行，并且拥有执行安全审计和在 Amazon S3 中存储报告的必要权限。输出是一份降价报告，可对您的 AWS 基础架构进行全面的安全分析。为了帮助详细调试代理行为，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html) | DevOps 工程师 | 
| 查看代理执行的结果。 | 要查看代理执行的结果，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html)报告以基于时间戳的文件名存储，如下所示：`security-audit-report-YYYY-MM-DD-HH-MM-SS.md)` | DevOps 工程师 | 
| 监控代理执行。 | 要通过 CloudWatch 日志监控代理的执行情况，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html) | DevOps 工程师 | 
|  自定义代理行为。 | 要修改代理或其任务，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html)<pre>cd terraform </pre><pre>terraform apply</pre> | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除创建的资源。 | 要删除此模式创建的所有基础设施，请运行以下命令：<pre>terraform plan -destroy </pre>以下命令将永久删除由此模式创建的所有资源。在移除任何资源之前，该命令会提示进行确认。仔细审查销毁计划。如果计划的删除可以接受，则请运行以下命令：<pre>terraform destroy</pre> | DevOps 工程师 | 

## 问题排查
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 代理行为 | 有关此问题的信息，请参阅 Amazon Bedrock 文档中的[测试代理行为并进行问题排查](https://docs.aws.amazon.com/lambda/latest/dg/troubleshooting-networking.html)。 | 
| Lambda 网络问题 | 有关这些问题的信息，请参阅 Lambda 文档中的 [Lambda 中的联网问题疑难解答](https://docs.aws.amazon.com/lambda/latest/dg/troubleshooting-networking.html)。 | 
| IAM 权限 | 有关这些问题的信息，请参阅 IAM 文档中的[排查 IAM 问题](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot.html)。 | 

## 相关资源
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-resources"></a>

**AWS 博客**
+ [使用 CrewAI 和 Amazon Bedrock 构建代理式系统](https://aws.amazon.com/blogs/machine-learning/build-agentic-systems-with-crewai-and-amazon-bedrock/)

**AWS 文档**
+ [Amazon Bedrock 文档](https://docs.aws.amazon.com/bedrock/)
+ [亚马逊 Bedrock Agents 的工作原理](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-how.html)
+ [AWS 架构完善的框架](https://docs.aws.amazon.com/wellarchitected/latest/framework/welcome.html)

**其他资源**
+ [CrewAI 文档](https://docs.crewai.com/introduction)
+ [Terraform AWS 提供者文档](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)

## 附加信息
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-additional"></a>

本部分包含有关实施方法、工具开发和扩缩注意事项的信息，其中这些注意事项与之前在[自动化和扩缩](#deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-architecture)中讨论的内容有关。

**实施方法**

请考虑使用以下方法来添加代理：

1. 代理配置：
   + 向 `config/agents.yaml` 文件中添加新的代理定义。
   + 为每个代理定义专门的背景故事、目标和工具。
   + 根据代理的专业，配置内存和分析功能。

1. 任务编排：
   + 更新 `config/tasks.yaml` 文件，以包含新的代理特定任务。
   + 在各项任务之间创建依赖关系，以帮助确保正确的信息传递流程。
   + 适当时实施并行任务执行。

**技术实施**

以下是 `agents.yaml` 文件的新增内容，主要涉及拟任的威胁情报专家代理：

```
Example new agent configuration in agents.yaml
threat_intelligence_agent:
 name: "Threat Intelligence Specialist"
 role: "Cybersecurity Threat Intelligence Analyst"
 goal: "Correlate AWS security findings with external threat intelligence"
 backstory: "Expert in threat intelligence with experience in identifying emerging threats and attack patterns relevant to cloud infrastructure." 
verbose: true 
allow_delegation: true 
tools: 
- "ThreatIntelligenceTool" 
- "AWSResourceAnalyzer"
```

**开发工具**

借助 CrewAI 框架，您可以执行以下操作来提高安全审计人员的效率：
+ 为新代理创建自定义工具。
+ 与外部集成 APIs 以获取威胁情报。
+ 针对不同的 AWS 服务情况开发专门的分析仪。

**扩展注意事项**

在扩展您的 AWS 基础设施安全审计和报告系统以处理更大的环境或更全面的审计时，请考虑以下扩展因素：
+ **计算资源**
  + 增加 Lambda 内存分配，以处理其他代理。
  + 考虑将代理工作负载分成多个 Lambda 函数。
+ **成本管理**
  + 随着代理数量的增加，监控 Amazon Bedrock API 的使用情况。
  + 根据审计范围，实施选择性代理激活。
+ **协作效率**
  + 优化代理之间的信息共享。
  + 为复杂的环境实施分层代理结构。
+ **知识库增强**
  + 为代理提供其所在领域的专业知识库。
  + 使用新的安全最佳实践定期更新代理知识。

# 使用 AWS CodePipeline CI/CD 管道部署 AWS Glue 作业
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline"></a>

*Bruno Klein 和 Luis Henrique Massao Yamada，Amazon Web Services*

## Summary
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-summary"></a>

此模式演示了如何将 AWS CodeCommit 和 AWS CodePipeline 与 AWS Glue 集成，并在开发人员将其更改推送到远程 AWS 存储库后立即使用 AWS CodeCommit Lambda 启动作业。 

当开发者向提取、转换和加载 (ETL) 存储库提交更改并将更改推送到 AWS 时 CodeCommit，将调用新的管道。管道启动 Lambda 函数，该函数会启动包含这些更改的 AWS Glue 作业。AWS Glue 作业执行 ETL 任务。

当企业、开发人员和数据工程师希望在提交更改并将其推送到目标存储库后立即启动作业时，此解决方案非常有用。它有助于实现更高水平的自动化和可重复性，从而避免作业启动和生命周期期间出现错误。

## 先决条件和限制
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account。
+ [Git](https://git-scm.com/) 已安装在本地计算机上
+ 安装在本地计算机上的 [Amazon Cloud Development Kit (Amazon CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)
+ 安装在本地机器中的 [Python](https://www.python.org/)
+ *附件*部分中的代码

**限制**
+ AWS Glue 作业成功启动后，管道即完成。它不会等待作业结束。
+ 附件中提供的代码仅用于演示目的。

## 架构
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-architecture"></a>

**目标技术堆栈 **
+ AWS Glue
+ AWS Lambda
+ AWS CodePipeline
+ AWS CodeCommit

**目标架构 **

![\[开发者将更改推送到存储库后，立即使用 Lambda 启动 Glue CodeCommit 任务。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/99a67388-5939-4267-8324-b6ca8bfa7962/images/917c9041-b94d-4e95-a3c4-9a1115ead228.png)


 

该过程包括这些步骤：

1. 开发人员或数据工程师对 ETL 代码进行修改，提交更改并将更改推送到 AWS CodeCommit。

1. 推送启动管道。

1. 管道启动 Lambda 函数，它会调用存储库上的 `codecommit:GetFile` 并将文件上传到Amazon Simple Storage Service (Amazon S3).。

1. Lambda 函数使用 ETL 代码启动新的 AWS Glue 作业。

1. Lambda 函数完成管道。

**自动化和扩展**

示例附件演示了如何将 AWS Glue 与 AWS 集成 CodePipeline。它提供了一个基准示例，您可对其进行自定义或扩展以供自己使用。有关详细信息，请参阅*操作说明*部分。

## 工具
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-tools"></a>
+ [AWS CodePipeline](https://aws.amazon.com/codepipeline/) — AWS CodePipeline 是一项完全托管的[持续交付](https://aws.amazon.com/devops/continuous-delivery/)服务，可帮助您自动执行发布管道，实现快速可靠的应用程序和基础设施更新。
+ [AWS CodeCommit](https://aws.amazon.com/codecommit/) — AWS CodeCommit 是一项完全托管的[源代码控制](https://aws.amazon.com/devops/source-control/)服务，可托管基于 Git 的安全存储库。
+ [AWS Lambda](https://aws.amazon.com/lambda/) – AWS Lambda 是一项无服务器计算服务，可帮助您运行代码，无需预置或管理服务器。
+ [AWS Glue](https://aws.amazon.com/glue) – AWS Glue 是一项无服务器数据集成服务，可轻松发现、准备和组合数据，以用于分析、机器学习和应用程序开发。
+ [Git 客户端](https://git-scm.com/downloads) — Git 提供 GUI 工具，或者你可以使用命令行或桌面工具从中查看所需的工件 GitHub。 
+ [AWS CDK](https://aws.amazon.com/cdk/) – The AWS CDK 是开源软件开发框架，帮助您使用熟悉的编程语言定义云应用程序资源。

## 操作说明
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-epics"></a>

### 部署示例代码
<a name="deploy-the-sample-code"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置 AWS CLI。 | 将 AWS 命令行界面（AWS CLI）配置为目标并使用您当前的 Amazon Web Services account 进行身份验证。有关说明，请参阅 [AWS CLI 文档](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。 | 开发人员、 DevOps 工程师 | 
| 提取项目文件示例。 | 从附件中提取文件，以创建包含示例项目文件的文件夹。 | 开发人员、 DevOps 工程师 | 
| 部署示例代码。 | 解压缩文件后，从提取位置运行以下命令，以创建基准示例：<pre>cdk bootstrap<br />cdk deploy<br />git init<br />git remote add origin <code-commit-repository-url><br />git stage .<br />git commit -m "adds sample code"<br />git push --set-upstream origin main</pre>执行最后一个命令后，您可以监控管道和 AWS Glue 作业的状态。 | 开发人员、 DevOps 工程师 | 
| 自定义代码。 | 根据您的业务需求自定义 etl.py 文件代码。您可修改 ETL 代码、修改管道阶段或者扩展解决方案。 | 数据工程师 | 

## 相关资源
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-resources"></a>
+ [AWS CDK 入门](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)
+ [在 AWS Glue 中添加作业](https://docs.aws.amazon.com/glue/latest/dg/add-job.html)
+ [源操作集成 CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/integrations-action-type.html#integrations-source)
+ [在中的管道中调用 AWS Lambda 函数 CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-invoke-lambda-function.html)
+ [AWS Glue 编程](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming.html)
+ [AWS CodeCommit GetFile API](https://docs.aws.amazon.com/codecommit/latest/APIReference/API_GetFile.html)

## 附件
<a name="attachments-99a67388-5939-4267-8324-b6ca8bfa7962"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/99a67388-5939-4267-8324-b6ca8bfa7962/attachments/attachment.zip)

# 使用 AWS CodePipeline、AWS 和 AWS 在多个 AWS CodeCommit 区域部署代码 CodeBuild
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild"></a>

*Anand Krishna Varanasi，Amazon Web Services*

## Summary
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-summary"></a>

此模式演示了如何使用 AWS 跨多个 Amazon Web Services (AWS) 区域构建基础设施或架构 CloudFormation。它包括跨多个 AWS 区域的持续集成（CI）/持续部署（CD），以实现更快的部署。****例如，此模式中的步骤已经过测试，用于创建部署到三个 AWS 区域的 AWS CodePipeline 任务。您可以基于用例来更改区域数量。

## 先决条件和限制
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 
  + *在 AmazonS3 FullAccess* 和*CloudWatchFullAccess*政策中 CodeBuild 扮演的角色。这些政策 CodeBuild 允许 CodeCommit 通过亚马逊观看 AWS 的事件， CloudWatch 以及使用亚马逊简单存储服务 (Amazon S3) Simple Storage Service 作为工件存储。
  + 具有以下策略的 AWS CloudFormation 角色，这些策略使 AWS CloudFormation 能够在最后的构建阶段创建或更新 AWS Lambda 函数、推送或监视 Amazon CloudWatch 日志，以及创建和更新更改集。 
    + *AWSLambdaFullAccess*
    + *AWSCodeDeployFullAccess*
    + *CloudWatchFullAccess*
    + *AWSCloudFormationFullAccess*
    + *AWSCodePipelineFullAccess*
**注意**  
两个 AWS 和 AWS 的 AWS CodeBuild Identity and Access Management (IAM) 角色 CloudFormation 具有适当的策略，用于 CodeBuild 执行 CI 任务，即测试、捆绑、打包工件以及并行部署到多个 AWS 区域。  交叉检查由创建的策略 CodePipeline 以验证是否 CodeBuild 和 AWS 在 CI 和 CD 阶段 CloudFormation 具有适当的权限。

## 架构
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-architecture"></a>

![\[部署到三个 AWS 区域的 AWS CodePipeline 任务。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/d44c393c-7243-4d4e-8b84-88a8503af98f/images/5c27fc35-5e62-4292-8b18-a7bc7faf2631.png)


此模式的多区域架构和工作流程包括以下步骤。

1. 您将代码发送到存储 CodeCommit 库。

1. 在收到任何代码更新或提交后， CodeCommit 调用一个 CloudWatch 事件，该事件反过来会启动作 CodePipeline 业。

1. CodePipeline 使用由 CodeBuild处理的 CI。将执行以下任务。
   + 测试 AWS CloudFormation 模板（可选）
   + 打包部署中包含的每个区域的 AWS CloudFormation 模板。例如，此模式与三个 AWS 区域并行部署，因此将 AWS CloudFormation 模板 CodeBuild 打包到三个 S3 存储桶中，每个指定区域一个。S3 存储桶仅供 CodeBuild 用作项目存储库。

1. CodeBuild 将工件打包为下一个部署阶段的输入，该阶段将在三个 AWS 区域并行运行。如果您指定不同数量的区域，则 CodePipeline 会部署到这些区域。

## 工具
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-tools"></a>

**工具**
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) — CodePipeline 是一项持续交付服务，可用于对持续发布软件变更所需的步骤进行建模、可视化和自动化。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) — CodeBuild 是一项完全托管的构建服务，可编译您的源代码、运行单元测试并生成可随时部署的项目。
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) — CodeCommit 是一项由 Amazon Web Services 托管的版本控制服务，您可以使用它来私下存储和管理云中的资产（例如源代码和二进制文件）。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) — AWS CloudFormation 是一项服务，可帮助您建模和设置 Amazon Web Services 资源，这样您就可以花更少的时间管理这些资源，而将更多的时间集中在在 AWS 中运行的应用程序上。
+ [AWS Identity and Access Management](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)– AWS Identity and Access Management (IAM) 是一项 Web 服务，可帮助您安全地控制对 AWS 资源的访问。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一项面向互联网的存储服务。该服务旨在降低开发人员进行网络规模级计算的难度。

**代码**

以下示例代码适用于该 `BuildSpec.yaml` 文件（构建阶段）。

```
---
artifacts:
discard-paths: true
files:
- packaged-first-region.yaml
- packaged-second-region.yaml
- packaged-third-region.yaml
phases:
build:
commands:
- echo "********BUILD PHASE - CF PACKAGING**********"
- "aws cloudformation package --template-file sam-template.yaml --s3-bucket $S3_FIRST_REGION --output-template-file packaged-first-region.yaml --region $FIRST_REGION"
- "aws cloudformation package --template-file sam-template.yaml --s3-bucket $S3_SECOND_REGION --output-template-file packaged-second-region.yaml --region $SECOND_REGION"
- "aws cloudformation package --template-file sam-template-anand.yaml --s3-bucket $S3_THIRD_REGION --output-template-file packaged-third-region.yaml --region $THIRD_REGION"
install:
commands:
- echo "********BUILD PHASE - PYTHON SETUP**********"
runtime-versions:
python: 3.8
post_build:
commands:
- echo "********BUILD PHASE - PACKAGING COMPLETION**********"
pre_build:
commands:
- echo "********BUILD PHASE - DEPENDENCY SETUP**********"
- "npm install --silent --no-progress"
- echo "********BUILD PHASE - DEPENDENCY SETUP DONE**********"
version: 0.2
```

## 操作说明
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-epics"></a>

### 准备代码和 CodeCommit 存储库
<a name="prepare-the-code-and-the-codecommit-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 选择用于部署的主要 AWS 区域。 | 登录 Amazon Web Services account，选择要部署的主区域。 CodeCommit 存储库将位于主区域。 | DevOps | 
| 创建 CodeCommit 存储库。 | 创建 CodeCommit 存储库，并将所需的代码推送到其中。该代码通常包括 AWS CloudFormation 或 AWS SAM 模板、Lambda 代码（如果有）以及作为 AWS 输入的 CodeBuild `buildspec.yaml`文件。 CodePipeline | DevOps | 
| 将代码推送到 CodeCommit 存储库中。 | 在*附件*部分中，下载此示例的代码，然后将所需代码推送到其中。通常，代码可以包含 AWS CloudFormation 或 AWS SAM 模板、Lambda 代码和作为管道输入的 CodeBuild `buildspec.yaml`文件。 | DevOps | 

### 源代码阶段：创建管线
<a name="source-phase-create-the-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建作 CodePipeline 业。 | 在 CodePipeline 控制台上，选择**创建管道**。 | DevOps | 
| 为 CodePipeline 作业命名并选择服务角色设置。 | 输入作业的名称，并保留默认的服务角色设置，以便 CodePipeline 创建附加必要策略的角色。 | DevOps | 
| 指定构件存储的位置。 | 在 **“高级设置”** 下，保留默认选项，以便 CodePipeline 创建用于存储代码项目的 S3 存储桶。如果您改用现有 S3 存储桶，则该存储桶必须位于您在第一个操作说明中指定的主区域。 | DevOps | 
| 指定加密密钥。 | 保留默认选项：**默认 AWS 托管式密钥**，或者选择使用您自己的 AWS Key Management Service（AWS KMS）客户托管密钥。 | DevOps | 
| 指定源提供程序。 | 在**来源提供商**下，选择 **AWS CodeCommit**。 | DevOps | 
| 指定存储库。 | 选择您在第一部长篇故事中创建的 CodeCommit 存储库。如果您将代码放在分支中，请选择该分支。 | DevOps | 
| 指定如何检测代码更改。 | 保留默认的 **Amazon Ev CloudWatch en** ts 作为启动 CodePipeline 任务的 CodeCommit 更改触发器。 | DevOps | 

### 构建阶段：配置管线
<a name="build-phase-configure-the-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 指定构建提供程序。 | 对于构建提供商，请选择 **AWS CodeBuild**。 | DevOps | 
| 指定 AWS 区域。 | 选择您在第一个操作说明中指定的主区域。 | DevOps | 

### 构建阶段：创建和配置项目
<a name="build-phase-create-and-configure-the-project"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建项目 | 选择**创建项目**，然后输入项目的名称。 | DevOps | 
| 指定环境映像。 | 对于此模式演示，请使用默认的 CodeBuild 托管映像。如果您有自定义的 Docker 映像，您还可以选择使用该 Docker 映像。 | DevOps | 
| 指定操作系统。 | 选择 Amazon Linux 2 或 Ubuntu。即将终止对 Amazon Linux 2 的支持。欲了解更多信息，请参阅[亚马逊 Linux 2 FAQs](https://aws.amazon.com/amazon-linux-2/faqs/)。 | DevOps | 
| 指定服务角色。 | 选择您在开始创建 CodePipeline 作业 CodeBuild 之前为其创建的角色。（请参阅*先决条件*部分。） | DevOps | 
| 设置其他选项。 | 对于**超时**和**队列超时**，请保留默认值。对于证书，除非您有要使用的自定义证书，否则请保留默认设置。 | DevOps | 
| 创建环境变量。 | 对于您要部署到的每个 AWS 区域，请通过提供 S3 存储桶名称和区域名称（例如 us-east-1）来创建环境变量。 | DevOps | 
| 如果不是 buildspec.yml，请提供 buildspec 文件名。 | 如果文件名为默认名称 `buildspec.yaml`，则将此字段留空。如果您重命名了 buildspec 文件，请在此处输入名称。确保它与 CodeCommit 存储库中文件的名称相匹配。 | DevOps | 
| 指定日志记录。 | 要查看 Amazon CloudWatch 事件的日志，请保留默认设置。或者，您可以定义任何特定的组或记录器名称。 | DevOps | 

### 跳过“部署”阶段
<a name="skip-the-deploy-phase"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 跳过部署阶段并完成管线的创建。 | 设置管道时，只 CodePipeline 允许您在 “部署” 阶段创建一个阶段。要部署到多个 AWS 区域，请跳过此阶段。创建管线后，您可以添加“部署阶段”的多个阶段。 | DevOps | 

### 部署阶段：配置管线以部署到第一个区域
<a name="deploy-phase-configure-the-pipeline-for-deployment-to-the-first-region"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 向部署阶段添加阶段。 | 编辑管线，然后在“部署”阶段选择**添加阶段**。第一个阶段适用于主区域。 | DevOps | 
| 提供阶段的操作名称。 | 输入反映第一个（主）阶段和区域的唯一名称。例如，输入 **primary\$1<region>\$1deploy**。 | DevOps | 
| 指定操作提供程序。 | 对于**操作提供者**，请选择 AWS CloudFormation。 | DevOps | 
| 为第一个阶段配置区域。 | 选择第一个（主要）区域，即设置 CodePipeline 和 CodeBuild 的相同区域。这是您要在其中部署堆栈的主区域。 | DevOps | 
| 指定输入构件。 | 选择 **BuildArtifact**。这是构建阶段的输出。 | DevOps | 
| 指定要采取的操作。 | 对于**操作模式**，选择**创建或更新堆栈**。 | DevOps | 
| 输入堆 CloudFormation 栈的名称。 |  | DevOps | 
| 为第一个区域指定模板。 | 选择由第一个（主）区域打包 CodeBuild 并转储到第一个（主）区域的 S3 存储桶中的特定于区域的软件包名称。 | DevOps | 
| 指定功能。 | 如果堆栈模板包含 IAM 资源，或者您直接使用包含宏的模板创建堆栈，则需要功能。对于这种模式，请使用 CAPABILITY\$1IAM、CAPABILITY\$1NAMED\$1IAM、CAPABILITY\$1AUTO\$1EXPAND。 | DevOps | 

### 部署阶段：配置管线以部署到第二个区域
<a name="deploy-phase-configure-the-pipeline-for-deployment-to-the-second-region"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将第二个阶段添加到“部署”阶段。 | 要为第二个区域添加阶段，请编辑管线并在“部署”阶段选择**添加阶段**。重要：创建第二个区域的过程与第一个区域的创建过程相同，但以下值除外。 | DevOps | 
| 提供第二个阶段的操作名称。 | 输入反映第二个阶段和第二个区域的唯一名称。 | DevOps | 
| 为第二个阶段配置区域。 | 选择您希望在其上部署堆栈的第二个区域。 | DevOps | 
| 为第二个区域指定模板。 | 选择由第二个区域打包 CodeBuild 并转储到 S3 存储桶中的特定于区域的软件包名称。 | DevOps | 

### 部署阶段：配置管线以部署到第三个区域
<a name="deploy-phase-configure-the-pipeline-for-deployment-to-the-third-region"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将第三个阶段添加到“部署”阶段。 | 要为第三个区域添加阶段，请编辑管线并在“部署”阶段选择**添加阶段**。重要：创建第三个区域的过程与前两个区域的创建过程相同，但以下值除外。 | DevOps | 
| 提供第三个阶段的操作名称。 | 输入反映第三个阶段和第三个区域的唯一名称。 | DevOps | 
| 为第三个阶段配置区域。 | 选择您希望在其上部署堆栈的第三个区域。 | DevOps | 
| 为第三个区域指定模板。 | 选择由第三个区域打包 CodeBuild 并转储到 S3 存储桶中的特定于区域的软件包名称。 | DevOps | 

### 清理部署
<a name="clean-up-the-deployment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除 AWS 资源。 | 要清理部署，请删除每个区域中的 CloudFormation 堆栈。然后从主区域中删除 CodeCommit CodeBuild、和 CodePipeline 资源。 | DevOps | 

## 相关资源
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-resources"></a>
+ [什么是 AWS CodePipeline？](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)
+ [AWS 无服务器应用程序模型](https://aws.amazon.com/serverless/sam/)
+ [AWS CloudFormation](https://aws.amazon.com/cloudformation/)
+ [适用于 AWS 的 AWS CloudFormation 架构结构参考 CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/action-reference-CloudFormation.html)

## 附件
<a name="attachments-d44c393c-7243-4d4e-8b84-88a8503af98f"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/d44c393c-7243-4d4e-8b84-88a8503af98f/attachments/attachment.zip)

# 将工作负载从 Azure DevOps 管道部署到私有的 Amazon EKS
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters"></a>

*Mahendra Revanasiddappa，Amazon Web Services*

## Summary
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-summary"></a>

此模式演示了如何实现从 Azure DevOps 管道到私有亚马逊 Elastic Kubernetes Service (Amazon EKS) 集群的持续集成和持续交付 (CI/CD)。此模式解决了组织在通过过渡至 Amazon EKS 集群的私有 API 服务器端点来增强其安全态势时所面临的一项关键挑战。

公有端点会直接向互联网公开 Kubernetes API 服务器，从而可能会扩大恶意行为者的攻击面。切换到私有端点后，仅限在客户的虚拟私有云（VPC）内访问集群的控制面板。

尽管将 Amazon EKS 集群过渡到私有 API 终端节点可以显著增强安全性，但它会给 Azure DevOps 等外部 CI/CD 平台带来连接挑战。只能从集群的 VPC 或对等网络中访问私有端点。因此，在 AWS 私有网络之外运行的标准微软托管的 Azure DevOps 代理无法直接访问 Kubernetes API 服务器。这就破坏了依赖于在这些代理上运行的工具（例如 kubectl 或 Helm）的典型部署工作流，因为它们无法与集群建立连接。

为了克服这个问题，这种模式展示了一种有效的方法，即在私有 Amazon EKS 集群中使用自托管 Azure DevOps 代理。该解决方案提供了卓越的成本优化、运营效率和可扩展性，同时保留了安全要求。这种方法特别有利于寻求在不影响性能或安全性的前提下简化多云 DevOps 流程的企业。

## 先决条件和限制
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ AWS Command Line Interface [(AWS CLI) 版本 2.13.17 或更高版本，已安装。](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
+ kubectl 版本 1.25.1 或更高版本，[已安装](https://kubernetes.io/docs/tasks/tools/)。
+ [已创建](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html)私有 Amazon EKS 集群版本 1.24 或更高版本，具有创建命名空间、密钥和部署的权限[。](https://docs.aws.amazon.com/eks/latest/userguide/create-cluster.html)
+ Amazon EKS 集群中的工作节点具有互联网的出站连接，因此在其上运行的 Azure DevOps 代理可以连接到 Azure DevOps 代理池。
+ GitHub 账户[已创建](https://github.com/signup)。
+ [创建](https://learn.microsoft.com/en-us/azure/devops/user-guide/sign-up-invite-teammates?view=azure-devops&tabs=microsoft-account)了一个有权配置服务连接的 Azure DevOps 项目，这些连接是 Azure Pipelines 与外部或远程服务之间经过身份验证的连接。
+ 为上一点中描述的 Azure DevOps 项目安装的 1.15 或更高 AWS Toolkit for Azure DevOps 版本。有关安装说明，请参阅 Visual Studio Marketplace 中的 [AWS Toolkit for Azure DevOps](https://marketplace.visualstudio.com/items?itemName=AmazonWebServices.aws-vsts-tools)。

**限制**
+ 有些 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-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-architecture"></a>

此模式会创建以下内容：
+ **亚马逊 ECR 存储库** ——亚马逊弹性容器注册表 (Amazon ECR) Registry 存储库将 Docker 映像与 Azure DevOps 代理和部署的示例应用程序一起存储。
+ **Azure DevOps 代理池**-Azure DevOps 自托管代理池注册在私有 Amazon EKS 集群上运行的代理。
+ **IAM 角色**-Azure 服务连接的 AWS Identity and Access Management (IAM) 角色，用于为在私有 Amazon EKS 集群上运行的代理提供所需的访问权限。
+ **Azure DevOps 服务连接**-Azure DevOps 账户中的服务连接，用于使用 IAM 角色，为管道作业提供访问所需的访问权限 AWS 服务。

下图显示了在私有 Amazon EKS 集群上部署自托管 Azure DevOps 代理并在同一集群上部署示例应用程序的架构。

![\[在私有 Amazon EKS 集群上部署自托管的 Azure DevOps 代理和示例应用程序。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a965834f-a1e2-4679-bd8c-15eed4f57b55/images/ee22bd3e-311c-46e0-8024-9b7e7752080a.png)


下图显示了如下工作流：

1. 将自托管的 Azure DevOps 代理部署为在 Amazon EKS 集群中的部署。

1. Azure DevOps 代理使用个人访问令牌 (PAT) 进行身份验证，连接到 Azure DevOps 帐户上的代理池。

1. Azure Pipelines 使用 GitHub 存储库中的代码配置要部署的管道。

1. 该管道可在代理池中的代理上运行，其中该代理池可管道配置中进行配置。Azure DevOps 代理通过不断轮询到 Azure DevOps 帐户来获取管道的作业信息。

1. Azure DevOps 代理在管道作业中构建 Docker 映像，并将该映像推送到 Amazon ECR 存储库。

1. Azure DevOps 代理将示例应用程序部署到名为的命名`webapp`空间中的私有 Amazon EKS 集群上。

## 工具
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-tools"></a>

**工具**
+ [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/what-is-eks.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。

**其他工具**
+ [Docker](https://www.docker.com/) 是一组平台即服务（PaaS）产品，它们使用操作系统级别的虚拟化技术在容器中交付软件。
+ [kubectl](https://kubernetes.io/docs/tasks/tools/)：针对 Kubernetes 集群运行命令的命令行界面。

**代码存储库**
+ 此模式的代码可在 GitHub [deploy-kubernetes-resources-to-amazon-eks-using-azure-devops](https://github.com/aws-samples/deploy-kubernetes-resources-to-amazon-eks-using-azure-devops) 存储库中找到。

## 最佳实践
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-best-practices"></a>
+ 有关 Amazon EKS 的信息，请参阅 [Amazon EKS 最佳实践指南](https://docs.aws.amazon.com/eks/latest/best-practices/introduction.html)。
+ 遵循最低权限原则，并授予执行任务所需的最低权限。有关详情，请参阅 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="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-epics"></a>

### 创建服务连接
<a name="create-a-service-connection"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查找 Azure DevOps 组织指南。 | 登录你的 Azure DevOps 帐户，然后使用以下 URL 查找组织 GUID：`https://dev.azure.com/{DevOps_Org_ID}/_apis/projectCollections?api-version=6.0`在网址中，`{DevOps_org_ID}`替换为你的 Azure DevOps 组织 ID。 | AWS DevOps | 
| 在 AWS 账户中配置 IdP。 | 要在中为 Azure 服务连接配置身份提供者 (IdP)，请使用以下步骤： AWS 账户 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)有关更多详细信息，请参阅[如何 DevOps 使用 OpenID Connect AWS 从 Azure 联合到](https://aws.amazon.com/blogs/modernizing-with-aws/how-to-federate-into-aws-from-azure-devops-using-openid-connect/)。 | AWS DevOps | 
| 在 AWS 账户中创建 IAM 策略。 | 要创建 IAM 策略以向 Azure DevOps 管道使用的 IAM 角色提供所需权限，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | AWS DevOps | 
| 在 AWS 账户中创建 IAM 角色。 | 要在中为 Azure 服务连接配置 IAM 角色，请使用以下步骤： AWS 账户 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)<pre>{<br />  "Version": "2012-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Effect": "Allow",<br />      "Principal": {<br />        "Federated": "arn:aws:iam::{account_id}:oidc-provider/vstoken.dev.azure.com/{OrganizationGUID}"<br />      },<br />      "Action": "sts:AssumeRoleWithWebIdentity",<br />      "Condition": {<br />        "StringEquals": {<br />          "vstoken.dev.azure.com/{OrganizationGUID}:aud": "api://AzureADTokenExchange",<br />          "vstoken.dev.azure.com/{OrganizationGUID}:sub": "sc://{OrganizationName}/{ProjectName}/{ServiceConnectionName}"<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/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | AWS DevOps | 
| 在 Azure DevOps 帐户中创建服务连接。 | 要配置 Azure 服务连接，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)有关更多详细信息，请参阅 Microsoft 文档中的[创建服务连接](https://learn.microsoft.com/en-us/azure/devops/pipelines/library/service-endpoints?view=azure-devops#create-a-service-connection)。 | AWS DevOps | 
| 将 IAM 角色添加到 Amazon EKS 配置文件。 | IAM 角色必须具有在 Amazon EKS 集群上执行所需操作的必要权限。由于 IAM 角色是一个管道角色，因此该角色必须能够管理集群上几乎所有类型的资源。因此，`system:masters` 组权限适用于此角色。要将所需的配置添加到 Kubernetes 内的 `aws-auth ConfigMap` 中，请使用以下代码：<pre>- groups:<br />  - system:masters<br />  rolearn: arn:aws:iam::{account_id}:role/ADO-role<br />  username: ADO-role</pre>`{account_id}`用您的 AWS 账户 身份证替换。有关更多详细，请参阅 Amazon EKS 文档中的[Amazon EKS 如何与 IAM 配合使用](https://docs.aws.amazon.com/eks/latest/userguide/security-iam-service-with-iam.html#security-iam-service-with-iam-roles)。 | AWS DevOps | 

### 创建代理池
<a name="create-an-agent-pool"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建自托管代理池。 | 要在 Azure DevOps 帐户中配置自托管代理池，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)有关更多详细信息，请参阅 Microsoft 文档中的[创建和管理代理池](https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/pools-queues?view=azure-devops&tabs=yaml%2Cbrowser)。 |  | 

### 构建 Azure DevOps 代理镜像并推送到亚马逊 ECR
<a name="build-azure-devops-agent-image-and-push-to-ecr"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Amazon ECR 存储库。 | 用于在私有 Amazon EKS 集群上部署 Azure DevOps 代理和示例应用程序 (`webapp`) 的 Docker 映像必须存储在 Amazon ECR 存储库中。要创建 Amazon ECR 存储库，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)有关更多详细信息，请参阅 Amazon ECR 文档中的[创建 Amazon ECR 私有存储库来存储映像](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)。 | AWS DevOps | 
| 创建一个 Dockerfile 来构建 Azure 代理 DevOps 。 | 创建一个 Dockerfile 来生成安装了 Azure DevOps 代理的 Docker 镜像。将以下内容存储在名为 `Dockerfile` 的文件中：<pre><br />FROM ubuntu:22.04 <br />ENV TARGETARCH="linux-x64"<br />RUN apt update && apt upgrade -y && apt install -y curl git jq libicu70 unzip wget<br /><br />RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"<br />RUN unzip awscliv2.zip<br />RUN ./aws/install<br />RUN rm -rf aws awscliv2.zip<br /><br />RUN curl -sSL https://get.docker.com/ | sh<br /><br />RUN curl -sL https://aka.ms/InstallAzureCLIDeb | bash<br />RUN mkdir -p azp <br />WORKDIR /azp/<br /><br />COPY ./start.sh ./ <br />RUN chmod +x ./start.sh<br /><br />RUN useradd -m -d /home/agent agent <br />RUN chown -R agent:agent /azp /home/agent<br />RUN groupadd -f docker <br />RUN usermod -aG docker agent<br />USER agent<br /><br />ENTRYPOINT [ "./start.sh" ]</pre> | AWS DevOps | 
| 为 Azure DevOps 代理创建脚本。 | 要创建 `start.sh` 脚本，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | AWS DevOps | 
| 使用 Azure DevOps 代理构建 Docker 镜像。 | 要创建 Docker 镜像来安装 Azure DevOps 代理，请使用你之前创建的 Dockerfile 来构建镜像。在存储 Dockerfile 的同一个目录中，运行以下命令：<pre>aws ecr get-login-password --region region | docker login --username AWS --password-stdin aws_account_id.dkr.ecr.region.amazonaws.com<br /><br />docker build --platform linux/amd64 -t ado-agent:latest .<br /><br />docker tag ado-agent:latest aws_account_id.dkr.ecr.region.amazonaws.com/webapp:latest<br /><br />docker push aws_account_id.dkr.ecr.region.amazonaws.com/webapp:latest</pre>用您的 AWS 账户 ID 替换`aws_account_id`和`region`，然后 AWS 区域。 | AWS DevOps | 

### 将 Azure DevOps 代理部署到私有 Amazon EKS 集群
<a name="deploy-the-azure-devops-agent-to-a-private-eks-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 生成 Azure 个人访问令牌。 | 在私有 Amazon EKS 集群上运行的代理需要个人访问令牌 (PAT)，这样它才能使用 Azure DevOps 账户进行身份验证。要生成 PAT，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)<pre>apiVersion: v1<br />kind: Secret<br />metadata:<br />  name: azdevops-pat<br />  namespace: default<br />type: Opaque<br />stringData:<br />  AZP_TOKEN: <PAT Token></pre>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)<pre>kubectl create -f ado-secret.yaml</pre>有关更多详细信息，请参阅 Microsoft 文档中的[使用个人访问令牌（PAT）注册代理](https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/personal-access-token-agent-registration?view=azure-devops)。 | AWS DevOps | 
| 使用 Kubernetes 清单文件以进行代理部署。 | 要在私有 Amazon EKS 集群上部署 Azure DevOps 代理，请复制以下清单文件并将该文件存储为`agent-deployment.yaml`：<pre>apiVersion: apps/v1<br />kind: Deployment<br />metadata:<br />  name: azure-pipelines-agent-eks<br />  labels:<br />    app: azure-pipelines-agent<br />spec:<br />  replicas: 1<br />  selector:<br />    matchLabels:<br />      app: azure-pipelines-agent<br />  template:<br />    metadata:<br />      labels:<br />        app: azure-pipelines-agent<br />    spec:<br />      containers:<br />      - name: docker<br />        image: docker:dind<br />        securityContext: <br />          privileged: true<br />        volumeMounts:<br />        - name: shared-workspace<br />          mountPath: /workspace<br />        - name: dind-storage<br />          mountPath: /var/lib/docker<br />        env:<br />        - name: DOCKER_TLS_CERTDIR<br />          value: ""<br />      - name: azure-pipelines-agent<br />        image: aws_account_id.dkr.ecr.region.amazonaws.com/webapp:latest<br />        env:<br />        - name: AZP_URL<br />          value: "<Azure account URL>"<br />        - name: AZP_POOL<br />          value: "eks-agent"<br />        - name: AZP_TOKEN<br />          valueFrom:<br />            secretKeyRef:<br />              name: azdevops-pat<br />              key: AZP_TOKEN<br />        - name: AZP_AGENT_NAME<br />          valueFrom:<br />            fieldRef:<br />              fieldPath: metadata.name<br />        - name: DOCKER_HOST<br />          value: tcp://localhost:2375<br />        volumeMounts:<br />        - mountPath: /workspace<br />          name: shared-workspace<br />      volumes:<br />      - name: dind-storage<br />        emptyDir: {}<br />      - name: shared-workspace<br />        emptyDir: {}</pre>将`aws_account_id`和`<Azure account URL>`替换为你的 AWS 账户 ID 和 Azure DevOps 帐户网址。 | AWS DevOps | 
| 在私有 Amazon EKS 集群上部署代理。 | 要在私有 Amazon EKS 集群上部署 Azure DevOps 代理，请使用以下命令：<pre>kubectl create -f agent-deployment.tf</pre> | AWS DevOps | 
| 验证代理是否正在运行。 | 要验证 Azure DevOps 代理是否正在运行，请使用以下命令：<pre>kubectl get deploy azure-pipelines-agent-eks<br /></pre>该预期输出应该类似于以下所示：<pre><br />NAME                        READY   UP-TO-DATE   AVAILABLE   AGE<br />azure-pipelines-agent-eks   1/1     1            1           58s</pre>确认 `READY ` 列已显示 `1/1`。 | AWS DevOps | 
| 验证代理是否已在 Azure DevOps 代理池中注册。 | 要验证代理是否已部署在私有 Amazon EKS 集群上并已向代理池 `eks-agent` 中注册，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)您应该看到列出的代理的**状态为 “****在线**”，并且该代理的名称应以 **azure-pipelines-agent-eks-\$1** 开头。 | AWS DevOps | 

### 部署示例应用程序
<a name="deploy-sample-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将示例应用程序存储库分支到您的 GitHub 账户。 | 将以下 AWS 示例存储库分支到您的 GitHub 账户：[https://github.com/aws-samples/deploy-kubernetes-resources-to-amazon-eks-using-azure-devops](https://github.com/aws-samples/deploy-kubernetes-resources-to-amazon-eks-using-azure-devops) | AWS DevOps | 
| 创建管道。 | 要在你的 Azure DevOps 帐户中创建管道，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)<pre>pool:<br />  name: eks-agent<br />#pool: self-hosted # If you are running self-hosted Azure DevOps Agents<br /><br />stages:<br /># Refering the pipeline template, input parameter that are not specified will be added with defaults<br />- template: ./pipeline_templates/main_template.yaml<br />  parameters:<br />    serviceConnectionName: aws-sc<br />    awsRegion: <your region><br />    awsEKSClusterName: <name of your EKS cluster><br />    projectName: webapp<br /></pre>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | AWS DevOps | 
| 验证示例应用程序是否已部署。 | 管道完成后，检查 Amazon ECR 存储库和 Amazon EKS 集群，进而验证示例应用程序是否已成功部署。要验证 Amazon ECR 存储库中的构件，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)例如，`20250501.1-image` 和 `20250501.1-helm`。要在命名空间 `webapp` 中验证私有 Amazon EKS 集群上的部署，请使用以下命令：<pre>kubectl get deploy -n webapp </pre>预期的输出如下所示：<pre><br />NAME     READY   UP-TO-DATE   AVAILABLE<br />webapp   1/1     1            1           </pre>注意：如果这是您首次运行管道，则可能需要对服务连接和代理池执行授权。在 Azure DevOps 管道界面中查找权限请求，然后批准它们以继续。 | AWS DevOps | 

## 问题排查
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 当 Amazon ECR 存储库名称与 `webapp` 不匹配时，管道失败 | 示例应用程序希望 Amazon ECR 存储库名称与 `azure_pipeline.yml` 中的 `projectName: webapp` 参数相匹配。要解决此问题，请将您的 Amazon ECR 存储库重命名为 `webapp`，或更新以下内容：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | 
| 错误：Kubernetes 集群无法访问：服务器已要求客户端提供凭证 | 如果您在 Azure Pipelines 的“提取并部署 Helm 图表”步骤中遇到此错误，则根本原因通常源于 Amazon EKS 集群 `aws-auth ConfigMap` 中的 IAM 角色配置不正确。要解决此问题，请检查以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | 

## 相关资源
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-resources"></a>

**AWS 博客**
+ [如何 DevOps 使用 OpenID Connect AWS 从 Azure 联合进入](https://aws.amazon.com/blogs/modernizing-with-aws/how-to-federate-into-aws-from-azure-devops-using-openid-connect/)

**AWS 服务 文档**
+ [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)
+ [Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html)

**微软文档**
+ [什么是 Azure DevOps？](https://learn.microsoft.com/en-us/azure/devops/user-guide/what-is-azure-devops?view=azure-devops)
+ [什么是 Azure Pipelines？](https://learn.microsoft.com/en-us/azure/devops/pipelines/get-started/what-is-azure-pipelines?view=azure-devops)

# 使用 Terraform 执行 Amazon Redshift SQL 查询
<a name="execute-redshift-sql-queries-using-terraform"></a>

*Sylvia Qi 和 Aditya Ambati， Amazon Web Services*

## Summary
<a name="execute-redshift-sql-queries-using-terraform-summary"></a>

使用基础设施即代码 (IaC) 来部署和管理 Amazon Redshift 是一种普遍的做法。 DevOpsIaC 有助于部署和配置各种 Amazon Redshift 资源，例如集群、快照和参数组。但是，IaC 并未扩展到管理数据库资源，例如表、架构、视图和存储过程。这些数据库元素通过 SQL 查询进行管理，并且不受 IaC 工具支持，无法直接进行处理。尽管有用于管理这些资源的解决方案和工具，但您可能不希望在技术堆栈中引入其他工具。

此模式概述了一种使用 Terraform 部署 Amazon Redshift 数据库资源（包括表、架构、视图和存储过程）的方法。该模式区分了两种类型的 SQL 查询：
+ **不可重复查询** – 这些查询在最初的 Amazon Redshift 部署期间执行一次，以建立基本的数据库组件。
+ **可重复查询** – 这些查询是不可变的，可以在不影响数据库的情况下重新运行。该解决方案使用 Terraform 来监控可重复查询中的变化并相应地应用它们。

有关更多详细信息，请参阅[其他信息](#execute-redshift-sql-queries-using-terraform-additional)中的*解决方案演练*。

## 先决条件和限制
<a name="execute-redshift-sql-queries-using-terraform-prereqs"></a>

**先决条件**

您必须激活 AWS 账户 并在部署计算机上安装以下内容：
+ [AWS Command Line Interface](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (AWS CLI)
+ [AWS CLI 配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)了亚马逊 Redshi read/write ft 权限的个人资料
+ [Terraform](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) 版本 1.6.2 或更高版本
+ [Python3](https://www.python.org/downloads/)
+ [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)

**限制**
+ 此解决方案支持单个 Amazon Redshift 数据库，因为 Terraform 只允许在创建集群期间创建一个数据库。
+ 此模式不包括在应用对可重复查询的更改之前验证该更改的测试。我们建议您采用此类测试以增强可靠性。
+ 为了说明该解决方案，此模式提供了一个使用本地 Terraform 状态文件的示例 `redshift.tf` 文件。但是，对于生产环境，我们强烈建议您使用带有锁定机制的远程状态文件，以增强稳定性和协作性。
+ 有些 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)，然后选择相应服务的链接。

**产品版本**

该解决方案是在 [Amazon Redshift 补丁 179](https://docs.aws.amazon.com/redshift/latest/mgmt/cluster-versions.html#cluster-version-179) 上开发和测试的。

**代码存储库**

此模式的代码可在 GitHub [amazon-redshift-sql-deploy-terraform](https://github.com/aws-samples/amazon-redshift-sql-deploy-terraform) 存储库中找到。

## 架构
<a name="execute-redshift-sql-queries-using-terraform-architecture"></a>

下图阐明了 Terraform 如何通过处理不可重复和可重复的 SQL 查询来管理 Amazon Redshift 数据库资源。

![\[Terraform 使用 SQL 查询管理 Amazon Redshift 数据库资源的流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/0f4467ac-761b-4b6b-a32f-e18a2ca2245d/images/3b6ff9e8-e3d1-48ed-9fa1-4b14f7d3d65b.png)


图中显示以下步骤：

1. 在最初的 Amazon Redshift 集群部署期间，Terraform 会应用不可重复的 SQL 查询。

1. 开发人员提交对可重复的 SQL 查询的更改。

1. Terraform 监控可重复的 SQL 查询中的变化。

1. Terraform 将可重复的 SQL 查询应用到 Amazon Redshift 数据库。

此模式提供的解决方案是基于[适用于 Amazon Redshift 的 Terraform 模块](https://registry.terraform.io/modules/terraform-aws-modules/redshift/aws/latest)构建的。Terraform 模块预调配了 Amazon Redshift 集群和数据库。为了增强该模块，我们使用了`terraform_data`资源，这些资源调用自定义 Python 脚本来使用 Amazon [ExecuteStatement](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_ExecuteStatement.html)Redshift API 操作执行 SQL 查询。因此，该模块可以执行以下操作：
+ 预调配数据库后，使用 SQL 查询部署任意数量的数据库资源。
+ 持续监控可重复的 SQL 查询中的更改，并使用 Terraform 应用这些更改。

有关更多详细信息，请参阅[其他信息](#execute-redshift-sql-queries-using-terraform-additional)中的*解决方案演练*。

## 工具
<a name="execute-redshift-sql-queries-using-terraform-tools"></a>

**AWS 服务**
+ [Amazon Redshift](https://docs.aws.amazon.com/redshift/latest/mgmt/welcome.html) 是 AWS 云中的一项完全托管式 PB 级数据仓库服务。

**其他工具**
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。
+ [Python](https://www.python.org/) 是一种通用的编程语言，在此模式中用于执行 SQL 查询。

## 最佳实践
<a name="execute-redshift-sql-queries-using-terraform-best-practices"></a>
+ [亚马逊 Redshift 最佳实践](https://docs.aws.amazon.com/redshift/latest/dg/best-practices.html)
+ [使用 Amazon Redshift 数据 API 与Amazon Redshift 集群交互](https://aws.amazon.com/blogs/big-data/using-the-amazon-redshift-data-api-to-interact-with-amazon-redshift-clusters/)

## 操作说明
<a name="execute-redshift-sql-queries-using-terraform-epics"></a>

### 使用 Terraform 部署解决方案
<a name="deploy-the-solution-using-terraform"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| **克隆存储库。** | 要克隆包含用于预调配 Amazon Redshift 集群的 Terraform 代码的 Git 存储库，请使用以下命令。<pre>git clone https://github.com/aws-samples/amazon-redshift-sql-deploy-terraform.git</pre> | DevOps 工程师 | 
| **更新 Terraform 变量。** | 要根据您的特定要求自定义 Amazon Redshift 集群部署，请更新 `terraform.tfvars` 文件中的以下参数。<pre>region                    = "<AWS_REGION>"<br />cluster_identifier        = "<REDSHIFT_CLUSTER_IDENTIFIER>"<br />node_type                 = "<REDSHIFT_NODE_TYPE>"<br />number_of_nodes           = "<REDSHIFT_NODE_COUNT>"<br />database_name             = "<REDSHIFT_DB_NAME>"<br />subnet_ids                = "<REDSHIFT_SUBNET_IDS>"<br />vpc_security_group_ids    = "<REDSHIFT_SECURITY_GROUP_IDS>"<br />run_nonrepeatable_queries = true<br />run_repeatable_queries    = true<br />sql_path_bootstrap        = "<BOOTSTRAP_SQLS_PATH>"<br />sql_path_nonrepeatable    = "<NON-REPEATABLE_SQLS_PATH>"<br />sql_path_repeatable       = "<REPEATABLE_SQLS_PATH>"<br />sql_path_finalize         = "<FINALIZE_SQLS_PATH>"<br />create_random_password    = false<br />master_username           = "<REDSHIFT_MASTER_USERNAME>"</pre> | DevOps 工程师 | 
| 使用 Terraform 部署资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/execute-redshift-sql-queries-using-terraform.html) | DevOps 工程师 | 
| （可选）执行其他 SQL 查询。 | 示例存储库提供了几个 SQL 查询用于演示。要执行您自己的 SQL 查询，请将其添加到以下文件夹：`/bootstrap` `/nonrepeatable` `/repeatable` `/finalize` |  | 

### 监控 SQL 语句的执行
<a name="monitor-the-execution-of-sql-statements"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 监控 SQL 语句的部署。 | 您可以监控 Amazon Redshift 集群的 SQL 执行结果。有关显示 SQL 执行失败和成功执行的输出示例，请参阅[其他信息](#execute-redshift-sql-queries-using-terraform-additional)中的 *SQL 语句示例*。 | 数据库管理员、工程师 DevOps  | 
| 清理资源。 | 要删除 Terraform 部署的所有资源，请运行以下命令。<pre>terraform destroy</pre> | DevOps 工程师 | 

### 验证结果
<a name="validate-the-results"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证 Amazon Redshift 集群中的数据。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/execute-redshift-sql-queries-using-terraform.html) | DBA、AWS DevOps | 

## 相关资源
<a name="execute-redshift-sql-queries-using-terraform-resources"></a>

**AWS 文档**
+ [亚马逊 Redshift 预配置的集群](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html)
+ [亚马逊 Redshift 数据 API 问题疑难解答](https://docs.aws.amazon.com/redshift/latest/mgmt/data-api-troubleshooting.html)

**其他资源**
+ [命令：应用](https://developer.hashicorp.com/terraform/cli/commands/apply)（Terraform 文档）

## 附加信息
<a name="execute-redshift-sql-queries-using-terraform-additional"></a>

**解决方案演练**

要使用该解决方案，您必须以特定的方式组织您的 Amazon Redshift SQL 查询。所有 SQL 查询都必须存储在以 `.sql` 为扩展名的文件中。

在此模式提供的代码示例中，SQL 查询按以下文件夹结构进行组织。您可以修改代码（`sql-queries.tf` 和 `sql-queries.py`），使其适用于适合您独特使用案例的任何结构。

```
/bootstrap
     |- Any # of files
     |- Any # of sub-folders
/nonrepeatable
     |- Any # of files
     |- Any # of sub-folders
/repeatable
     /udf
          |- Any # of files
          |- Any # of sub-folders
     /table
          |- Any # of files
          |- Any # of sub-folders
     /view
          |- Any # of files
          |- Any # of sub-folders
     /stored-procedure
          |- Any # of files
          |- Any # of sub-folders
/finalize
     |- Any # of files
     |- Any # of sub-folders
```

鉴于上述文件夹结构，在 Amazon Redshift 集群部署期间，Terraform 按以下顺序执行查询：

1. `/bootstrap`

1. `/nonrepeatable`

1. `/repeatable`

1. `/finalize`

`/repeatable` 文件夹包含四个子文件夹：`/udf`、`/table`、`/view` 和 `/stored-procedure`。这些子文件夹指示 Terraform 执行 SQL 查询的顺序。

执行 SQL 查询的 Python 脚本是 `sql-queries.py`。首先，该脚本读取特定源目录的所有文件和子文件夹，例如 `sql_path_bootstrap` 参数。然后，该脚本通过调用 Amazon [ExecuteStatement](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_ExecuteStatement.html)Redshift API 操作来执行查询。一个文件中可能有一个或多个 SQL 查询。以下代码片段显示了 Python 函数，该函数针对 Amazon Redshift 集群执行存储在文件中的 SQL 语句。

```
def execute_sql_statement(filename, cluster_id, db_name, secret_arn, aws_region):
    """Execute SQL statements in a file"""
    redshift_client = boto3.client(
        'redshift-data', region_name=aws_region)
    contents = get_contents_from_file(filename),
    response = redshift_client.execute_statement(
        Sql=contents[0],
        ClusterIdentifier=cluster_id,
        Database=db_name,
        WithEvent=True,
        StatementName=filename,
        SecretArn=secret_arn
    )
    ...
```

Terraform 脚本 `sql-queries.tf` 创建用于调用 `sql-queries.py` 脚本的 [terraform\$1data](https://developer.hashicorp.com/terraform/language/resources/terraform-data) 资源。四个文件夹中的每一个都有一个 `terraform_data` 资源：`/bootstrap`、`/nonrepeatable`、`/repeatable`、和`/finalize`。以下代码片段显示了在 `/bootstrap` 文件夹中执行 SQL 查询的 `terraform_data` 资源。

```
locals {
  program               = "${path.module}/sql-queries.py"
  redshift_cluster_name = try(aws_redshift_cluster.this[0].id, null)
}

resource "terraform_data" "run_bootstrap_queries" {
  count      = var.create && var.run_nonrepeatable_queries && (var.sql_path_bootstrap != "") && (var.snapshot_identifier == null) ? 1 : 0
  depends_on = [aws_redshift_cluster.this[0]]

  provisioner "local-exec" {
    command = "python3 ${local.program} ${var.sql_path_bootstrap} ${local.redshift_cluster_name} ${var.database_name} ${var.redshift_secret_arn} ${local.aws_region}"
  }
}
```

您可以使用以下变量控制是否运行这些查询。如果您不想在 `sql_path_bootstrap`、`sql_path_nonrepeatable`、`sql_path_repeatable` 或 `sql_path_finalize` 中运行查询 ，请将其值设置为 `""`。

```
  run_nonrepeatable_queries = true
  run_repeatable_queries    = true
  sql_path_bootstrap        = "src/redshift/bootstrap"
  sql_path_nonrepeatable    = "src/redshift/nonrepeatable"
  sql_path_repeatable       = "src/redshift/repeatable"
  sql_path_finalize         = "src/redshift/finalize"
```

运行 `terraform apply` 时，无论脚本的结果如何，Terraform 都会考虑脚本完成后添加的 `terraform_data` 资源。如果某些 SQL 查询失败，而您想重新运行它们，则可以手动将该资源从 Terraform 状态中移除，然后重新运行 `terraform apply`。例如，以下命令将 `run_bootstrap_queries` 资源从 Terraform 状态中移除。

`terraform state rm module.redshift.terraform_data.run_bootstrap_queries[0]`

以下代码示例显示了 `run_repeatable_queries` 资源如何使用 [sha256 哈希值](https://developer.hashicorp.com/terraform/language/functions/sha256) 监视`repeatable`文件夹中的变化。如果更新了文件夹中的任何文件，Terraform 会将整个目录标记为更新。然后，Terraform 在下一 `terraform apply` 期间运行目录中的查询。

```
resource "terraform_data" "run_repeatable_queries" {
  count      = var.create_redshift && var.run_repeatable_queries && (var.sql_path_repeatable != "") ? 1 : 0
  depends_on = [terraform_data.run_nonrepeatable_queries]

  # Continuously monitor and apply changes in the repeatable folder
  triggers_replace = {
    dir_sha256 = sha256(join("", [for f in fileset("${var.sql_path_repeatable}", "**") : filesha256("${var.sql_path_repeatable}/${f}")]))
  }

  provisioner "local-exec" {
    command = "python3 ${local.sql_queries} ${var.sql_path_repeatable} ${local.redshift_cluster_name} ${var.database_name} ${var.redshift_secret_arn}"
  }
}
```

要完善代码，您可以实施一种机制，以检测并仅对 `repeatable` 文件夹中已更新的文件应用更改，而不是任意地将更改应用于所有文件。

**SQL 语句示例**

以下输出显示了 SQL 执行失败以及错误消息。

```
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): Executing: ["/bin/sh" "-c" "python3 modules/redshift/sql-queries.py src/redshift/nonrepeatable testcluster-1 db1 arn:aws:secretsmanager:us-east-1:XXXXXXXXXXXX:secret:/redshift/master_user/password-8RapGH us-east-1"]
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): -------------------------------------------------------------------
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): src/redshift/nonrepeatable/table/admin/admin.application_family.sql
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): -------------------------------------------------------------------
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): Status: FAILED
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): SQL execution failed.
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec): Error message: ERROR: syntax error at or near ")"
module.redshift.terraform_data.run_nonrepeatable_queries[0] (local-exec):   Position: 244
module.redshift.terraform_data.run_nonrepeatable_queries[0]: Creation complete after 3s [id=ee50ba6c-11ae-5b64-7e2f-86fd8caa8b76]
```

以下为成功执行后的输出示例。

```
module.redshift.terraform_data.run_bootstrap_queries[0]: Provisioning with 'local-exec'...
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): Executing: ["/bin/sh" "-c" "python3 modules/redshift/sql-queries.py src/redshift/bootstrap testcluster-1 db1 arn:aws:secretsmanager:us-east-1:XXXXXXXXXXXX:secret:/redshift/master_user/password-8RapGH us-east-1"]
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): -------------------------------------------------------------------
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): src/redshift/bootstrap/db.sql
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): -------------------------------------------------------------------
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): Status: FINISHED
module.redshift.terraform_data.run_bootstrap_queries[0] (local-exec): SQL execution successful.
module.redshift.terraform_data.run_bootstrap_queries[0]: Creation complete after 2s [id=d565ef6d-be86-8afd-8e90-111e5ea4a1be]
```

# 将 AWS Organizations 中整个组织的 AWS Backup 报告导出为 CSV 文件
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file"></a>

*Aromal Raj Jayarajan 和 Purushotham G K，Amazon Web Services*

## Summary
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-summary"></a>

此模式演示如何将 AWS Organizations 中整个组织的 AWS Backup 作业报告导出为 CSV 文件。该解决方案使用 AWS Lambda 和 Amazon EventBridge 根据状态对 AWS Backup 任务报告进行分类，这有助于配置基于状态的自动化。

AWS Backup 帮助组织集中管理和自动化跨 Amazon Web Services、云中和本地的数据保护。但是，对于在 AWS Organizations 中配置的 AWS Backup 作业，合并报告仅在每个组织管理账户的 AWS 管理控制台 中可用。将此报告置于管理账户之外可以减少审核所需工作量并扩大自动化、通知和警报的范围。

## 先决条件和限制
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ AWS Organizations 中、至少包含一个管理账户和一个成员账户的活跃 [组织](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_tutorials_basic.html)
+ AWS Organizations 组织级的 AWS Backup 配置（若要获取更多信息，请参见 AWS Blog 中的[使用 AWS Backup 跨 Amazon Web Services 大规模自动化集中备份](https://aws.amazon.com/blogs/storage/automate-centralized-backup-at-scale-across-aws-services-using-aws-backup/)）
+ [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)，已在本地计算机上安装并配置

**限制**

此模式中提供的解决方案可识别仅为 AWS Backup 作业配置的 AWS 资源。该报告无法识别未配置为通过 AWS Backup 备份的 AWS 资源。

## 架构
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-architecture"></a>

**目标技术堆栈**
+ AWS Backup
+ AWS CloudFormation
+ Amazon EventBridge
+ AWS Lambda
+ AWS Security Token Service (AWS STS)
+ Amazon Simple Storage Service（Amazon S3）
+ AWS Identity and Access Management (IAM)

**目标架构**

下图显示了将 AWS Organizations 中整个组织的 AWS Backup 作业报告导出为 CSV 文件的示例工作流。

![\[使用 EventBridge Lambda、AWS STS 和 IAM 以 CSV 格式从整个组织中导出 AWS Backup 任务报告。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/74955aad-cc6d-488b-aa34-ae43f50fec60/images/5c39c79f-e731-4ad0-b404-51ebe0976420.png)


下图显示了如下工作流：

1. 计划 EventBridge 事件规则调用成员（报告）AWS 账户中的 Lambda 函数。

1. 然后，Lambda 函数使用 AWS STS 承担拥有连接管理账户所需权限的 IAM 角色。

1. Lambda 函数执行以下操作：
   + 从 AWS Backup 服务请求合并的 AWS Backup 作业报告
   + 根据 AWS Backup 作业状态对结果进行分类
   + 将响应转换到 CSV 格式文件
   + 将结果上传到报告账户中的 Amazon S3 存储桶，该存储桶位于根据创建日期标记的文件夹内

## 工具
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-tools"></a>

**工具**
+ [AWS Backup](https://docs.aws.amazon.com/aws-backup/latest/devguide/whatisbackup.html) 是一项完全托管式服务，帮助您在云中以及在本地集中管理和自动执行各种 Amazon Web Services 中的数据保护。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可帮助您设置 AWS 资源，快速一致地配置这些资源，并在 AWS 账户和区域的整个生命周期中对其进行管理。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一项无服务器事件总线服务，可帮助您将应用程序与来自各种来源的实时数据连接起来。例如，AWS Lambda 函数、使用 API 目标的 HTTP 调用端点或其他 Amazon Web Services account 中的事件总线。
+ [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)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**代码**

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

## 最佳实践
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-best-practices"></a>
+ [Amazon S3 安全最佳实践](https://docs.aws.amazon.com/AmazonS3/latest/userguide/security-best-practices.html)（*Amazon S3 用户指南*）
+ [AWS Lambda 函数使用最佳实践](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)（*AWS Lambda 开发人员指南*）
+ [管理账户的最佳实践](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_best-practices_mgmt-acct.html)（*AWS Organizations 用户指南*）

## 操作说明
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-epics"></a>

### 部署解决方案组件
<a name="deploy-the-solution-components"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆 GitHub 存储库。 | 在终端窗口中运行以下命令来克隆 GitHub [aws-backup-report-generator](https://github.com/aws-samples/aws-backup-report-generator)存储库：<pre>git clone https://github.com/aws-samples/aws-backup-report-generator.git</pre>有关更多信息，请参阅 GitHub 文档[中的克隆存储库](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository)。 | AWS DevOps， DevOps 工程师 | 
| 在成员（报告）Amazon Web Services account 中部署解决方案组件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.html) | DevOps 工程师，AWS DevOps | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 请确保 EventBridge 规则在测试之前运行。 | 确保 EventBridge 规则通过等待至少 24 小时或在 CloudFormation 模板的 t **emplate-** reporting.yml 文件中增加报告频率来运行。**增加报告频率**[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.html) | AWS DevOps， DevOps 工程师 | 
| 检查 Amazon S3 存储桶，以获取生成的报告。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.html) | AWS DevOps， DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 从成员（报告）账户中删除解决方案组件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.html) | AWS DevOps， DevOps 工程师 | 
| 从管理账户中删除解决方案组件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.html) | AWS DevOps， DevOps 工程师 | 

## 相关资源
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-resources"></a>
+ [教程：将 AWS Lambda 与计划的事件结合使用](https://docs.aws.amazon.com/lambda/latest/dg/services-cloudwatchevents-tutorial.html)（AWS Lambda 文档）
+ [创建计划事件以运行 AWS Lambda 函数（用于 JavaScript 文档](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/scheduled-events-invoking-lambda-example.html)的 AWS 开发工具包）
+ [IAM 教程：使用 IAM 角色委派跨 AWS 账户的访问权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html)（IAM 文档）
+ [AWS Organizations 术语和概念](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_getting-started_concepts.html)（AWS Organizations 文档）
+ [使用 AWS Backup 控制台创建报告计划](https://docs.aws.amazon.com/aws-backup/latest/devguide/create-report-plan-console.html)（AWS Backup 文档）
+ [创建审计报告](https://docs.aws.amazon.com/aws-backup/latest/devguide/create-audit-report.html)（AWS Backup 文档）
+ [创建按需报告](https://docs.aws.amazon.com/aws-backup/latest/devguide/create-on-demand-reports.html)（AWS Backup 文档）
+ [什么是 AWS Backup？](https://docs.aws.amazon.com/aws-backup/latest/devguide/whatisbackup.html) （AWS Backup 文档）
+ [使用 AWS Backup 在 AWS 服务中大规模自动进行集中备份](https://aws.amazon.com/blogs/storage/automate-centralized-backup-at-scale-across-aws-services-using-aws-backup/)（AWS Blog 文章）

# 将亚马逊 EC2 实例列表的标签导出到 CSV 文件
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file"></a>

*Sida Ju 和 Pac Joonhyun，Amazon Web Services*

## Summary
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-summary"></a>

此模式显示如何以编程方式将亚马逊弹性计算云 (Amazon EC2) 实例列表的标签导出到 CSV 文件。

通过使用提供的示例 Python 脚本，您可以缩短按特定标签对您的 Amazon EC2 实例进行审查和分类所需的时间。例如，您可使用该脚本来快速识别您的安全团队已标记为需要进行软件更新的实例列表并对其进行分类。

## 先决条件和限制
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-prereqs"></a>

**先决条件**
+ 已安装并配置 Python 3
+ AWS 命令行界面（AWS CLI）已安装并配置

**限制**

此模式中提供的示例 Python 脚本只能根据以下属性搜索 Amazon EC2 实例：
+ 实例 IDs
+ 私有 IPv4 地址
+ 公共 IPv4 地址

## 工具
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-tools"></a>
+ [Python](https://www.python.org/) 是通用的计算机编程语言。
+ [virtualenv](https://virtualenv.pypa.io/en/latest/) 可以帮助您创建隔离的 Python 环境。
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它可帮助您通过命令行 Shell 中的命令与 Amazon Web Services 交互。

**代码存储库**

此模式的 Python 脚本示例，可在 GitHub [搜索 ec2](https://github.com/aws-samples/search-ec2-instances-export-tags) 存储库中找到。instances-export-tags

## 操作说明
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-epics"></a>

### 安装并配置先决条件
<a name="install-and-configure-the-prerequisites"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆 GitHub 存储库。 | 如果您在运行 AWS CLI 命令时收到错误，[请确认您使用的是最新 AWS CLI 版本](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-troubleshooting.html)。在终端 GitHub [窗口中运行以下 Git 命令来克隆 search-ec2 instances-export-tags](https://github.com/aws-samples/search-ec2-instances-export-tags) 存储库：<pre>git clone https://github.com/aws-samples/search-ec2-instances-export-tags.git</pre> | DevOps 工程师 | 
| 安装和激活 virtualenv。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file.html)有关更多信息，请参阅 [virtualenv 用户指南](https://virtualenv.pypa.io/en/latest/user_guide.html)。 | DevOps 工程师 | 
| 安装依赖项。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file.html) | DevOps 工程师 | 
| 配置 AWS 命名配置文件。 | 如果您尚未配置一个 AWS 命名配置文件，其中包含运行脚本所需凭证。要创建命名配置文件，请运行 [aws configure](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-methods) 命令。有关更多信息，请参阅 AWS CLI 文档中的[使用命名配置文件](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-using-profiles)。 | DevOps 工程师 | 

### 配置并运行 Python 脚本
<a name="configure-and-run-the-python-script"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建输入文件。 | 创建一个输入文件，其中包含您希望脚本搜索和导出标签的 Amazon EC2 实例列表。您可以列出实例 IDs、私有 IPv4 地址或公有 IPv4 地址。确保每个 Amazon EC2 实例在输入文件中单独列出。**输入文件示例**<pre>1    i-0547c351bdfe85b9f<br />2    54.157.194.156<br />3    172.31.85.33<br />4    54.165.198.144<br />5    i-0b6223b5914111a4b<br />6    172.31.85.44<br />7    54.165.198.145<br />8    172.31.80.219<br />9    172.31.94.199</pre> | DevOps 工程师 | 
| 运行 Python 脚本。 | 通过在终端中运行以下命令运行脚本：<pre>python search_instances.py -i INPUTFILE -o OUTPUTFILE -r REGION [-p PROFILE]</pre>将 `INPUTFILE` 替换为您的输入文件的名称。将 `OUTPUTFILE` 替换为您要为 CSV 输出文件提供的名称。`REGION`替换为您的亚马逊 EC2 资源所在的 AWS 区域。如果您使用的是 AWS 命名的配置文件，请将 `PROFILE` 替换为您正在使用的命名配置文件。要获取支持的参数及其描述的列表，请运行以下命令：<pre>python search_instances.py -h</pre>要了解更多信息并查看输出文件示例，请参阅 s GitHub [earch-instances-export-tags ec2](https://github.com/aws-samples/search-ec2-instances-export-tags) 存储库中的`README.md`文件。 | DevOps 工程师 | 

## 相关资源
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-resources"></a>
+ [配置 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)（*AWS CLI 用户指南*）

# 使用 Troposphere 生成包含 AWS Config 托管规则的 AWS CloudFormation 模板
<a name="generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere"></a>

*Lucas Nation 和 Freddie Wilson，Amazon Web Services*

## Summary
<a name="generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere-summary"></a>

许多组织使用 [AWS Config 托管](https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config_use-managed-rules.html)规则来评估其 Amazon Web Services (AWS) 资源是否符合常见的最佳实践。但是，维护这些规则可能很耗时，这种模式可以帮助您利用 Python 库 [Troposphere](https://troposphere.readthedocs.io/en/latest/quick_start.html) 生成和管理 AWS Config 托管规则。

该模式使用 Python 脚本将包含 AWS 托管规则的 Microsoft Excel 电子表格转换为 AWS CloudFormation 模板，从而帮助您管理 AWS Config 托管规则。Troposphere 充当基础设施即代码（IaC），这意味着您可以使用托管规则更新 Excel 电子表格，而不是使用 JSON 或 YAML 格式的文件。然后，您可以使用该模板启动一个 AWS CloudFormation 堆栈，该堆栈在您的 AWS 账户中创建和更新托管规则。

AWS CloudFormation 模板使用 Excel 电子表格定义每个 AWS Config 托管规则，并帮助您避免在 AWS 管理控制台中手动创建单个规则。该脚本将每个托管规则的参数默认为一个空字典，作用域的`ComplianceResourceTypes`默认值为`THE_RULE_IDENTIFIER.template file`*。* 有关规则标识符的更多信息，请参阅 [AWS Config 文档中的使用 AWS CloudFormation 模板创建 AWS Config 托管规则](https://docs.aws.amazon.com/config/latest/developerguide/aws-config-managed-rules-cloudformation-templates.html)。

## 先决条件和限制
<a name="generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 熟悉使用 AWS CloudFormation 模板创建 AWS Config 托管规则。有关这方面的更多信息，请参阅 [AWS Config 文档中的使用 AWS CloudFormation 模板创建 AWS Config 托管规则](https://docs.aws.amazon.com/config/latest/developerguide/aws-config-managed-rules-cloudformation-templates.html)。 
+ Python 3，已安装并配置。有关这方面的更多信息，请参阅 [Python 文档](https://www.python.org/)。
+ 现有集成式开发环境（IDE）。 
+ 在示例 `excel_config_rules.xlsx` Excel 电子表格（附后OUs）的列中标识您的组织单位 ()。

## 操作说明
<a name="generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere-epics"></a>

### 自定义和配置 AWS Config 托管规则
<a name="customize-and-configure-the-aws-config-managed-rules"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新 Excel 电子表格示例。 | 下载示例 `excel_config_rules.xlsx` Excel 电子表格（附件），并将其标记为要使用的 AWS Config 托管规则 `Implemented`。 标记为的规则`Implemented`将添加到 AWS CloudFormation 模板中。 | 开发者版 | 
| （可选）使用 AWS Config 规则参数更新 config\$1rules\$1params.json 文件。 | 某些 AWS Config 托管规则需要参数，应使用 `--param-file` 选项将其作为 JSON 文件传递到 Python 脚本。例如，`access-keys-rotated` 托管规则使用以下 `maxAccessKeyAge` 参数：<pre>{<br />         "access-keys-rotated": {<br />             "InputParameters": {<br />                 "maxAccessKeyAge": 90<br />             }<br />         }<br />     }</pre>在此示例参数中，`maxAccessKeyAge` 设置为 90 天。该脚本读取参数文件并添加它找到的任何 `InputParameters`。 | 开发者版 | 
| （可选）使用 AWS Config 更新 config\$1rules\$1params.json 文件。 ComplianceResourceTypes | 默认情况下，Python 脚本会从 AWS 定义的模板中检索 `ComplianceResourceTypes`。如果您想覆盖特定 AWS Config 托管规则范围，则需要使用 `--param-file` 选项将其作为 JSON 文件传递给 Python 脚本。例如，以下示例代码显示了如何将 `ec2-volume-inuse-check` 的 `ComplianceResourceTypes` 设置为 `["AWS::EC2::Volume"]` 列表：<pre>{<br />         "ec2-volume-inuse-check": {<br />             "Scope": {<br />                 "ComplianceResourceTypes": [<br />                     "AWS::EC2::Volume"<br />                 ]<br />             }<br />         }<br />     }</pre> | 开发者版 | 

### 运行 Python 脚本
<a name="run-the-python-script"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 从 requirements.txt 文件处安装 pip 程序包。 | 下载 `requirements.txt` 文件（附件），然后在 IDE 中运行以下命令来安装 Python 程序包：`pip3 install -r requirements.txt` | 开发者版 | 
| 运行 Python 脚本。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere.html)您还可以添加以下可选参数：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere.html) | 开发者版 | 

### 部署 AWS Config 托管规则
<a name="deploy-the-aws-config-managed-rules"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动 AWS CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/generate-an-aws-cloudformation-template-containing-aws-config-managed-rules-using-troposphere.html) | 开发者版 | 

## 附件
<a name="attachments-07c1cfff-fc9e-4a1f-bd36-48f025808bd8"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/07c1cfff-fc9e-4a1f-bd36-48f025808bd8/attachments/attachment.zip)

# 为 SageMaker 笔记本实例提供对另一个 AWS 账户中 CodeCommit 存储库的临时访问权限
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account"></a>

*Helge Aufderheide，Amazon Web Services*

## Summary
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-summary"></a>

此模式演示如何授予 Amazon SageMaker 笔记本实例和用户临时访问其他 AWS 账户中的 AWS CodeCommit 存储库的权限。此模式还显示了如何为每个实体可以在每个存储库上执行的特定操作授予精细权限。

组织通常将存储 CodeCommit 库存储在与托管其开发环境的账户不同的 AWS 账户中。这种多账户设置有助于控制对存储库的访问权限并降低意外删除存储库的风险。要授予这些跨账户权限，最好做法是使用 AWS Identity and Acccess Management (IAM) 角色。然后，每个 Amazon Web Services account 中预定义的 IAM 身份可以临时代入这些角色，从而在各账户之间创建受控的信任链。

**注意**  
您可以应用类似的程序向其他 IAM 身份授予对 CodeCommit 存储库的跨账户访问权限。有关更多信息，请参阅 AWS * CodeCommit 用户指南*中的[使用角色配置对 AWS CodeCommit 存储库的跨账户访问权限](https://docs.aws.amazon.com/codecommit/latest/userguide/cross-account.html)。

## 先决条件和限制
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-prereqs"></a>

**先决条件**
+ 具有 CodeCommit 存储库的活跃 AWS 账户（*账户 A*）
+ 带有 SageMaker 笔记本实例的第二个活跃 AWS 账户（*账户 B*）
+ 一个具有在账户 A 中创建和修改 IAM 角色的足够权限的 AWS 用户
+ 第二个具有在账户 B 中创建和修改 IAM 角色的足够权限的 AWS 用户

## 架构
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-architecture"></a>

下图显示了向 SageMaker 笔记本实例和一个 AWS 账户中的用户授予跨账户访问 CodeCommit 存储库权限的示例工作流程：

![\[跨账户访问的工作流程 CodeCommit\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/54d0fdb3-6d25-4433-9f67-c87846633d61/images/97a799af-ce88-4495-a61c-d0cd22493ce2.png)


下图显示了如下工作流：

1. 账户 B 中的 AWS 用户角色和 SageMaker 笔记本实例角色采用已[命名的个人资料](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-using-profiles)。

1. 指定配置文件的权限策略在账户 A 中指定 CodeCommit 访问角色，然后该配置文件将担任该角色。

1. 账户 A 中的 CodeCommit 访问角色的信任策略允许账户 B 中的指定配置文件担任 CodeCommit 访问角色。

1. 账户 A 中 CodeCommit 存储库的 IAM 权限策略允许 CodeCommit 访问角色访问 CodeCommit 存储库。

**技术堆栈**
+ CodeCommit
+ Git
+ IAM
+ pip
+ SageMaker

## 工具
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-tools"></a>
+ [AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/welcome.html) 是一项版本控制服务，可帮助您私下存储和管理 Git 存储库，而无需管理自己的源代码控制系统。
+ [AWS Identity and Access Management (AWS IAM) ](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)通过控制验证和授权使用您 AWS 资源的用户，帮助您安全地管理对您 AWS 资源的访问。
+ [Git](https://git-scm.com/) 是分布式版本控制系统，用于追踪软件开发期间源代码的更改。
+ [git-remote-codecommit](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-git-remote-codecommit.html)是一个通过扩展 Git 来帮助您从 CodeCommit 存储库中推送和提取代码的实用工具。
+ [pip](https://pypi.org/project/pip/) 是 Python 的软件包安装程序。您可以使用 pip 来安装来自 Python 软件包索引和其他索引中的软件包。

## 最佳实践
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-best-practices"></a>

在使用 IAM policy设置权限时，请仅授予执行任务所需许可。有关更多信息，请参阅 IAM 文档中的[应用最低权限许可](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)。

在实施此模式时，请务必执行以下操作：
+ 确认 IAM 原则仅具有在每个存储库中执行特定必要操作所需权限。例如，建议允许经批准的 IAM 原则将更改推送和合并到特定的存储库分支，但只能请求合并到受保护的分支。
+ 确认根据每个项目各自的角色和职责，为 IAM 角色分配不同的 IAM 原则。例如，开发人员将拥有与发布管理员或 AWS 管理员不同的访问权限。

## 操作说明
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-epics"></a>

### 配置 IAM 角色
<a name="configure-the-iam-roles"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置 CodeCommit 访问角色和权限策略。 | 要自动执行本长篇故事中记录的手动设置过程，****您可以使用 A [WS CloudFormation 模板](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-guide.html)。在包含 CodeCommit 存储库的账户（*账户 A*）中，执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.html)在将此设置移至生产环境之前，最佳实践是自己编写应用[最低权限许可](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)的 IAM 策略。有关更多信息，请参阅此模式的**其他信息**部分。 | 常规 AWS、AWS DevOps | 
| 向账户 B 中的 SageMaker 笔记本实例角色授予在账户 A 中担任 CodeCommit 访问角色的权限。 | 在包含 SageMaker 笔记本实例的 IAM 角色的*账户（账户 B）中，*执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.html)要查看存储库的 Amazon 资源名称 (ARN)，请参阅 AW *S CodeCommit 用户*指南中的[查看 CodeCommit 存储库详情](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-view-repository-details.html)。 | 常规 AWS、AWS DevOps | 

### 在账户 B 中设置您的 SageMaker 笔记本实例
<a name="set-up-your-sagemaker-notebook-instance-in-account-b"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 AWS SageMaker 笔记本实例上设置用户配置文件以代入账户 A 中的角色。 | [请确认已安装最新版本的 AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。在包含 SageMaker 笔记本实例的账户（*账户 B）中，*执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.html)<pre>------.aws/config--------------<br />[profile remoterepouser]<br />role_arn = arn:aws:iam::<ID of Account A>:role/<rolename><br />role_session_name = remoteaccesssession<br />region = eu-west-1<br />credential_source  = Ec2InstanceMetadata<br />----------------------------------</pre> | 常规 AWS、AWS DevOps | 
| 安装 git-remote-codecommit 实用程序。 | 按照 *AWS CodeCommit 用户指南*中的[步骤 2：安装 git-remote-codecommit](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-git-remote-codecommit.html#setting-up-git-remote-codecommit-install)中的说明进行操作。 | 数据科学家 | 

### 访问存储库
<a name="access-the-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 Git 命令访问 CodeCommit 存储库或 SageMaker。 | **要使用 Git**，请执行以下操作在账户 B 中扮演 SageMaker 笔记本实例角色的 IAM 委托人现在可以运行 Git 命令来访问账户 A 中的 CodeCommit 存储库。例如，用户可以运行`git clone``git pull`、和`git push`之类的命令。有关说明，请参阅 [AWS * CodeCommit 用户指南中的 Connect 到 AWS CodeCommit * 存储库](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)。有关如何使用 Git 的信息 CodeCommit，请参阅 [AWS * CodeCommit 用户指南 CodeCommit中的 AWS* 入门](https://docs.aws.amazon.com/codecommit/latest/userguide/getting-started-cc.html)。**要使用 SageMaker**要从 SageMaker 控制台使用 Git，必须允许 Git 从 CodeCommit 仓库中检索证书。有关说明，请参阅 SageMaker 文档[中的将不同 AWS 账户中的 CodeCommit 存储库与笔记本实例关联](https://docs.aws.amazon.com/sagemaker/latest/dg/nbi-git-cross.html)。 | Git，bash 控制台 | 

## 相关资源
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-resources"></a>
+ [使用角色配置对 AWS CodeCommit 存储库的跨账户访问权限](https://docs.aws.amazon.com/codecommit/latest/userguide/cross-account.html)（AWS CodeCommit 文档）
+ [IAM 教程：使用 IAM 角色委派跨 AWS 账户的访问权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html)（IAM 文档）

## 附加信息
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-additional"></a>

**将 CodeCommit 权限限制为特定操作**

要限制 IAM 委托人可以在 CodeCommit 存储库中执行的操作，请修改 CodeCommit 访问策略中允许的操作。

有关 CodeCommit API 操作的更多信息，请参阅 *AWS CodeCommit 用户指南*中的[CodeCommit 权限参考](https://docs.aws.amazon.com/codecommit/latest/userguide/auth-and-access-control-permissions-reference.html)。

**注意**  
您还可以编辑 [AWSCodeCommitPowerUser](https://docs.aws.amazon.com/codecommit/latest/userguide/security-iam-awsmanpol.html#managed-policies-poweruser)AWS 托管策略以适应您的使用案例。

**限制对特定仓库的 CodeCommit 权限**

要创建只有特定用户才能访问多个代码存储库的多租户环境，请执行以下操作：

1. 在账户 A 中创建多个 CodeCommit 访问角色。然后，将每个访问角色的信任策略配置为允许账户 B 中的特定用户代入该角色。

1. 通过在每个 CodeCommit 访问角色的策略中添加 **“资源”** 条件，限制每个角色可以担任的代码存储库。

**限制 IAM 委托人访问特定 CodeCommit 存储库的 “资源” 条件示例**

```
"Resource" : [<REPOSITORY_ARN>,<REPOSITORY_ARN> ]
```

**注意**  
为了帮助识别和区分同一个 AWS 账户中的多个代码存储库，您可以为存储库的名称分配不同的前缀。例如，您可以使用与不同开发人员组对应的前缀来命名代码存储库，例如 **myproject-subproject1-repo1** 和 **myproject-subproject2-repo1**。然后，您可以根据为每个开发人员组分配的前缀为其创建一个 IAM 角色。例如，您可以创建一个名为 **myproject-subproject1-repoaccess** 的角色，并授予其访问包含前缀 **myproject-subproject1** 的所有代码存储库的权限。

**引用包含特定前缀的代码存储库 ARN 的“资源”条件示例**

```
"Resource" : arn:aws:codecommit:<region>:<account-id>:myproject-subproject1-*
```

# 为多 DevOps 账户环境实施 GitHub Flow 分支策略
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments"></a>

*Mike Stephens 和 Abhilash Vinod，Amazon Web Services*

## Summary
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-summary"></a>

管理源代码存储库时，不同的分支策略会影响开发团队使用的软件开发和发布流程。常见分支策略的示例包括 Trunk、 GitHub Flow 和 Gitflow。这些策略使用不同的分支，并且在每种环境中执行的活动也各不相同。正在实施 DevOps 流程的组织将受益于可视化指南，以帮助他们了解这些分支策略之间的区别。在组织中使用此视觉对象可以帮助开发团队协调工作并遵循组织标准。此模式提供了这种视觉效果，并描述了在您的组织中实施 GitHub Flow 分支策略的过程。

这种模式是关于为具有多个 AWS 账户分支机构的组织选择和实施 DevOps 分支策略的文档系列的一部分。本系列旨在帮助您从一开始就应用正确的策略和最佳实践，以简化您在云中的体验。 GitHub Flow 只是您的组织可以使用的一种可能的分支策略。本文档系列还涵盖了[中继](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-trunk-branching-strategy-for-multi-account-devops-environments.html)和 [Gitflow](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) 分支模型。如果你还没有这样做，我们建议你先查看[为多账户 DevOps 环境选择 Git 分支策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)，然后再按此模式实施指南。请务必谨慎选择适合组织的分支策略。

本指南提供了一个示意图，显示了组织如何实施 GitHub Flow 策略。建议您查看《Well-Ar [ DevOps chitec AWS ted 指南》，以查看最佳实](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)践。此模式包括 DevOps 流程中每个步骤的推荐任务、步骤和限制。

## 先决条件和限制
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-prereqs"></a>

**先决条件**
+ Git，[已安装](https://git-scm.com/downloads)。这可用作源代码存储库工具。
+ Draw.io，[已安装](https://github.com/jgraph/drawio-desktop/releases)。此应用程序可用于查看和编辑图表。

## 架构
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-architecture"></a>

**目标架构**

下图的使用方法与[旁氏表](https://en.wikipedia.org/wiki/Punnett_square)类似（维基百科）。您可以将垂直轴上的分支与水平轴上的 AWS 环境对齐，以确定在每个场景中要执行的操作。这些数字表示工作流中各项操作的顺序。此示例可引导您了解从 `feature` 分支到在生产环境中部署的整个过程。

![\[每个分支和环境中的 GitHub Flow 活动的 Punnett 方块。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/780a5bce-3cd2-4092-8537-b7a77c3d6b8d/images/8a2a774a-cd85-466e-838e-a9a1f3b58a63.png)


有关 GitHub Flow 方法中的 AWS 账户、环境和分支的更多信息，请参阅[为多账户 DevOps 环境选择 Git 分支策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach)。

**自动化和扩展**

持续集成和持续交付（CI/CD) is the process of automating the software release lifecycle. It automates much or all of the manual processes traditionally required to get new code from an initial commit into production. A CI/CD pipeline encompasses the sandbox, development, testing, staging, and production environments. In each environment, the CI/CD pipeline provisions any infrastructure that is needed to deploy or test the code. By using CI/CD, development teams can make changes to code that are then automatically tested and deployed. CI/CD管道）还通过强制执行一致性、标准、最佳实践以及功能接受和部署的最低接受程度，为开发团队提供管理和护栏。 有关更多信息，请参阅[上的 “练习持续集成和持续交付” AWS](https://docs.aws.amazon.com/whitepapers/latest/practicing-continuous-integration-continuous-delivery/welcome.html)。

AWS 提供了一套旨在帮助您构建 CI/CD 管道的开发人员服务。例如，[AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)是一项完全托管的持续交付服务，可帮助您实现发布管道的自动化，从而实现快速可靠的应用程序和基础设施更新。 [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)编译源代码、运行测试和生成 ready-to-deploy软件包。有关更多信息，请参阅[上的开发者工具 AWS](https://aws.amazon.com/products/developer-tools/)。

## 工具
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-tools"></a>

**AWS 服务和工具**

AWS 提供了一套开发者服务，你可以用它们来实现这种模式：
+ [AWS CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/welcome.html) 是一项高度可扩展的托管式构件存储库服务，有助于您存储和共享用于应用程序开发的软件包。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管式构建服务，可编译源代码、运行单元测试和生成部署就绪的构件。
+ [AWS CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)自动部署到亚马逊弹性计算云 (Amazon EC2)、本地实例、 AWS Lambda 函数或亚马逊弹性容器服务 (Amazon ECS) 服务。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可帮助您快速对软件发布过程的不同阶段进行建模和配置，并自动执行持续发布软件变更所需步骤。

**其他工具**
+ [Draw.io 桌面](https://github.com/jgraph/drawio-desktop/releases)是用于制作流程图和图表的应用程序。代码存储库包含 Draw.io 的 .drawio 格式模板。
+ [Figma](https://www.figma.com/design-overview/) 是一款专为协作而打造的在线设计工具。代码存储库包含 Figma 的 .fig 格式模板。

**代码存储库**

此模式下图表的源文件可在 GitHub [Git GitHub Flow 分支策略存储库中找](https://github.com/awslabs/git-branching-strategies-for-multiaccount-devops/tree/main/github-flow)到。其包括采用 PNG、draw.io 和 Figma 格式的文件。您可以修改这些图表，以为组织的流程提供支持。

## 最佳实践
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-best-practices"></a>

遵循 Well-Architect [AWS e DevOps d 指南和为多账户环境](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)[选择 Git 分支](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)策略中的最佳实践和建议。 DevOps 它们可以帮助您有效地实施 GitHub 基于 Flow 的开发、促进协作、提高代码质量和简化开发流程。

## 操作说明
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-epics"></a>

### 查看 GitHub Flow 工作流程
<a name="reviewing-the-github-flow-workflows"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看标准 GitHub 流程流程。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 工程师 | 
| 查看错误修复 GitHub 流程流程。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 工程师 | 
| 查看修补程序 GitHub 流程流程。 | GitHub Flow 旨在实现持续交付，在这种交付中，可以频繁可靠地将代码更改部署到更高的环境中。关键在于，每个 `feature` 分支都可以随时部署。类似于 `feature` 或 `bugfix` 分支的 `Hotfix` 分支可以遵循与其他分支相同的过程。但是，考虑到其紧迫性，修补程序通常具有更高的优先级。根据团队的政策和情况的即时性，可以加快流程中的某些步骤。例如，修补程序的代码审查可能加速进行。因此，尽管修补程序过程与功能或错误修复过程相似，但由于围绕修补程序的紧迫性，可能需要修改程序遵守情况。务必制定有关管理修补程序的指导原则，以确保高效、安全地处理修补程序。 | DevOps 工程师 | 

## 问题排查
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 分支冲突 |  GitHub Flow 模型可能出现的一个常见问题是，需要在生产环境中进行修补程序，但需要在修改相同资源的`feature``bugfix`、或`hotfix`分支中进行相应的更改。我们建议您经常将来自 `main` 更改合并到较低的分支中，以避免在合并到 `main` 时发生重大冲突。 | 
| 团队成熟度 | GitHub Flow 鼓励每天部署到更高的环境，采用真正的持续集成和持续交付 (CI/CD)。团队必须具备工程成熟度，才能构建功能并为其创建自动化测试。在审批更改之前，团队必须对合并请求进行详尽的审查。这就打造了一种强大的工程文化，促进了开发过程的质量、问责制和效率。 | 

## 相关资源
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-resources"></a>

本指南不包括针对 Git 的培训；但是，如果您需要这种培训，则可以在互联网上找到许多可用的高质量的资源。我们建议从 [Git 文档](https://git-scm.com/doc)网站开始。

以下资源可以帮助您完成 GitHub Flow 分支之 AWS 云旅。

**AWS DevOps 指导**
+ [AWS DevOps 指南](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)
+ [AWS 部署管道参考架构](https://pipelines.devops.aws.dev/)
+ [什么是 DevOps？](https://aws.amazon.com/devops/what-is-devops/)
+ [DevOps resources](https://aws.amazon.com/devops/resources/)

**GitHub 流量指导**
+ [GitHub Flow 快速入门教程](https://docs.github.com/en/get-started/using-github/github-flow) () GitHub
+ [为什么 GitHub Flow？](https://githubflow.github.io/)

**其他资源**
+ [十二要素应用程序方法论](https://12factor.net/)（12factor.net）

# 为多账户环境实施 Gitflow 分支策略 DevOps
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments"></a>

*迈克·斯蒂芬斯、斯蒂芬 DiCato、Abhilash Vinod 和 Amazon Web Services 的 Tim Wondergem*

## Summary
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-summary"></a>

管理源代码存储库时，不同的分支策略会影响开发团队使用的软件开发和发布流程。常见分支策略的示例包括 Trunk、Gitflow 和 Flow。 GitHub 这些策略使用不同的分支，并且在每种环境中执行的活动也各不相同。正在实施 DevOps 流程的组织将受益于可视化指南，以帮助他们了解这些分支策略之间的区别。在组织中使用此视觉对象可以帮助开发团队协调工作并遵循组织标准。此模式提供了该视觉对象，并描述了在组织中实施 Gitflow 分支策略的过程。

这种模式是关于为具有多个 AWS 账户分支机构的组织选择和实施 DevOps 分支策略的文档系列的一部分。该系列旨在帮助您从一开始就应用正确的策略和最佳实践，以简化您的云体验。Gitflow 只是您的组织可以使用的一种潜在分支策略。本文档系列还涵盖了 Tr [unk](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-trunk-branching-strategy-for-multi-account-devops-environments.html) 和 [GitHub Flow](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.html) 分支模型。如果你还没有这样做，我们建议你先查看[为多账户 DevOps 环境选择 Git 分支策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)，然后再按此模式实施指南。请务必谨慎选择适合组织的分支策略。

本指南提供了图表，其中显示了组织如何实施 Gitflow 策略。建议您查看《Well-Ar [ DevOps chitec AWS ted 指南》，以查看最佳实](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)践。此模式包括 DevOps 流程中每个步骤的推荐任务、步骤和限制。

## 先决条件和限制
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-prereqs"></a>

**先决条件**
+ Git，[已安装](https://git-scm.com/downloads)。这可用作源代码存储库工具。
+ Draw.io，[已安装](https://github.com/jgraph/drawio-desktop/releases)。此应用程序可用于查看和编辑图表。
+ （可选）Gitflow 插件，[已安装](https://github.com/nvie/gitflow)。

## 架构
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-architecture"></a>

**目标架构**

下图的使用方法与[旁氏表](https://en.wikipedia.org/wiki/Punnett_square)类似（维基百科）。您可以将垂直轴上的分支与水平轴上的 AWS 环境对齐，以确定在每个场景中要执行的操作。这些数字表示工作流中各项操作的顺序。此示例可引导您了解从特征分支到在生产环境中部署的整个过程。

![\[每个分支和环境中的 Gitflow 活动的旁氏表。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/1dee2a06-cc54-4797-b9a9-78b6685edd33/images/d8be49bf-dca1-4892-ac4c-11996a7258c2.png)


有关 Gitflow 方法中的 AWS 账户、环境和分支的更多信息，请参阅[为多账户环境选择 Git 分支策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)。 DevOps 

**自动化和扩展**

持续集成和持续交付（CI/CD) is the process of automating the software release lifecycle. It automates much or all of the manual processes traditionally required to get new code from an initial commit into production. A CI/CD pipeline encompasses the sandbox, development, testing, staging, and production environments. In each environment, the CI/CD pipeline provisions any infrastructure that is needed to deploy or test the code. By using CI/CD, development teams can make changes to code that are then automatically tested and deployed. CI/CD管道）还通过强制执行一致性、标准、最佳实践以及功能接受和部署的最低接受程度，为开发团队提供管理和护栏。 有关更多信息，请参阅[上的 “练习持续集成和持续交付” AWS](https://docs.aws.amazon.com/whitepapers/latest/practicing-continuous-integration-continuous-delivery/welcome.html)。

AWS 提供了一套旨在帮助您构建 CI/CD 管道的开发人员服务。例如，[AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)是一项完全托管的持续交付服务，可帮助您实现发布管道的自动化，从而实现快速可靠的应用程序和基础设施更新。 [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)编译源代码、运行测试和生成 ready-to-deploy软件包。有关更多信息，请参阅[上的开发者工具 AWS](https://aws.amazon.com/products/developer-tools/)。

## 工具
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-tools"></a>

**AWS 服务和工具**

AWS 提供了一套开发者服务，你可以用它们来实现这种模式：
+ [AWS CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/welcome.html) 是一项高度可扩展的托管式构件存储库服务，有助于您存储和共享用于应用程序开发的软件包。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管式构建服务，可编译源代码、运行单元测试和生成部署就绪的构件。
+ [AWS CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)自动部署到亚马逊弹性计算云 (Amazon EC2)、本地实例、 AWS Lambda 函数或亚马逊弹性容器服务 (Amazon ECS) 服务。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可帮助您快速对软件发布过程的不同阶段进行建模和配置，并自动执行持续发布软件变更所需步骤。

**其他工具**
+ [Draw.io 桌面](https://github.com/jgraph/drawio-desktop/releases)是用于制作流程图和图表的应用程序。代码存储库包含 Draw.io 的 .drawio 格式模板。
+ [Figma](https://www.figma.com/design-overview/) 是一款专为协作而打造的在线设计工具。代码存储库包含 Figma 的 .fig 格式模板。
+ （可选）[Gitflow 插件](https://github.com/nvie/gitflow)是 Git 扩展的集合，它们可为 Gitflow 分支模型提供高级存储库操作。

**代码存储库**

此模式下图表的源文件可在 GitFlow存储库的 GitHub [Git 分支策略](https://github.com/awslabs/git-branching-strategies-for-multiaccount-devops/tree/main/gitflow)中找到。其包括采用 PNG、draw.io 和 Figma 格式的文件。您可以修改这些图表，以为组织的流程提供支持。

## 最佳实践
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-best-practices"></a>

遵循 Well-Architect [AWS e DevOps d 指南和为多账户环境](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)[选择 Git 分支](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)策略中的最佳实践和建议。 DevOps 这些最佳实践可以帮助您有效地实施基于 Gitflow 的开发、促进协作、提高代码质量以及简化开发流程。

## 操作说明
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-epics"></a>

### 查看 Gitflow 工作流
<a name="reviewing-the-gitflow-workflows"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看标准的 Gitflow 流程。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 工程师 | 
| 查看修补程序 Gitflow 流程。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 工程师 | 
| 查看错误修复 Gitflow 流程。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 工程师 | 

## 问题排查
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 分支冲突 | Gitflow 模型可能出现的一个常见问题是，生产环境需要修补程序，但较低级别的环境中也需要进行相应更改，因为另一个分支中同样存在要修改的资源。我们建议您一次仅激活一个发布分支。如果您一次有多个分支处于活动状态，则环境中的更改可能会发生冲突，并且您可能无法将分支推进到生产中。 | 
| 合并 | 应尽快将版本合并回主分支并进行开发，以便将工作整合回主分支。 | 
| 压缩合并 | 只有在从 `feature` 分支合并到 `develop` 分支时才会使用压缩合并。在较高的分支中使用压缩合并，可能会导致在向较低级别分支合并更改时遇到困难。 | 

## 相关资源
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-resources"></a>

本指南不包括针对 Git 的培训；但是，如果您需要这种培训，则可以在互联网上找到许多可用的高质量的资源。我们建议从 [Git 文档](https://git-scm.com/doc)网站开始。

以下资源可以帮助您在 AWS 云中完成 Gitflow 分支之旅。

**AWS DevOps 指导**
+ [AWS DevOps 指南](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)
+ [AWS 部署管道参考架构](https://pipelines.devops.aws.dev/)
+ [什么是 DevOps？](https://aws.amazon.com/devops/what-is-devops/)
+ [DevOps resources](https://aws.amazon.com/devops/resources/)

**Gitflow 指引**
+ [原始 Gitflow 博客](https://nvie.com/posts/a-successful-git-branching-model/)（Vincent Driessen 博客文章）
+ [Gitflow 工作流](https://www.atlassian.com/git/tutorials/comparing-workflows/gitflow-workflow)（Atlassian）
+ [Gitflow 开启 GitHub：如何将 Git Flow 工作流程与 GitHub 基于 Repos 的存储库一起使用](https://youtu.be/WQuxeEvaCxs)（视频）YouTube 
+ [Git Flow 初始化示例](https://www.youtube.com/watch?v=d4cDLBFbekw)（YouTube 视频）
+ [Gitflow 发布分支从头到尾（视频](https://www.youtube.com/watch?v=rX80eKPdA28)）YouTube 

**其他资源**

[十二要素应用程序方法论](https://12factor.net/)（12factor.net）

# 为多 DevOps 账户环境实施中继分支策略
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments"></a>

*Mike Stephens 和 Rayjan Wilson，Amazon Web Services*

## Summary
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-summary"></a>

管理源代码存储库时，不同的分支策略会影响开发团队使用的软件开发和发布流程。常见分支策略的示例包括 Trunk、 GitHub Flow 和 Gitflow。这些策略使用不同的分支，并且在每种环境中执行的活动也各不相同。正在实施 DevOps 流程的组织将受益于可视化指南，以帮助他们了解这些分支策略之间的区别。在组织中使用此视觉对象可以帮助开发团队协调工作并遵循组织标准。此模式提供了该视觉对象，并描述了在组织中实施中继分支策略的过程。

这种模式是关于为具有多个 AWS 账户分支机构的组织选择和实施 DevOps 分支策略的文档系列的一部分。该系列旨在帮助您从一开始就应用正确的策略和最佳实践，以简化您的云体验。中继只是您的组织可以使用的一种潜在分支策略。本文档系列还涵盖了 [GitHub Flow](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.html) 和 [Gitflow 分支模型](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html)。如果你还没有这样做，我们建议你先查看[为多账户 DevOps 环境选择 Git 分支策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)，然后再按此模式实施指南。请务必谨慎选择适合组织的分支策略。

本指南提供了图表，其中显示了组织如何实施中继策略。建议您查看官方的《Well-Ar [ DevOps chitec AWS ted 指南》，以查看最佳实](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)践。此模式包括 DevOps 流程中每个步骤的推荐任务、步骤和限制。

## 先决条件和限制
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-prereqs"></a>

**先决条件**
+ Git，[已安装](https://git-scm.com/downloads)。这可用作源代码存储库工具。
+ Draw.io，[已安装](https://github.com/jgraph/drawio-desktop/releases)。此应用程序可用于查看和编辑图表。

## 架构
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-architecture"></a>

**目标架构**

下图的使用方法与[旁氏表](https://en.wikipedia.org/wiki/Punnett_square)类似（维基百科）。您可以将垂直轴上的分支与水平轴上的 AWS 环境对齐，以确定在每个场景中要执行的操作。这些数字表示工作流中各项操作的顺序。此示例可引导您了解从 `feature` 分支到在生产环境中部署的整个过程。

![\[每个分支和环境中的中继活动的旁氏表\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/5df23e4d-84fe-4ab3-a54f-96b6406abc57/images/ad549ef4-90ad-47c1-bd01-f21d6ce5511a.png)


有关 Trunk 方法中的 AWS 账户、环境和分支的更多信息，请参阅[为多账户 DevOps 环境选择 Git 分支策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach)。

**自动化和扩展**

持续集成和持续交付（CI/CD) is the process of automating the software release lifecycle. It automates much or all of the manual processes traditionally required to get new code from an initial commit into production. A CI/CD pipeline encompasses the sandbox, development, testing, staging, and production environments. In each environment, the CI/CD pipeline provisions any infrastructure that is needed to deploy or test the code. By using CI/CD, development teams can make changes to code that are then automatically tested and deployed. CI/CD管道）还通过强制执行一致性、标准、最佳实践以及功能接受和部署的最低接受程度，为开发团队提供管理和护栏。 有关更多信息，请参阅[上的 “练习持续集成和持续交付” AWS](https://docs.aws.amazon.com/whitepapers/latest/practicing-continuous-integration-continuous-delivery/welcome.html)。

AWS 提供了一套旨在帮助您构建 CI/CD 管道的开发人员服务。例如，[AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)是一项完全托管的持续交付服务，可帮助您实现发布管道的自动化，从而实现快速可靠的应用程序和基础设施更新。 [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)编译源代码、运行测试和生成 ready-to-deploy软件包。有关更多信息，请参阅[上的开发者工具 AWS](https://aws.amazon.com/products/developer-tools/)。

## 工具
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-tools"></a>

**AWS 服务和工具**

AWS 提供了一套开发者服务，你可以用它们来实现这种模式：
+ [AWS CodeArtifact](https://docs.aws.amazon.com/codeartifact/latest/ug/welcome.html) 是一项高度可扩展的托管式构件存储库服务，有助于您存储和共享用于应用程序开发的软件包。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管式构建服务，可编译源代码、运行单元测试和生成部署就绪的构件。
+ [AWS CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html)自动部署到亚马逊弹性计算云 (Amazon EC2)、本地实例、 AWS Lambda 函数或亚马逊弹性容器服务 (Amazon ECS) 服务。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可帮助您快速对软件发布过程的不同阶段进行建模和配置，并自动执行持续发布软件变更所需步骤。

**其他工具**
+ [Draw.io 桌面](https://github.com/jgraph/drawio-desktop/releases) – 用于制作流程图和图表的应用程序。
+ [Figma](https://www.figma.com/design-overview/) 是一款专为协作而打造的在线设计工具。代码存储库包含 Figma 的 .fig 格式模板。

**代码存储库**

此模式中图表的源文件可在中[继的 GitHub Git 分支策略存储库中找](https://github.com/awslabs/git-branching-strategies-for-multiaccount-devops/tree/main/trunk)到。其包括采用 PNG、draw.io 和 Figma 格式的文件。您可以修改这些图表，以为组织的流程提供支持。

## 最佳实践
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-best-practices"></a>

遵循 Well-Architect [AWS e DevOps d 指南和为多账户环境](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)[选择 Git 分支](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)策略中的最佳实践和建议。 DevOps 这些最佳实践可以帮助您有效地实施基于中继的开发、促进协作、提高代码质量以及简化开发流程。

## 操作说明
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-epics"></a>

### 查看中继工作流
<a name="reviewing-the-trunk-workflow"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看标准中继流程。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/implement-a-trunk-branching-strategy-for-multi-account-devops-environments.html) | DevOps 工程师 | 

## 问题排查
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 分支冲突 | 中继模型可能出现的一个常见问题是，生产环境需要修补程序，但 `feature` 分支中也需要进行相应更改，因为该分支中同样存在要修改的资源。我们建议您经常将来自 `main` 更改合并到较低的分支中，以避免在合并到 `main` 时发生重大冲突。 | 

## 相关资源
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-resources"></a>

本指南不包括针对 Git 的培训；但是，如果您需要这种培训，则可以在互联网上找到许多可用的高质量的资源。我们建议从 [Git 文档](https://git-scm.com/doc)网站开始。

以下资源可以帮助您在 AWS 云中完成中继分支之旅。

**AWS DevOps 指导**
+ [AWS DevOps 指南](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)
+ [AWS Deployment Pipeline Reference Architecture](https://pipelines.devops.aws.dev/)
+ [什么是 DevOps？](https://aws.amazon.com/devops/what-is-devops/)
+ [DevOps resources](https://aws.amazon.com/devops/resources/)

**中继指引**
+ [基于中继的开发](https://trunkbaseddevelopment.com/)

**其他资源**
+ [十二要素应用程序方法论](https://12factor.net/)（12factor.net）

# 在部署 AWS 基础设施之前，实施集中式自定义 Checkov 扫描以强制执行策略
<a name="centralized-custom-checkov-scanning"></a>

*Benjamin Morris，Amazon Web Services*

## Summary
<a name="centralized-custom-checkov-scanning-summary"></a>

这种模式提供了一个 GitHub 操作框架，用于在一个存储库中编写可在整个组织中重复使用的自定义 Checkov 策略。 GitHub 通过采用这种模式，信息安全团队可以根据公司要求编写、添加和维护自定义策略。自定义策略可以自动拉入 GitHub 组织中的所有管道。这种方法可用于在资源部署之前强制执行公司的资源标准。

## 先决条件和限制
<a name="centralized-custom-checkov-scanning-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 使用 “ GitHub 操作” 的 GitHub 组织
+ AWS 使用 HashiCorp Terraform 部署的基础架构或 AWS CloudFormation

**限制**
+ 此模式是为 GitHub 操作编写的。但是，它可以适应类似的持续集成和持续交付 (CI/CD) 框架，例如。 GitLab不需要特定的付费版本。 GitHub 
+ 有些 AWS 服务 并非全部可用 AWS 区域。有关区域可用性，请参阅 AWS 文档中的[服务终端节点和配额](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然后选择该服务的链接。

## 架构
<a name="centralized-custom-checkov-scanning-architecture"></a>

此模式旨在作为包含 GitHub 可重复使用的工作流程和自定义 Checkov 策略的 GitHub 存储库进行部署。可重复使用的工作流程可以扫描 Terraform 和 CloudFormation 基础设施即代码 (IaC) 存储库。

下图将**可重用 GitHub 工作流程存储库**和**自定义 Checkov 策略存储库**作为单独的图标显示。但是，您可以将这些存储库作为单独的存储库或单个存储库来实现。示例代码使用单个存储库，工作流文件 (`.github/workflows`) 和自定义策略文件（`custom_policies` 文件夹和 `.checkov.yml` 配置文件）位于同一个存储库中。

![\[GitHub Actions 使用可重复使用 GitHub 的工作流程和自定义 Checkov 策略来评估 IaC。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/6c0c941f-14f9-4569-92da-9f81ab3e525c/images/a1539ce5-0ee6-4af1-bd01-cafad0f71708.png)


下图显示了如下工作流：

1. 用户在 GitHub 仓库中创建拉取请求。

1. 管道工作流程从 Acti GitHub ons 开始，包括对 Checkov 可重复使用工作流程的引用。

1. 管道工作流程从外部存储库下载引用的 Checkov 可重用工作流程，并使用 GitHub 操作运行该 Checkov 工作流程。

1. Checkov 可重复使用的工作流从外部存储库下载自定义策略。

1. Checkov 可重用工作流程根据内置和自定义 Checkov 策略评估 GitHub 存储库中的 IaC。Checkov 可重复使用的工作流通过还是失败取决于是否发现了安全问题。

**自动化和扩展**

此模式允许集中管理 Checkov 配置，以便于从单个位置应用策略更新。不过，此模式确实要求每个代码仓库都使用一个工作流，且该工作流需包含对中央可复用工作流的引用。您可以手动添加此引用，也可以使用脚本将文件推送到每个存储库的 `.github/workflows` 文件夹。

## 工具
<a name="centralized-custom-checkov-scanning-tools"></a>

**AWS 服务**
+ [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在资源的整个生命周期中跨地区对其 AWS 账户 进行管理。Checkov 可以扫描 CloudFormation。

**其他工具**
+ [Checkov](https://www.checkov.io/) 是一款静态代码分析工具，用于检查 IaC 是否存在安全性和合规性配置错误。
+ GitHub A@@ [c](https://github.com/features/actions) tions 已集成到 GitHub 平台中，可帮助您在 GitHub 仓库中创建、共享和运行工作流程。您可以使用 GitHub Actions 来自动执行诸如构建、测试和部署代码之类的任务。
+ [Terraform](https://www.terraform.io/) 是一款 IaC 工具 HashiCorp ，可帮助您创建和管理云和本地资源。Checkov 可以扫描 Terraform。

**代码存储库**

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

## 最佳实践
<a name="centralized-custom-checkov-scanning-best-practices"></a>
+ 为了保持一致的安全态势，请使贵公司的安全策略与 Checkov 策略保持一致。
+ 在实施 Checkov 自定义策略的早期阶段，您可以在 Checkov 扫描中使用软失败选项来允许合并存在安全问题的 IaC。随着过程的成熟，从软失败选项切换到硬失败选项。

## 操作说明
<a name="centralized-custom-checkov-scanning-epics"></a>

### 为自定义策略创建中央 Checkov 存储库
<a name="create-a-central-checkov-repository-for-custom-policies"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个中央 Checkov 存储库。 | 创建一个存储库来存储将在组织内使用的自定义 Checkov 策略。为了快速入门，您可以将此模式 GitHub [centralized-custom-checkov-sast ](https://github.com/aws-samples/centralized-custom-checkov-sast)存储库的内容复制到中央的 Checkov 存储库中。 | DevOps 工程师 | 
| 为可重复使用的工作流创建存储库。 | 如果可重复使用的工作流的存储库已存在，或者您计划在与自定义 Checkov 策略相同的存储库中包含可重复使用的工作流文件，则可以跳过此步骤。创建 GitHub 存储库以保存可重复使用的工作流程。其他存储库的管道将引用此存储库。 | DevOps 工程师 | 

### 创建可重复使用的 Checkov 工作流和示例
<a name="create-reusable-and-example-checkov-workflows"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 添加可重复使用的 Checkov 工作流。 | 在可重复使用的工作流程存储库中创建可重复 GitHub 使用的 Checkov Actions 工作流程（YAML 文件）。您可以从此模式中提供的工作流文件中调整此可重复使用的工作流。您可能想要进行的更改示例之一，是更改可重复使用的工作流以使用软失败选项。将 `soft-fail` 设置为 `true`，即使发生 Checkov 扫描失败仍允许作业成功完成。有关说明，请参阅 Checkov 文档中的[硬失败和软失败](https://www.checkov.io/2.Basics/Hard%20and%20soft%20fail.html)。 | DevOps 工程师 | 
| 添加示例工作流。 | 添加引用该 `reusable` 工作流的 Checkov 工作流示例。这将为 `reusable` 工作流的复用方式提供一个模板。在示例存储库中，`checkov-source.yaml` 是可重复使用的工作流，`checkov-scan.yaml` 是使用 `checkov-source` 的示例。有关编写示例 Checkov 工作流的更多详细信息，请参阅[其他信息](#centralized-custom-checkov-scanning-additional)。 | DevOps 工程师 | 

### 将公司策略与 Checkov 自定义策略相关联
<a name="associate-company-policies-to-checkov-custom-policies"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确定可以通过 Checkov 强制执行的策略。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralized-custom-checkov-scanning.html)有关创建 Checkov 自定义策略的更多详细信息，请参阅 Checkov 文档中的[自定义策略概述](https://www.checkov.io/3.Custom%20Policies/Custom%20Policies%20Overview.html)。 | 安全性与合规性 | 
| 添加 Checkov 自定义策略。 | 将已确定的公司策略转换为中央存储库中的自定义 Checkov 策略。您可以用 Python 或 YAML 编写简单的 Checkov 策略。 | 安全性 | 

### 实现集中式 Checkov 自定义策略
<a name="implement-centralized-checkov-custom-policies"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将 Checkov 可重复使用的工作流添加到所有存储库。 | 此时，您应举出一个引用可重复使用工作流的 Checkov 工作流示例。将引用可重复使用工作流的示例 Checkov 工作流复制到每个需要它的存储库。 | DevOps 工程师 | 
| 创建一种机制来确保 Checkov 在合并之前运行。 | 为确保每个拉取请求都运行 Checkov 工作流程，请创建一个[状态检查](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/about-status-checks)，要求在合并拉取请求之前成功执行 Checkov 工作流程。 GitHub 允许您要求在合并拉取请求之前运行特定的工作流程。 | DevOps 工程师 | 
| 创建组织范围的 PAT，并将其作为密钥共享。 | 如果您的 GitHub 组织是公开可见的，则可以跳过此步骤。这种模式要求 Checkov 工作流程能够从 GitHub 组织中的自定义策略存储库下载自定义策略。您必须提供相关权限，这样 Checkov 工作流才能访问这些存储库。为此，请创建拥有读取组织存储库权限的[个人访问令牌](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#creating-a-fine-grained-personal-access-token)（PAT）。与存储库共享此 PAT，可以作为组织范围的密钥（如果是付费计划），也可以是每个存储库中的密钥（免费版本）。在示例代码中，密钥的默认名称为 `ORG_PAT`。 | DevOps 工程师 | 
| （可选）保护 Checkov 工作流文件不被修改。 | 为了保护 Checkov 工作流文件免受不必要的更改，您可以使用 `CODEOWNERS` 文件。`CODEOWNERS` 文件通常部署在目录的根目录中。例如，要要求在修改`checkov-scan.yaml`文件时获得 GitHub 组织`secEng`群组的批准，请将以下内容附加到存储库`CODEOWNERS`的文件中：<pre>[Checkov]<br />.github/workflows/checkov-scan.yaml @myOrg/secEng</pre>`CODEOWNERS` 文件特定于其所在的存储库。为了保护存储库使用的 Checkov 工作流，必须在每个存储库中添加（或更新）一个 `CODEOWNERS` 文件。有关保护 Checkov 工作流文件的更多信息，请参阅[其他信息](#centralized-custom-checkov-scanning-additional)。有关`CODEOWNERS`文件的更多信息，请参阅您的 CI/CD 提供商的官方文档（例如 [GitHub](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners)）。 | DevOps 工程师 | 

## 相关资源
<a name="centralized-custom-checkov-scanning-resources"></a>
+ [Checkov 自定义策略概述](https://www.checkov.io/3.Custom%20Policies/Custom%20Policies%20Overview.html)
+ [CloudFormation 配置扫描](https://www.checkov.io/7.Scan%20Examples/Cloudformation.html)
+ [GitHub 操作可重复使用的工作流程](https://docs.github.com/en/actions/using-workflows/reusing-workflows)

## 附加信息
<a name="centralized-custom-checkov-scanning-additional"></a>

**编写 Checkov 工作流文件**

编写 `checkov-scan.yaml` 时，请考虑希望它何时运行。顶级 `on` 密钥决定工作流何时运行。在示例存储库中，当有针对 `main` 分支的拉取请求时（以及该拉取请求的源分支被修改时），就会运行该工作流。由于 `workflow_dispatch` 密钥的缘故，也可以根据需要运行该工作流。

您可以根据您希望的工作流运行频率来更改工作流触发条件。例如，您可以将工作流更改为每次将代码推送到任何分支时运行，方法是将 `pull_request` 替换为 `push` 并移除 `branches` 密钥。

您可以修改在单个存储库中创建的示例工作流文件。例如，如果存储库围绕 `production` 分支构造，则可以将目标分支的名称从 `main` 调整为 `production`。

**保护 Checkov 工作流文件**

Checkov 扫描可提供有关潜在安全配置错误的有用信息。但是，一些开发人员可能会认为这是他们工作效率的障碍，因此试图删除或禁用扫描工作流。

有几种方法可以解决这个问题，包括更好地宣传安全扫描的长期价值，更清晰地记录如何部署安全基础设施。这些是重要的 “软” DevSecOps 协作方法，可以看作是解决这个问题根本原因的办法。但是，您也可以使用 `CODEOWNERS` 文件之类的技术控制措施作为护栏，帮助开发人员走在正确的道路上。

**在沙盒中测试模式**

要在沙盒环境测试此模式，请执行以下步骤：

1. 创建新 GitHub 组织。创建一个对组织中的所有存储库拥有只读访问权限的令牌。由于此令牌适用于沙盒环境，而非付费环境，因此您将无法将此令牌存储在组织级密钥中。

1. 创建一个 `checkov` 存储库来存放 Checkov 配置，并创建一个 `github-workflows` 存储库来存放可重复使用的工作流配置。使用示例存储库的内容填充存储库。

1. 创建一个应用程序存储库，然后将 `checkov-scan.yaml` 工作流复制并粘贴到其 `.github/workflows` 文件夹。向存储库中添加一个密钥，其中包含您为组织只读访问创建的 PAT。默认密钥为 `ORG_PAT`。

1. 创建一个拉取请求，向应用程序存储库中添加一些 Terraform 或 CloudFormation 代码。Checkov 应进行扫描并返回结果。

# 通过 K8sGPT 和 Amazon Bedrock 集成，实施人工智能驱动的 Kubernetes 诊断和问题排查
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration"></a>

*Ishwar Chauthaiwale、Muskan . 和 Prafful Gupta，Amazon Web Services*

## Summary
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-summary"></a>

此模式演示了如何通过将 K8sGPT 与 Amazon Bedrock 上提供的 Anthropic Claude v2 模型集成来实施人工智能驱动的 Kubernetes 诊断和问题排查。该解决方案通过安全的堡垒主机架构为 Kubernetes 集群问题提供了自然语言分析和修复步骤。通过将 K8sGPT Kubernetes 专业知识与 Amazon Bedrock 的高级语言功能相结合 DevOps ，团队可以快速识别和解决集群问题。借助这些功能，平均解决时间（MTTR）有可能实现至高 50% 的缩短。

此云原生模式利用 Amazon Elastic Kubernetes Service（Amazon EKS）for Kubernetes 管理。该模式通过适当的 AWS Identity and Access Management (IAM) 角色和网络隔离来实现安全最佳实践。对于希望通过人工智能帮助简化 Kubernetes 操作并增强问题排查能力的组织来说，该解决方案特别有价值。

## 先决条件和限制
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-prereqs"></a>

**先决条件**
+  AWS 账户 具有适当权限的活跃用户
+ 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)
+ Amazon EKS 集群
+ 在 [Amazon Bedrock](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html) 上访问 Anthropic Claude 2 模型
+ 具有所需安全组设置的堡垒主机
+ K8sGPT [已安装](https://docs.k8sgpt.ai/getting-started/installation/)

**限制**
+ K8sGPT 分析受到 Claude v2 模型上下文窗口大小的限制。
+ Amazon Bedrock 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)，然后选择相应服务的链接。

**产品版本**
+ Amazon EKS [版本 1.31 或更高版本](https://docs.aws.amazon.com/eks/latest/userguide/kubernetes-versions.html)
+  Amazon Bedrock 上的 [Claude 2 模型](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html)
+ K8sGPT [v0.4.2 或更高版本](https://github.com/k8sgpt-ai/k8sgpt/releases)

## 架构
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-architecture"></a>

下图显示了在 AWS 云中通过集成 K8sGPT 与 Amazon Bedrock 进行人工智能驱动的 Kubernetes 诊断的架构。

![\[通过集成 K8sGPT 与 Amazon Bedrock 进行 Kubernetes 诊断的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/09bc08f6-e191-4cef-b26b-dcb6225b15cc/images/8789891d-4a90-44b0-a108-387f6d96496b.png)


该架构显示了以下工作流：

1. 开发人员通过与堡垒主机的安全连接来访问环境。此 Amazon EC2 实例充当安全入口点，包含 k8sGpt 命令行界面 (CLI) 安装和必需的配置。

1. 堡垒主机配置了特定 IAM 角色，可与 Amazon EKS 集群和 Amazon Bedrock 端点建立安全连接。K8sGPT 已安装并配置到堡垒主机上，可执行 Kubernetes 集群分析。

1. Amazon EKS 管理 Kubernetes 控制面板和 Worker 节点，从而为 K8sGPT 分析提供目标环境。该服务可在虚拟私有云（VPC）内跨多个可用区运行，而这有助于提供高可用性和弹性。Amazon EKS 通过 Kubernetes API 提供运营数据，从而实现全面的集群分析。

1. k8sGPT 向 Amazon Bedrock 发送分析数据，后者为自然语言处理提供 Claude v2 基础模型（FM）。该服务可处理 k8sGPT 分析以生成人类可读的解释，并根据已发现的问题提供详细的补救建议。Amazon Bedrock 是一种无服务器人工智能服务，具有高可用性和可扩展性。

**注意**  
在整个工作流中，IAM 通过角色和策略控制组件之间的访问权限，进而管理堡垒主机、Amazon EKS 和 Amazon Bedrock 交互的身份验证。IAM 实现了最低权限原则，并在整个架构中实现安全的跨服务通信。

**自动化和扩展**

K8sGPT 操作可以通过各种 AWS 服务 工具在多个 Amazon EKS 集群中实现自动化和扩展。[该解决方案支持使用 [Jenkins、Actions](https://www.jenkins.io/) 或[AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html)用于计划分析的持续集成和持续部署 (CI/CD) 集成。GitHub ](https://docs.github.com/en/actions/get-started/understand-github-actions)K8sGPT 运算符利用自动问题检测和报告功能实现集群内持续监控。对于企业级部署，您可以使用 [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 来安排扫描并使用自定义脚本触发自动响应。 AWS SDK 集成支持对大型集群进行编程控制。

## 工具
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-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/getting-started.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。

**其他工具**
+ [k8sGPT](https://k8sgpt.ai/) 是一款开源的人工智能驱动型工具，可改变 Kubernetes 的管理方式。它充当虚拟站点可靠性工程（SRE）专家，自动扫描、诊断和排查 Kubernetes 集群问题。管理员可以使用自然语言与 k8sGPT 进行交互，并获得有关集群状态、容器组（pod）崩溃和服务故障的清晰、可操作的见解。该工具的内置分析器可以检测各种问题，从组件配置错误到资源限制，并提供 easy-to-understand解释和解决方案。

## 最佳实践
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-best-practices"></a>
+ 通过使用 AWS Systems Manager Session Manager [堡垒主机访问来实现安全的访问](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.html)控制。
+ 确保 K8sGPT 身份验证使用最低权限的专用 IAM 角色进行 Amazon Bedrock 和 Amazon EKS 交互。有关详情，请参阅 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)。
+ 配置[资源标记](https://docs.aws.amazon.com/whitepapers/latest/tagging-best-practices/what-are-tags.html)，启用 Amazon CloudWatch [日志记录以进行审计跟踪](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/monitor-cloudtrail-log-files-with-cloudwatch-logs.html)，并对敏感[信息实施数据匿名化](https://aws.amazon.com/solutions/guidance/data-anonymization-on-aws/)。
+ 保持 k8sGPT 配置的定期备份，同时在非高峰时段设置自动扫描计划，以最大限度地减少对操作的影响。

## 操作说明
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-epics"></a>

### 将 Amazon Bedrock 添加到人工智能后端提供商列表。
<a name="add-br-to-ai-backend-provider-list"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将 Amazon Bedrock 设置为 K8sGPT 的人工智能后端提供商。 | 要将 Amazon Bedrock 设置为 k8sGpt 的人工智能[后端提供](https://docs.k8sgpt.ai/reference/providers/backend/)者 r，请使用以下命令： AWS CLI <pre>k8sgpt auth add -b amazonbedrock \<br /> -r us-west-2 \<br /> -m anthropic.claude-v2 \<br /> -n endpoint-name <br /></pre>在此示例命令中，使用 `us-west-2` 来表示 AWS 区域。但是，您可以选择其他区域，前提是 Amazon EKS 集群和相应的 Amazon Bedrock 模型在该选定区域均可用并已启用。要检查 `amazonbedrock` 是否已添加到人工智能后端提供商列表中并处于 `Active` 状态，请运行以下命令：<pre>k8sgpt auth list</pre>以下是预期的命令运行输出的示例：<pre>Default: <br />> openai<br />Active: <br />> amazonbedrock<br />Unused: <br />> openai<br />> localai<br />> ollama<br />> azureopenai<br />> cohere<br />> amazonsagemaker<br />> google<br />> noopai<br />> huggingface<br />> googlevertexai<br />> oci<br />> customrest<br />> ibmwatsonxai</pre> | AWS DevOps | 

### 使用筛选器扫描资源
<a name="scan-resources-using-a-filter"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看可用的筛选器列表。 | 要查看所有可用过滤器的列表，请使用以下 AWS CLI 命令：<pre>k8sgpt filters list</pre>以下是预期的命令运行输出的示例：<pre>Active: <br />> Deployment<br />> ReplicaSet<br />> PersistentVolumeClaim<br />> Service<br />> CronJob<br />> Node<br />> MutatingWebhookConfiguration<br />> Pod<br />> Ingress<br />> StatefulSet<br />> ValidatingWebhookConfiguration</pre> | AWS DevOps | 
| 使用筛选器扫描特定命名空间中的容器组（pod）。 | 此命令对于有针对性地调试 Kubernetes 集群中的特定容器组（pod）问题非常有用，它使用 Amazon Bedrock AI 功能来分析和解释它发现的问题。要使用过滤器扫描特定命名空间中的 pod，请使用以下 AWS CLI 命令：<pre>k8sgpt analyze --backend amazonbedrock --explain --filter Pod -n default</pre>以下是预期的命令运行输出的示例：<pre>100% |████████████████████████████████████████████████████████| (1/1, 645 it/s)        <br />AI Provider: amazonbedrock<br /><br />0: Pod default/crashme()<br />- Error: the last termination reason is Error container=crashme pod=crashme<br />Error: The pod named crashme terminated because the container named crashme crashed.<br />Solution: Check logs for crashme pod to identify reason for crash. Restart pod or redeploy application to resolve crash.</pre> | AWS DevOps | 
| 使用筛选器扫描特定命名空间中的部署。 | 此命令对于识别和排查特定于部署的问题非常有用，尤其是在实际状态与所需状态不匹配时。要使用筛选器扫描特定命名空间中的部署，请使用以下 AWS CLI 命令：<pre>k8sgpt analyze --backend amazonbedrock --explain --filter Deployment -n default</pre>以下是预期的命令运行输出的示例：<pre>100% |██████████████████████████████████████████████████████████| (1/1, 10 it/min)        <br />AI Provider: amazonbedrock<br /><br />0: Deployment default/nginx()<br />- Error: Deployment default/nginx has 1 replicas but 2 are available<br /> Error: The Deployment named nginx in the default namespace has 1 replica specified but 2 pod replicas are running.<br />Solution: Check if any other controllers like ReplicaSet or StatefulSet have created extra pods. Delete extra pods or adjust replica count to match available pods.</pre> | AWS DevOps | 
| 使用筛选器扫描特定命名空间中的节点。 | 要使用筛选器扫描特定命名空间中的节点，请使用以下 AWS CLI 命令：<pre>k8sgpt analyze --backend amazonbedrock --explain --filter Node -n default </pre>以下是预期的命令运行输出的示例：<pre>AI Provider: amazonbedrock<br /><br />No problems detected</pre> | AWS DevOps | 

### 分析详细输出
<a name="analyze-detailed-outputs"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 获取详细输出。 |  要获得详细输出，请使用以下 AWS CLI 命令：<pre>k8sgpt analyze --backend amazonbedrock --explain --ouput json</pre>以下是预期的命令运行输出的示例：<pre>{<br />  "provider": "amazonbedrock",<br />  "errors": null,<br />  "status": "ProblemDetected",<br />  "problems": 1,<br />  "results": [<br />    {<br />      "kind": "Pod",<br />      "name": "default/crashme",<br />      "error": [<br />        {<br />          "Text": "the last termination reason is Error container=crashme pod=crashme",<br />          "KubernetesDoc": "",<br />          "Sensitive": []<br />        }<br />      ],<br />      "details": " Error: The pod named crashme terminated because the container named crashme crashed.\nSolution: Check logs for crashme pod to identify reason for crash. Restart pod or redeploy application to resolve crash.",<br />      "parentObject": ""<br />    }<br />  ]<br />}</pre> | AWS DevOps | 
| 检查有问题的容器组（pod）。 | 要检查是否有特定问题的 pod，请使用以下 AWS CLI 命令：<pre>kubectl get pods --all-namespaces | grep -v Running</pre>以下是预期的命令运行输出的示例：<pre>NAMESPACE    NAME      READY    STATUS          RESTARTS      AGE                                       <br />default     crashme     0/1   CrashLoopBackOff   260(91s ago)   21h</pre> | AWS DevOps | 
| 获取特定于应用程序的见解。 | 在以下情况下，此命令特别有用：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration.html)要获取特定于应用程序的见解，请使用以下命令：<pre>k8sgpt analyze --backend amazonbedrock --explain -L app=nginx -n default</pre>以下是预期的命令运行输出的示例：<pre>AI Provider: amazonbedrock<br /><br />No problems detected</pre> |  | 

## 相关资源
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-resources"></a>

**AWS Blog**
+ [使用 Amazon Bedrock 代理式工作流自动执行 Amazon EKS 问题排查](https://aws.amazon.com/blogs/machine-learning/automate-amazon-eks-troubleshooting-using-an-amazon-bedrock-agentic-workflow/)
+ [使用 k8sGpt 和 Amazon Bedrock 简化 Kubernetes 集群维护](https://aws.amazon.com/blogs/machine-learning/use-k8sgpt-and-amazon-bedrock-for-simplified-kubernetes-cluster-maintenance/)

**AWS 文档**
+ AWS CLI [命令：[创建集群和描述集群](https://docs.aws.amazon.com/cli/latest/reference/eks/create-cluster.html)](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-cluster.html)
+ [Amazon Cognito 入门](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html)（Amazon 文档）
+ [IAM 中的安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)（IAM 文档）

**其他资源**
+ [k8sgpt](https://k8sgpt.ai/)

# 自动检测变化并为 monorepo 启动不同的 CodePipeline 管道 CodeCommit
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit"></a>

*Helton Ribeiro、Petrus Batalha 和 Ricardo Morais，Amazon Web Services*

## Summary
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-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/)

这种模式可以帮助您自动检测基于 monorepo 的应用程序的源代码的更改，然后在其中启动运行持续集成 AWS CodeCommit 和持续交付（管道）的CI/CD) automation for each microservice. This approach means that each microservice in your monorepo-based application can have a dedicated CI/CD管道，从而确保更好的可见性、更轻松的代码共享以及改进的协作、标准化和可发现性。 AWS CodePipeline 

此模式中描述的解决方案不会在 monorepo 内部的微服务之间执行任何依赖关系分析。它仅检测源代码中的更改并启动匹配的 CI/CD 管道。

该模式 AWS Cloud9 用作集成开发环境 (IDE)，并使用两个 CloudFormation 堆栈 AWS Cloud Development Kit (AWS CDK) 来定义基础架构：`MonoRepoStack`和`PipelinesStack`。`MonoRepoStack`堆栈在中创建 monorepo AWS CodeCommit 和启动管道的 AWS Lambda 函数。 CI/CD `PipelinesStack` 堆栈定义了管道基础设施。

**重要**  
此模式的工作流是概念验证（PoC）。我们建议您仅将其用在测试环境中。如果您想在生产环境中使用此模式的方法，请参阅 AWS Identity and Access Management (IAM) 文档[中的 IAM 中的安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)，并对您的 IAM 角色和进行必要的更改 AWS 服务。 

## 先决条件和限制
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ AWS Command Line Interface (AWS CLI)，已安装并配置。有关更多信息，请参阅 AWS CLI 文档 AWS CLI中的[安装、更新和卸载](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)。 
+ Python 3 和 `pip`，已安装于本地计算机。有关更多信息，请参阅 [Python 文档](https://www.python.org/)。 
+ AWS CDK，已安装并配置。有关更多信息，请参阅 AWS CDK 文档[AWS CDK中的入门](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)。 
+ 已安装和配置的 AWS Cloud9 IDE。有关更多信息，请参阅 AWS Cloud9 文档 AWS Cloud9中的[设置](https://docs.aws.amazon.com/cloud9/latest/user-guide/setting-up.html)。 
+  GitHub [AWS CodeCommit monorepo 多管道触发器](https://github.com/aws-samples/monorepo-multi-pipeline-trigger)存储库，克隆到您的本地计算机上。 
+ 包含要用来生成和部署的应用程序代码的现有目录 CodePipeline。
+ 熟悉 DevOps 最佳实践并有经验. AWS 云为了增加对它的熟悉程度 DevOps，你可以使用 “[使用 DevOps 实践和 AWS 规范指南” AWS Cloud9网站上的 “构建与微服务松散耦合的架构](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/build-a-loosely-coupled-architecture-with-microservices-using-devops-practices-and-aws-cloud9.html)” 模式。 

## 架构
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-architecture"></a>

下图显示了如何使用 AWS CDK 来定义具有两个 AWS CloudFormation 堆栈的基础架构：`MonoRepoStack`和。`PipelinesStack`

![\[使用 AWS CDK 定义包含两个 CloudFormation 堆栈的基础设施的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a3397158-a208-4033-844e-969af13ae8b6/images/b0bb1094-b598-4b3d-ab8b-ad9b0eb45f38.png)


下图显示了如下工作流：

1. 引导过程使用创建 AWS CloudFormation 堆栈和`MonoRepoStack`。 AWS CDK `PipelinesStack`

1. `MonoRepoStack`堆栈会为您的应用程序创建 CodeCommit 存储库，并在每次提交后启动的 `monorepo-event-handler` Lambda 函数。

1. `PipelinesStack`堆栈在 CodePipeline 其中创建由 Lambda 函数启动的管道。每项微服务都必须有定义的基础设施管道。

1. 的管道`microservice-n`由 Lambda 函数启动，并根据中的源代码启动其隔离 CI/CD 阶段。 CodeCommit

1. 的管道`microservice-1`由 Lambda 函数启动，并根据中的源代码启动其隔离 CI/CD 阶段。 CodeCommit

下图显示了 AWS CloudFormation 堆栈`MonoRepoStack`和账户`PipelinesStack`中的部署情况。

![\[在 AWS 账户 MonoRepoStack PipelinesStack 中部署 CloudFormation 堆栈。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a3397158-a208-4033-844e-969af13ae8b6/images/39e60e49-dea2-486d-8a2c-6cae438f69b4.png)


1. 用户在其中一个应用程序微服务中更改代码。

1. 用户将更改从本地存储库推送到 CodeCommit 存储库。

1. 推送活动启动 Lambda 函数，该函数接收所有到存储库的推送。 CodeCommit 

1. Lambda 函数在 Parameter Store（ AWS Systems Manager的一项功能）中读取参数，以检索最新的提交 ID。此参数的命名格式为：`/MonoRepoTrigger/{repository}/{branch_name}/LastCommit`。如果未找到该参数，Lambda 函数会从 CodeCommit 存储库中读取最后一次提交 ID，并将返回的值保存在参数存储中。

1. 识别提交 ID 和更改的文件后，Lambda 函数会识别每个微服务目录的管道并启动所需的管道。 CodePipeline 

## 工具
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-tools"></a>
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)是一个软件开发框架，用于在代码中定义云基础架构并通过它进行配置 CloudFormation。
+ [Python](https://www.python.org/) 是一种可让您快速工作并更高效地集成系统的编程语言。

**代码**

此模式的源代码和模板可在 GitHub [AWS CodeCommit monorepo 多管道](https://github.com/aws-samples/monorepo-multi-pipeline-trigger)触发器存储库中找到。

## 最佳实践
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-best-practices"></a>
+ 此示例架构不包括对已部署基础设施的监控解决方案。如果您要在生产环境中部署此解决方案，建议您启用监控。有关更多信息，请参阅 AWS Serverless Application Model (AWS SAM) 文档中的[使用 Application Insights 监控您的无服务器 CloudWatch 应用程序](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/monitor-app-insights.html)。
+ 编辑此模式提供的示例代码时，请遵循 AWS CDK 文档中[开发和部署云基础设施的最佳实践](https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html)。
+ 定义微服务管道时，请查看 AWS CodePipeline 文档中的[安全最佳实践](https://docs.aws.amazon.com/codepipeline/latest/userguide/security-best-practices.html)。
+ 您也可以使用 [cdk-na](https://github.com/cdklabs/cdk-nag) g 实用程序检查 AWS CDK 代码以了解最佳实践。此工具使用一组按包分组的规则来评估您的代码。可用的包有：
  + [AWS 解决方案库](https://github.com/cdklabs/cdk-nag/blob/main/RULES.md#awssolutions)
  + [健康保险流通与责任法案（HIPAA）安全](https://github.com/cdklabs/cdk-nag/blob/main/RULES.md#hipaa-security)
  + [美国国家标准与技术研究院（NIST）800-53 Rev 4](https://github.com/cdklabs/cdk-nag/blob/main/RULES.md#nist-800-53-rev-4)
  + [NIST 800-53 第 5 版](https://github.com/cdklabs/cdk-nag/blob/main/RULES.md#nist-800-53-rev-5)
  + [支付卡行业数据安全标准 (PCI DSS) 3.2.1](https://github.com/cdklabs/cdk-nag/blob/main/RULES.md#pci-dss-321)

## 操作说明
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建虚拟 Python 环境。 | 在 AWS Cloud9 IDE 中，通过运行以下命令创建虚拟 Python 环境并安装所需的依赖项：`make install` | 开发者版 | 
| Bootstrap AWS 账户 和 f AWS 区域 or. AWS CDK | 通过运行以下命令引导所需的 AWS 账户 区域和区域：`make bootstrap account-id=<your-AWS-account-ID> region=<required-region>` | 开发者版 | 

### 为微服务添加新管道
<a name="add-a-new-pipeline-for-a-microservice"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  将示例代码添加至应用程序目录。 | 将包含您的示例应用程序代码的目录添加到克隆的 GitHub [AWS CodeCommit monorepo 多](https://github.com/aws-samples/monorepo-multi-pipeline-trigger)管道触发器存储库中的`monorepo-sample`目录中。 | 开发者版 | 
| 编辑 `monorepo-main.json` 文件。 | 将应用程序代码目录名称和管道名称添加至克隆的存储库中的 `monorepo-main.json` 文件。 | 开发者版 | 
| 创建管道。 | 在适用于存储库的 `Pipelines` 目录中，为您的应用程序添加管道 `class`。该目录包含两个示例文件：`pipeline_hotsite.py` 和 `pipeline_demo.py`。每个文件都有三个阶段：源、构建和部署。您可以复制其中一个文件，并根据应用程序要求对其进行更改。  | 开发者版 | 
| 编辑 `monorepo_config.py` 文件。 | 在 `service_map` 中，添加应用程序的目录名称和为管道创建的分类。例如，以下代码显示了 `Pipelines` 目录中的管道定义，该定义使用名为 `pipeline_mysample.py` 的 `MySamplePipeline` 类文件：<pre>...<br /># Pipeline definition imports<br />from pipelines.pipeline_demo import DemoPipeline<br />from pipelines.pipeline_hotsite import HotsitePipeline<br />from pipelines.pipeline_mysample import MySamplePipeline<br /><br />### Add your pipeline configuration here<br />service_map: Dict[str, ServicePipeline]  = {<br />    # folder-name -> pipeline-class<br />    'demo': DemoPipeline(),<br />    'hotsite': HotsitePipeline(),<br />    'mysample': MySamplePipeline()<br />}</pre> | 开发者版 | 

### 部署堆 MonoRepoStack 栈
<a name="deploy-the-monorepostack-stack"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 AWS CloudFormation 堆栈。 | 通过运行`make deploy-core`命令将带有默认参数值的 AWS CloudFormation `MonoRepoStack`堆栈部署到克隆存储库的根目录中。您可以通过运行 `make deploy-core monorepo-name=<repo_name>` 命令更改存储库名称。您可以使用 `make deploy monorepo-name=<repo_name>` 命令同时部署两个管道。 | 开发者版 | 
| 验证 CodeCommit 存储库。 | 通过运行 `aws codecommit get-repository --repository-name <repo_name>` 命令验证资源是否已创建。由于 CloudFormation 堆栈会创建存储 monorepo 的存储 CodeCommit 库，因此如果您已开始向其中推送修改，请不要运行该`cdk destroy MonoRepoStack `命令。 | 开发者版 | 
| 验证 CloudFormation 堆栈结果。 | 通过运行以下命令验证 CloudFormation `MonoRepoStack`堆栈的创建和配置是否正确：<pre>aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE --query 'StackSummaries[?StackName == 'MonoRepoStack']'</pre> | 开发者版 | 

### 部署堆 PipelinesStack 栈
<a name="deploy-the-pipelinesstack-stack"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 CloudFormation 堆栈。 |  AWS CloudFormation `PipelinesStack`堆栈必须在部署堆`MonoRepoStack`栈后部署。当将新微服务添加至 monorepo 的代码库中时，堆栈的大小会增加，并在加入新微服务时重新部署。通过运行`make deploy-pipelines`命令部署 PipelinesStack 堆栈。您也可以通过运行 `make deploy monorepo-name=<repo_name>` 命令同时部署两个管道。以下示例输出显示了`PipelinesStacks`部署在 URLs 实现结束时如何打印微服务的内容：<pre>Outputs:<br />PipelinesStack.demourl = .cloudfront.net<br />PipelinesStack.hotsiteurl = .cloudfront.net</pre> | 开发者版 | 
| 验证 AWS CloudFormation 堆栈结果。 | 通过运行以下命令验证 AWS CloudFormation `PipelinesStacks`堆栈的创建和配置是否正确：<pre>aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE --query 'StackSummaries[?StackName == 'PipelinesStack']'</pre> | 开发者版 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除您的 AWS CloudFormation 堆栈。 | 运行 `make destroy`命令。 | 开发者版 | 
| 删除管道的 S3 存储桶。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html) | 开发者版 | 

## 问题排查
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 我遇到了 AWS CDK 问题。 | 请参阅 AWS CDK 文档中的[常见 AWS CDK 问题疑难解答](https://docs.aws.amazon.com/cdk/v2/guide/troubleshooting.html)。 | 
| 我推送了我的微服务代码，但微服务管道未运行。 | **设置验证***验证分支配置：*[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)*验证配置文件：*[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)**在控制台上排查问题***AWS CodePipeline 支票：*[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)*AWS Lambda 疑难解答：*[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html) | 
| 我需要重新部署我所有的微服务。 | 有两种方法可强制重新部署所有微服务。选择适合您要求的选项。**方法 1：删除 Parameter Store 中的参数**此方法涉及删除 Systems Manager Parameter Store 中的特定参数，该参数跟踪上次用于部署的提交 ID。删除此参数后，系统将被迫在下次触发时重新部署所有微服务，因为它会将其视为刷新状态。步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)优点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)缺点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)**方法 2：在每个 monorepo 子文件夹中推送一个提交**此方法涉及进行细微的更改，然后将其推送到 monorepo 中的每个微服务子文件夹中，以启动其各自的管道。步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)优点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)缺点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html) | 

## 相关资源
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit-resources"></a>
+ [使用 CDK Pipelines 进行持续集成和交付 (CI/CD)](https://docs.aws.amazon.com/cdk/latest/guide/cdk_pipeline.html)（文档）AWS CDK 
+ [aws-cdk/pipelines 模块（API 参考](https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html)AWS CDK 

# 使用 AWS 将 Bitbucket 存储库与 AWS Amplify 集成 CloudFormation
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation"></a>

*Alwin Abraham，Amazon Web Services*

## Summary
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-summary"></a>

AWS Amplify 可帮助您快速部署和测试静态网站，无需设置通常所需基础设施。如果您的组织想要使用 Bitbucket 进行源代码控制，无论是迁移现有应用程序代码还是构建新应用程序，都可部署这种模式的方法。通过使用 AWS CloudFormation 自动设置 Amplify，您可以查看自己使用的配置。

此模式描述了如何使用 AWS 将 Bitbucket 存储库与 AWS Amplify 集成， CloudFormation 从而创建前端持续集成和持续部署 (CI/CD) 管道和部署环境。此模式方法意味着你可以为可重复的部署构建 Amplify 前端管道。

## 先决条件和限制
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-prereqs"></a>

**先决条件**** **
+ 活跃 Amazon Web Services (AWS) 账户
+ 含管理员访问权限的活跃 Bitbucket 账户
+ 访问使用 [cURL](https://curl.se/) 或 [Postman](https://www.postman.com/) 应用程序的终端
+ 熟悉 Amplify
+ 熟悉 AWS CloudFormation
+ 熟悉 YAML 格式的文件

## 架构
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-architecture"></a>

![\[Diagram showing user interaction with Bitbucket repository connected to AWS Amplify in AWS 云 region.\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/24ae87ed-aa5d-4114-9c5d-bdcb4d40a78b/images/25d73a9d-d2ae-40bc-9ebc-57f9bd13884a.png)


**技术堆栈**
+ Amplify
+ AWS CloudFormation
+ Bitbucket

## 工具
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-tools"></a>
+ [AWS Amplify](https://docs.aws.amazon.com/amplify/) — Amplify 帮助开发人员开发和部署基于云的移动与网络应用程序。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) — AWS CloudFormation 是一项服务，可帮助您建模和设置 AWS 资源，这样您就可以减少管理这些资源的时间，将更多时间集中在在 AWS 中运行的应用程序上。
+ [Bitbucket](https://bitbucket.org/) – Bitbucket 是一款专为专业团队设计的 Git 存储库管理解决方案。它为你提供了集中位置来管理 Git 存储库、协作处理源代码以及指导你完成开发流程。

 

**代码**

该`bitbucket-amplify.yml`文件（附后）包含此模式的 AWS CloudFormation 模板。

## 操作说明
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-epics"></a>

### 配置 Bitbucket 存储库
<a name="configure-the-bitbucket-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| （可选）创建 Bitbucket 存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html)您也可以使用现有的 Bitbucket 存储库。 | DevOps 工程师 | 
| 打开工作区设置。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html) | DevOps 工程师 | 
| 创建 OAuth 消费者。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html) | DevOps 工程师 | 
| 获取 OAuth 访问令牌。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html)`curl -X POST -u "KEY:SECRET" https://bitbucket.org/site/oauth2/access_token -d grant_type=client_credentials `用之前录制的密钥和私密密钥替换 `KEY` 和 `SECRET`。 2. 在不使用引号的情况下，记录访问令牌。该令牌仅在有限时间内有效，默认时间为两个小时。您必须在此时间范围内运行 AWS CloudFormation 模板。 | DevOps 工程师 | 

### 创建和部署 AWS CloudFormation 堆栈
<a name="create-and-deploy-the-aws-cloudformation-stack"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
|  下载 AWS CloudFormation 模板。 | 下载 A `bitbucket-amplify.yml` WS CloudFormation 模板（附后）。除了 Amplify 项目和分支之外，此模板还在 Amplify 中创建 CI/CD 管道。 |  | 
| 创建并部署 AWS CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html)5. 选择**下一步**，然后选择**创建堆栈**。 | DevOps 工程师 | 

### 测试 CI/CD 管道
<a name="test-the-ci-cd-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将代码部署到存储库中的分支。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html)有关这方面的更多信息，请参阅 Bitbucket 文档中的 [Basic Git 命令](https://confluence.atlassian.com/bitbucketserver/basic-git-commands-776639767.html)。  | 应用程序开发人员 | 

## 相关资源
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-resources"></a>

[身份验证方法](https://developer.atlassian.com/bitbucket/api/2/reference/meta/authentication)（Atlassian 文档）

## 附件
<a name="attachments-24ae87ed-aa5d-4114-9c5d-bdcb4d40a78b"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/24ae87ed-aa5d-4114-9c5d-bdcb4d40a78b/attachments/attachment.zip)

# 使用 Step Functions 和 Lambda 代理函数在 AWS 账户上启动 CodeBuild 项目
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function"></a>

*Richard Milner-Watts 和 Amit Anjarlekar，Amazon Web Services*

## Summary
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-summary"></a>

此模式演示了如何使用 AWS Step Functions 和 AWS Lambda 代理函数跨多个 AWS 账户异步启动 AWS CodeBuild 项目。你可以使用模式的示例 Step Functions 状态机来测试你的 CodeBuild 项目是否成功。

CodeBuild 帮助您在完全托管的运行时环境中使用 AWS 命令行界面 (AWS CLI) Line Interface 启动操作任务。您可以通过覆盖环境变量来更改 CodeBuild 项目在运行时的行为。此外，您还可以使用 CodeBuild 来管理工作流程。有关更多信息，请参阅 AWS Workshop 网站上的[服务目录工具](https://service-catalog-tools-workshop.com/tools.html)和在 AWS 数据库博客上使用 AWS [在 Amazon RDS for PostgreSQL 中安排作业，并在 CodeBuild AWS 数据库博客上使用 EventBridge](https://aws.amazon.com/blogs/database/schedule-jobs-in-amazon-rds-for-postgresql-using-aws-codebuild-and-amazon-eventbridge/)亚马逊安排作业。

## 先决条件和限制
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-prereqs"></a>

**先决条件**
+ 两个活跃的 AWS 账户：一个用于通过 Step Functions 调用 Lambda 代理函数的源账户和一个用于构建远程示例项目的目标账户 CodeBuild 

**限制**
+ 此模式不能用于在账户之间复制[构件](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-codebuild-project-artifacts.html)。

## 架构
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-architecture"></a>

下图显示此模式构建的架构。

![\[跨多个 AWS 账户启动 CodeBuild 项目的架构图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/809a5716-56e5-477c-aac6-02243675a2f2/images/857ba3ae-eb9a-4d6b-b73e-e596f41c8cb8.png)


下图显示了如下工作流：

1. Step Functions 状态机解析提供的输入映射，并为您定义的每个账户、区域和项目调用 Lambda 代理函数（`codebuild-proxy-lambda`）。

1. Lambda 代理函数使用 AWS Security Token Service（AWS STS）代入 IAM 代理角色 (`codebuild-proxy-role`)，而该角色会与目标账户中 IAM 策略 (`codebuild-proxy-policy`) 关联。

1. 使用代入的角色，Lambda 函数启动 CodeBuild 项目并返回 CodeBuild 任务 ID。Step Functions 状态机循环并轮询 CodeBuild 作业，直到收到成功或失败状态。

状态机逻辑如下图所示。

![\[Step Functions 状态机的工作流\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/809a5716-56e5-477c-aac6-02243675a2f2/images/4729bbfc-79ad-455d-a85a-b96cce00f432.png)


**技术堆栈**
+ AWS CloudFormation
+ CodeBuild
+ IAM
+ Lambda
+ Step Functions
+ X-Ray

## 工具
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-tools"></a>
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可帮助您设置 AWS 资源，快速一致地配置这些资源，并在 AWS 账户和区域的整个生命周期中对其进行管理。
+ [AWS CloudFormation Designer](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/working-with-templates-cfn-designer-json-editor.html) 提供了一个集成的 JSON 和 YAML 编辑器，可帮助您查看和编辑 CloudFormation 模板。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管的构建服务，可帮助您编译源代码、运行单元测试和生成可随时部署的项目。
+ [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) 是一项计算服务，可帮助您运行代码，而无需预置或管理服务器。它仅在需要时运行您的代码，并且能自动扩缩，因此您只需为使用的计算时间付费。
+ [AWS Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/welcome.html) 是一项无服务器编排服务，可让您搭配使用 AWS Lambda 函数和其他 Amazon Web Services 来构建业务关键型应用程序。
+ [AWS X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html) – 帮助您收集您的应用程序所服务的请求的相关数据，并提供用于查看、筛选和获取数据洞察力的工具，以确定问题和发现优化机会。

**代码**

此模式的示例代码可在 GitHub[跨账户 CodeBuild 代理](https://github.com/aws-samples/cross-account-codebuild-proxy)存储库中找到。此模式使用 AWS Lambda Powertools for Python 库来提供日志和跟踪功能。有关此库及其实用程序的更多信息，请参阅 [Powertools for AWS Lambda (Python)](https://docs.powertools.aws.dev/lambda/python/latest/)。

## 最佳实践
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-best-practices"></a>

1. 调整 Step Function 状态机中的等待时间值，以最大限度地减少对任务状态的轮询请求。使用 CodeBuild 项目的预期执行时间。

1. 在 Step Functions 中调整地图的`MaxConcurrency`属性以控制可以并行运行的 CodeBuild 项目数量。

1. 如有必要，请查看示例代码是否已准备就绪可供生产。考虑解决方案可能记录哪些数据，以及默认的 Amazon CloudWatch 加密是否足够。

## 操作说明
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-epics"></a>

### 在源账户中创建 Lambda 代理函数和关联 IAM 角色
<a name="create-the-lambda-proxy-function-and-associated-iam-role-in-the-source-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 记录 AWS 账户 IDs。 | 需要 AWS 账户 IDs 才能设置跨账户的访问权限。记录您的源账户和目标账户的 Amazon Web Services account ID。有关更多信息，请参阅 IAM 文档中的[查找您 Amazon Web Services account ID](https://docs.aws.amazon.com/IAM/latest/UserGuide/console_account-alias.html#FindingYourAWSId)。 | AWS DevOps | 
| 下载 AWS CloudFormation 模板。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html)在 AWS CloudFormation 模板中，`<SourceAccountId>`是源账户的 AWS 账户 ID，`<TargetAccountId>`也是目标账户的 AWS 账户 ID。 | AWS DevOps | 
| 创建并部署 AWS CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html)在目标账户中创建任何资源之前，您必须为代理 Lambda 函数创建 AWS CloudFormation 堆栈。当您在目标账户中创建信任策略时，IAM 角色会从角色名称转换至内部标识符。所以 IAM 角色必须已经存在。 | AWS DevOps | 
| 确认代理函数和状态机已创建。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | AWS DevOps | 

### 在目标账户中创建 IAM 角色并启动示例 CodeBuild 项目
<a name="create-an-iam-role-in-the-target-account-and-launch-a-sample-codebuild-project"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建并部署 AWS CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | AWS DevOps | 
| 验证示例 CodeBuild 项目的创建。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | AWS DevOps | 

### 测试跨账户 Lambda 代理函数
<a name="test-the-cross-account-lambda-proxy-function"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动状态机。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | AWS DevOps | 
| 验证环境变量。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | AWS DevOps | 

## 问题排查
<a name="launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| Step Functions 的执行时间比预期时间要长。 | 在 Step Function 状态机中调整地图的`MaxConcurrency`属性以控制可以并行运行多少 CodeBuild 项目。 | 
|  CodeBuild 任务的执行时间比预期的要长。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/launch-a-codebuild-project-across-aws-accounts-using-step-functions-and-a-lambda-proxy-function.html) | 

# 使用应用程序恢复控制器管理 EMR 集群的多可用区失效转移
<a name="multi-az-failover-spark-emr-clusters-arc"></a>

*Aarti Rajput、Ashish Bhatt、Neeti Mishra 和 Nidhi Sharma，Amazon Web Services*

## Summary
<a name="multi-az-failover-spark-emr-clusters-arc-summary"></a>

此模式可为 Amazon EMR 工作负载提供有效的灾难恢复策略，帮助确保单个 AWS 区域内多个可用区之间的高可用性和数据一致性。该设计使用 [Amazon 应用程序恢复控制器](https://docs.aws.amazon.com/r53recovery/latest/dg/what-is-route53-recovery.html)和[应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html)，为基于 Apache Spark 的 EMR 集群管理失效转移操作和流量分配。

在标准条件下，主可用区托管活动的 EMR 集群和具有完整 read/write 功能的应用程序。如果可用区意外发生故障，流量将自动重定向到辅助可用区，并在那里启动一个新的 EMR 集群。两个可用区均通过专用的[网关端点](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-s3.html)访问共享的 Amazon Simple Storage Service（Amazon S3）存储桶，从而确保数据管理的一致性。这种方法可以最大限度地减少停机时间，并在可用区发生故障时快速恢复关键的大数据工作负载。解决方案适用于金融、零售等实时分析至关重要的行业。

## 先决条件和限制
<a name="multi-az-failover-spark-emr-clusters-arc-prereqs"></a>

**先决条件**
+ 有效的 [AWS 账户](https://aws.amazon.com/resources/create-account/)
+ [亚马逊弹性计算云（亚马逊）上的亚马逊 EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html) EC2
+ 从 EMR 集群的主节点访问 Amazon S3。
+ AWS 多可用区基础架构

**限制**
+ 有些 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)页面，然后选择相应服务的链接。

**产品版本**
+ [Amazon EMR 6.x 或更高版本](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-release-components.html)

## 架构
<a name="multi-az-failover-spark-emr-clusters-arc-architecture"></a>

**目标技术堆栈**
+ Amazon EMR 集群
+ Amazon Application Recovery Controller
+ 应用程序负载均衡器
+ 亚马逊 S3 存储桶
+ 适用于 Amazon S3 的网关端点

**目标架构**

![\[含应用程序恢复控制器的自动恢复机制的架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e5ecdb66-0eef-4a6a-8367-982a55104748/images/e982d580-13db-4bdd-9f6b-6400d7c31c01.png)


此架构通过使用多个可用区，并借助应用程序恢复控制器实施自动化恢复机制，提供应用程序弹性。

1. 应用程序负载均衡器将流量路由到活动的 Amazon EMR 环境，通常是主可用区中的主 EMR 集群。

1. 活动的 EMR 集群处理应用程序请求，并通过其专用 Amazon S3 网关端点连接到 Amazon S3，以进行读取和写入操作。

1. Amazon S3 充当中央数据存储库，可能用作检查点或 EMR 集群之间的共享存储区。EMR 集群通过 `s3://` 协议和 [EMR 文件系统（EMRFS）](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-fs.html)直接写入 Amazon S3 时可以保持数据一致性。

1. 应用程序恢复控制器持续监控主可用区的运行状况，并在必要时自动管理失效转移操作。

1. 如果应用程序恢复控制器在主 EMR 集群中检测到故障，将采取以下措施：
   + 启动失效转移到可用区 2 中的辅助 EMR 集群的过程。
   + 更新路由配置以将流量定向至辅助集群。

## 工具
<a name="multi-az-failover-spark-emr-clusters-arc-tools"></a>

**AWS 服务**
+ [Amazon 应用程序恢复控制器****](https://docs.aws.amazon.com/r53recovery/latest/dg/what-is-route53-recovery.html)可帮助您管理和协调跨 AWS 区域 可用区的应用程序恢复。通过减少传统工具和流程所需的手动步骤，此服务简化了流程并提高了应用程序恢复的可靠性。
+ [应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html)在应用程序层运行，这是开放系统互连（OSI）模型的第 7 层。它在多个可用区中的多个目标（例如 EC2 实例）之间分配传入的应用程序流量。这将提高应用程序的可用性。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您 AWS 服务 通过命令行 shell 中的命令进行交互。
+ [Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html) 是一个大数据平台，可为 Apache Spark、Apache Hive、Presto 等开源框架提供数据处理、交互式分析和机器学习功能。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 提供了一个简单 Web 服务接口，可用于随时随地存储和检索任何数量的数据。借助此服务，您可以轻松构建利用云原生存储的应用程序。
+ [Amazon S3 的网关终端节点是您在路由表中指定的网关，用于](https://docs.aws.amazon.com/vpc/latest/privatelink/vpc-endpoints-s3.html)通过 AWS 网络从您的虚拟私有云 (VPC) 访问 Amazon S3。

## 最佳实践
<a name="multi-az-failover-spark-emr-clusters-arc-best-practices"></a>
+ 遵循 [AWS 安全性、身份和合规性最佳实践](https://aws.amazon.com/architecture/security-identity-compliance/?cards-all.sort-by=%5b…%5d.sort-order=desc&awsf.content-type=*all&awsf.methodology=*all)，确保架构强大且安全。
+ 确保架构符合 [AWS Well-Architected Framework](https://aws.amazon.com/architecture/well-architected/)。
+ 使用 Amazon S3 访问权限管控功能来管理基于 Spark 的 EMR 集群对 Amazon S3 的访问权限。有关详细信息，请参阅博客文章：[Use Amazon EMR with S3 Access Grants to Scale Spark access to Amazon S3](https://aws.amazon.com/blogs/big-data/use-amazon-emr-with-s3-access-grants-to-scale-spark-access-to-amazon-s3/)。
+ [使用亚马逊 S3 提高 Spark 性能](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-s3-performance.html)。

## 操作说明
<a name="multi-az-failover-spark-emr-clusters-arc-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 登录到 AWS 管理控制台。 | 以 IAM 用户身份登录 [AWS 管理控制台](https://console.aws.amazon.com/)。有关说明，请参阅 [AWS 文档](https://docs.aws.amazon.com/signin/latest/userguide/introduction-to-iam-user-sign-in-tutorial.html)。 | AWS DevOps | 
| 配置 AWS CLI。**** | 安装 AWS CLI 或将其更新到最新版本，以便可以在 AWS 服务 中进行交互 AWS 管理控制台。有关说明，请参阅 [AWS CLI 文档](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)。 | AWS DevOps | 

### 在 EMR 集群上部署 Spark 应用程序
<a name="deploy-a-spark-application-on-your-emr-cluster"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 S3 存储桶。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | AWS DevOps | 
| 创建 EMR 集群。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | AWS DevOps | 
| 配置 EMR 集群的安全设置。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | AWS DevOps | 
| 连接到 EMR 集群。 | 使用所提供的密钥对，通过 SSH 连接到 EMR 集群的主节点。请确保密钥对文件与您的应用程序位于同一目录下。运行以下命令为密钥对设置正确的权限并建立 SSH 连接：<pre>chmod 400 <key-pair-name><br />ssh -i ./<key-pair-name> hadoop@<master-node-public-dns></pre> | AWS DevOps | 
| 部署 Spark 应用程序。 | 建立 SSH 连接后，您将进入 Hadoop 控制台。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | AWS DevOps | 
| 监控 Spark 应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | AWS DevOps | 

### 将流量转移到其他可用区
<a name="shift-traffic-to-another-availability-zone"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建应用程序负载均衡器。 | 在 AWS 区域内设置目标组，在跨两个可用区的 Amazon EMR 主节点之间路由流量。有关说明，请参阅弹性负载均衡文档中的[为应用程序负载均衡器创建目标组](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-target-group.html)。 | AWS DevOps | 
| 在应用程序恢复控制器中配置可用区转移 | 在此步骤中，您需要使用应用程序恢复控制器中的[可用区转移功能](https://docs.aws.amazon.com/r53recovery/latest/dg/arc-zonal-shift.html)将流量转移到另一个可用区。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html)要使用 AWS CLI，请参阅应用程序恢复控制器文档[中的 AWS CLI 带区域偏移的使用示例](https://docs.aws.amazon.com/r53recovery/latest/dg/getting-started-cli-zonalshift.html)。 | AWS DevOps | 
| 验证可用区转移配置和进度。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | AWS DevOps | 

## 相关资源
<a name="multi-az-failover-spark-emr-clusters-arc-resources"></a>
+ AWS CLI 命令：
  + [create-cluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/create-cluster.html)
  + [describe-cluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/emr/describe-cluster.html)
  + [arc-zonal-shift](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/arc-zonal-shift/index.html)
+ [为竞价型实例配置 Amazon EMR 集群实例类型和最佳实践](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-plan-instances-guidelines.html)（Amazon EMR 文档）
+ [IAM 中的安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)（IAM 文档）
+ [使用实例配置文件](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html)（IAM 文档）
+ [使用可用区转移和可用区自动转移来恢复 ARC 中的应用程序](https://docs.aws.amazon.com/r53recovery/latest/dg/multi-az.html)（应用程序恢复控制器文档）

# 使用 AWS 代码服务和 AWS KMS 多区域密钥管理向多个账户和区域 blue/green 部署的微服务
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys"></a>

*Balaji Vedagiri、Vanitha Dontireddy、Ashish Kumar、Faisal Shahdad、Vivek Thangamuthu 和 Anand Krishna Varanasi，Amazon Web Services*

## Summary
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-summary"></a>

此模式描述了如何根据部署策略将全球微服务应用程序从中央 AWS 账户 blue/green 部署到多个工作负载账户和区域。该模式支持以下内容：
+ 软件是在一个中心账户中开发的，而工作负载和应用程序则分布在多个账户和 AWS 区域中。
+ 单个 AWS 密钥管理系统（AWS KMS）多区域密钥用于加密和解密，以涵盖灾难恢复。
+ KMS 密钥是特定于区域的，必须在三个不同的区域中维护或创建管道构件。KMS 多区域密钥有助于跨区域保留相同的密钥 ID。
+ Git 工作流分支模型由两个分支（开发分支和主分支）实现，使用拉取请求 (PRs) 合并代码。从此堆栈部署的 AWS Lambda 函数创建了一个从开发分支到主分支的 PR。PR 合并到主分支会启动 AWS CodePipeline 管道，该管道协调持续集成和持续交付 (CI/CD) 流程，并将堆栈部署到各个账户。

此模式提供了通过 AWS CloudFormation 堆栈设置的基础设施即代码 (IaC) 示例，以演示此用例。微服务的 blue/green 部署是使用 AWS CodeDeploy 实现的。

## 先决条件和限制
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-prereqs"></a>

**先决条件**
+ 四个活跃的 Amazon Web Services account：
  + 用于管理代码管道和维护 AWS CodeCommit 存储库的工具账户。
  + 用于部署微服务工作负载的三个工作负载（测试）账户。
+ 此模式使用以下区域。如果您想使用其他区域，则必须对 AWS CodeDeploy 和 AWS KMS 多区域堆栈进行适当的修改。
  + 工具 (AWS CodeCommit) 账户：`ap-south-1`
  + 工作负载（测试）账户 1：`ap-south-1`
  + 工作负载(测试)账户 2： `eu-central-1`
  + 工作负载(测试)账户 3： `us-east-1`
+ 每个工作负载账户中用于部署区域的三个 Amazon Simple Storage Service (Amazon S3) 桶。（在此模式中，它们稍后被称为 `S3BUCKETNAMETESTACCOUNT1`、`S3BUCKETNAMETESTACCOUNT2 ` 和 `S3BUCKETNAMETESTACCOUNT3 `。）

  例如，您可以在特定账户和区域中使用唯一的桶名称创建这些桶，如下所示（将 *xxxx* 替换为随机数）：

  ```
  ##In Test Account 1
  aws s3 mb s3://ecs-codepipeline-xxxx-ap-south-1 --region ap-south-1
  ##In Test Account 2
  aws s3 mb s3://ecs-codepipeline-xxxx-eu-central-1 --region eu-central-1
  ##In Test Account 3
  aws s3 mb s3://ecs-codepipeline-xxxx-us-east-1 --region us-east-1
  
  #Example
  ##In Test Account 1
  aws s3 mb s3://ecs-codepipeline-18903-ap-south-1 --region ap-south-1
  ##In Test Account 2
  aws s3 mb s3://ecs-codepipeline-18903-eu-central-1 --region eu-central-1
  ##In Test Account 3
  aws s3 mb s3://ecs-codepipeline-18903-us-east-1 --region us-east-1
  ```

**限制**

该模式使用 AWS CodeBuild 和其他配置文件来部署示例微服务。如果您有不同的工作负载类型（例如无服务器），则必须更新所有相关配置。

## 架构
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-architecture"></a>

**目标技术堆栈**
+ AWS CloudFormation
+ AWS CodeCommit
+ AWS CodeBuild
+ AWS CodeDeploy
+ AWS CodePipeline

**目标架构**

![\[用于将微服务部署到多个账户和区域的目标架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a144c977-6823-4b08-a215-fae779b3ce7c/images/eedfabdb-f266-4190-b271-5caf7ac9b47b.png)


**自动化和扩缩**

使用 AWS CloudFormation 堆栈模板 (IaC) 自动完成设置。它可以轻松扩展到多个环境和账户。

## 工具
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-tools"></a>

**AWS 服务**
+ [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 CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html) 自动部署到亚马逊弹性计算云 (Amazon EC2) 或本地实例、AWS Lambda 函数或亚马逊弹性容器服务 (Amazon ECS) 服务。
+ [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) 是一项安全、可扩展且可靠的托管容器映像注册表服务。
+ [Amazon Elastic Container Service (Amazon ECS)](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html)是一项快速且可扩展的容器管理服务，可帮助运行、停止和管理集群上的容器。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可帮助您创建和控制加密密钥，以帮助保护您的数据。
+ [Amazon Simple Storage Service(Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**其他工具**
+ [Git](https://git-scm.com/docs) 是一个开源的分布式版本控制系统，可与 AWS CodeCommit 存储库配合使用。
+ [Docker](https://www.docker.com/) 是一组平台即服务（PaaS）产品，它们使用操作系统级别的虚拟化技术在容器中交付软件。该模式使用 Docker 在本地构建和测试容器映像。
+ [cfn-lint](https://github.com/aws-cloudformation/cfn-lint) 和 [cfn-nag](https://github.com/stelligent/cfn_nag) 是开源工具，可帮助您检查 CloudFormation 堆栈中是否存在任何错误和安全问题。

**代码存储库**

此模式的代码可在[多个地区的 GitHub 全球 Blue/Green 部署和账户存储库中](https://github.com/aws-samples/ecs-blue-green-global-deployment-with-multiregion-cmk-codepipeline)找到。

## 操作说明
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 导出用于 CloudFormation 堆栈部署的环境变量。 | 定义环境变量，这些变量将在此模式的后面用作 CloudFormation 堆栈的输入。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 

### Package 并部署 CloudFormation 基础架构的堆栈
<a name="package-and-deploy-the-cloudformation-stacks-for-the-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 将[示例存储库](https://github.com/aws-samples/ecs-blue-green-global-deployment-with-multiregion-cmk-codepipeline)克隆到您工作位置的新存储库中：<pre>##In work location<br />git clone https://github.com/aws-samples/ecs-blue-green-global-deployment-with-multiregion-cmk-codepipeline.git</pre> | AWS DevOps | 
| 打包 Cloudformation 资源。 | 在此步骤中，您将打包 CloudFormation 模板引用的本地项目，以创建亚马逊虚拟私有云 (Amazon VPC) 和Application Load Balancer等服务所需的基础设施资源。这些模板位于代码存储库的 `Infra` 文件夹中。<pre>##In TestAccount1##<br />aws cloudformation package \<br />    --template-file mainInfraStack.yaml \<br />    --s3-bucket $S3BUCKETNAMETESTACCOUNT1 \<br />    --s3-prefix infraStack \<br />    --region $TESTACCOUNT1REGION \<br />    --output-template-file infrastructure_${TESTACCOUNT1}.template</pre><pre>##In TestAccount2##<br />aws cloudformation package \<br />    --template-file mainInfraStack.yaml \<br />    --s3-bucket $S3BUCKETNAMETESTACCOUNT2 \<br />    --s3-prefix infraStack \<br />    --region $TESTACCOUNT2REGION \<br />    --output-template-file infrastructure_${TESTACCOUNT2}.template</pre><pre>##In TestAccount3##<br />aws cloudformation package \<br />    --template-file mainInfraStack.yaml \<br />    --s3-bucket $S3BUCKETNAMETESTACCOUNT3 \<br />    --s3-prefix infraStack \<br />    --region $TESTACCOUNT3REGION \<br />    --output-template-file infrastructure_${TESTACCOUNT3}.template</pre> | AWS DevOps | 
| 验证程序包模板。 | 验证程序包模板：<pre>aws cloudformation validate-template \<br />    --template-body file://infrastructure_${TESTACCOUNT1}.template<br /><br />aws cloudformation validate-template \<br />    --template-body file://infrastructure_${TESTACCOUNT2}.template<br /><br />aws cloudformation validate-template \<br />    --template-body file://infrastructure_${TESTACCOUNT3}.template</pre> | AWS DevOps | 
| 将包文件部署到工作负载账户中， | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 

### 推送示例图像并扩展 Amazon ECS
<a name="push-a-sample-image-and-scale-amazon-ecs"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将示例图像推送到 Amazon ECR 存储库。 | 将一个示例 (NGINX) 图像推送到名为 `web` 的 Amazon Elastic Container Registry (Amazon ECR) 存储库中（如参数中所设置）。您可以根据需要自定义图像。要登录并设置用于将图像推送到 Amazon ECR 的凭证，请按照 [Amazon ECR 文档](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)中的说明进行操作。命令包括：<pre>  docker pull nginx<br />  docker images<br />  docker tag <imageid> aws_account_id.dkr.ecr.region.amazonaws.com/<web>:latest<br />  docker push <aws_account_id>.dkr.ecr.<region>.amazonaws.com/<web>:tag </pre> | AWS DevOps | 
| 扩展 Amazon ECS 并验证访问权限。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 

### 设置代码服务和资源
<a name="set-up-code-services-and-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在工具账户中创建 CodeCommit 存储库。 | 使用模板在工具帐户中创建 CodeCommit 存储库，该`codecommit.yaml`模板位于 GitHub 存储库的`code`文件夹中。您只能在计划开发代码的单个区域中创建此存储库。<pre>aws cloudformation deploy --stack-name codecommitrepoStack --parameter-overrides  CodeCommitReponame=$CODECOMMITREPONAME \<br />ToolsAccount=$TOOLSACCOUNT --template-file codecommit.yaml  --region $TOOLSACCOUNTREGION \<br />--capabilities CAPABILITY_NAMED_IAM</pre> | AWS DevOps | 
| 创建 S3 存储桶，用于管理由生成的项目 CodePipeline。 | 创建一个 S3 存储桶，用于管理 CodePipeline 通过使用`pre-reqs-bucket.yaml`模板生成的项目，该模板位于 GitHub 存储库的`code`文件夹中。堆栈必须部署在所有三个工作负载（测试）和工具账户和区域中。<pre>aws cloudformation deploy --stack-name pre-reqs-artifacts-bucket --parameter-overrides BucketStartName=$BUCKETSTARTNAME \<br />TestAccount1=$TESTACCOUNT1 TestAccount2=$TESTACCOUNT2 \<br />TestAccount3=$TESTACCOUNT3 CodeCommitAccount=$CODECOMMITACCOUNT ToolsAccount=$TOOLSACCOUNT \<br />--template-file pre-reqs_bucket.yaml --region $TESTACCOUNT1REGION --capabilities CAPABILITY_NAMED_IAM<br /><br />aws cloudformation deploy --stack-name pre-reqs-artifacts-bucket --parameter-overrides BucketStartName=$BUCKETSTARTNAME \<br />TestAccount1=$TESTACCOUNT1 TestAccount2=$TESTACCOUNT2 \<br />TestAccount3=$TESTACCOUNT3 CodeCommitAccount=$CODECOMMITACCOUNT ToolsAccount=$TOOLSACCOUNT \<br />--template-file pre-reqs_bucket.yaml --region $TESTACCOUNT2REGION --capabilities CAPABILITY_NAMED_IAM<br /><br />aws cloudformation deploy --stack-name pre-reqs-artifacts-bucket --parameter-overrides BucketStartName=$BUCKETSTARTNAME \<br />TestAccount1=$TESTACCOUNT1 TestAccount2=$TESTACCOUNT2 \<br />TestAccount3=$TESTACCOUNT3 CodeCommitAccount=$CODECOMMITACCOUNT ToolsAccount=$TOOLSACCOUNT \<br />--template-file pre-reqs_bucket.yaml --region $TESTACCOUNT3REGION --capabilities CAPABILITY_NAMED_IAM<br /><br />aws cloudformation deploy --stack-name pre-reqs-artifacts-bucket --parameter-overrides BucketStartName=$BUCKETSTARTNAME \<br />TestAccount1=$TESTACCOUNT1 TestAccount2=$TESTACCOUNT2 \<br />TestAccount3=$TESTACCOUNT3 CodeCommitAccount=$CODECOMMITACCOUNT ToolsAccount=$TOOLSACCOUNT \<br />--template-file pre-reqs_bucket.yaml --region $TOOLSACCOUNTREGION --capabilities CAPABILITY_NAMED_IAM</pre> | AWS DevOps | 
| 设置多区域 KMS 密钥。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 
| 在工具账户中设置 CodeBuild 项目。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 
|  CodeDeploy 在工作负载帐户中进行设置。 | 使用 GitHub 存储库`code`文件夹中的`codedeploy.yaml`模板在所有三个工作负载帐户 CodeDeploy 中进行设置。的输出`mainInfraStack`包括 Amazon ECS 集群的亚马逊资源名称 (ARNs) 和 Application Load Balancer 侦听器。基础架构堆栈中的值已经导出，因此它们由 CodeDeploy 堆栈模板导入。<pre>##WorkloadAccount1##<br />aws cloudformation deploy --stack-name ecscodedeploystack \<br />--parameter-overrides  ToolsAccount=$TOOLSACCOUNT mainInfrastackname=mainInfrastack \<br />--template-file codedeploy.yaml  --region $TESTACCOUNT1REGION --capabilities CAPABILITY_NAMED_IAM<br /><br />##WorkloadAccount2##<br />aws cloudformation deploy --stack-name ecscodedeploystack \<br />--parameter-overrides ToolsAccount=$TOOLSACCOUNT mainInfrastackname=mainInfrastack \<br />--template-file codedeploy.yaml  --region $TESTACCOUNT2REGION --capabilities CAPABILITY_NAMED_IAM<br /><br />##WorkloadAccount3##<br />aws cloudformation deploy --stack-name ecscodedeploystack \<br />--parameter-overrides ToolsAccount=$TOOLSACCOUNT mainInfrastackname=mainInfrastack \<br />--template-file codedeploy.yaml  --region $TESTACCOUNT3REGION --capabilities CAPABILITY_NAMED_IAM</pre> | AWS DevOps | 

### CodePipeline 在工具账户中设置
<a name="set-up-codepipeline-in-the-tools-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在工具账户中创建代码管道。 | 在工具账户中，运行以下命令：<pre>aws cloudformation deploy --stack-name ecscodepipelinestack --parameter-overrides  \<br />TestAccount1=$TESTACCOUNT1 TestAccount1Region=$TESTACCOUNT1REGION \<br />TestAccount2=$TESTACCOUNT2 TestAccount2Region=$TESTACCOUNT2REGION \<br />TestAccount3=$TESTACCOUNT3 TestAccount3Region=$TESTACCOUNT3REGION \<br />CMKARNTools=$CMKTROOLSARN CMKARN1=$CMKARN1 CMKARN2=$CMKARN2 CMKARN3=$CMKARN3 \<br />CodeCommitRepoName=$CODECOMMITREPONAME BucketStartName=$BUCKETSTARTNAME \<br />--template-file codepipeline.yaml --capabilities CAPABILITY_NAMED_IAM</pre> | AWS DevOps | 
| 在 AWS KMS 密钥策略 CodePipeline 和 S3 存储桶策略中提供访问权限和 CodeBuild 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | AWS DevOps | 

### 调用并测试管道
<a name="call-and-test-the-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将更改推送到 CodeCommit 存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) |  | 

### 清理
<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/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) |  | 

## 问题排查
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 您提交到存储库的更改不会得到部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.html) | 

## 相关资源
<a name="manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys-resources"></a>
+ [推送 Docker 映像](https://docs.aws.amazon.com/AmazonECR/latest/userguide/docker-push-ecr-image.html)（Amazon ECR 文档)
+ [连接到 AWS CodeCommit 存储库](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)（AWS CodeCommit 文档）
+ [AWS 疑难解答 CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/troubleshooting.html)（AWS CodeBuild 文档）

# 使用 AWS 和 AWS CloudFormation Config 监控亚马逊 ECR 存储库的通配符权限
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config"></a>

*Vikrant Telkar、Wassim Benhallam 和 Sajid Momin，Amazon Web Services*

## Summary
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-summary"></a>

在 Amazon Web Services (AWS) Cloud 上，Amazon Elastic Container Registry (Amazon ECR) 是一项托管容器映像注册表服务，支持使用 AWS Identity and Access Management（AWS IAM）且具有基于资源权限的私有存储库。

IAM 在资源和操作属性中均支持“`*`”通配符，这使得自动选择多个匹配项变得更加容易。在您的测试环境中，您可以通过在[存储库策略语句](https://docs.aws.amazon.com/AmazonECR/latest/userguide/set-repository-policy.html)的主体元素中使用 `ecr:*` [通配符权限](https://docs.aws.amazon.com/lambda/latest/operatorguide/wildcard-permissions-iam.html)来允许所有经过身份验证的 AWS 用户访问 Amazon ECR 存储库。在无法访问生产数据的开发账户中进行开发和测试时，`ecr:*` 通配符权限非常有用。

但是，您必须确保在生产环境中不使用 `ecr:*` 通配符权限，因为它可能会导致严重的安全漏洞。此模式的方法可帮助您识别在存储库策略语句中包含 `ecr:*` 通配符权限的 Amazon ECR 存储库。  该模式提供了在 AWS Config 中创建自定义规则的步骤和 AWS CloudFormation 模板。然后，AWS Lambda 函数会监控您的 Amazon ECR 存储库策略语句中是否有 `ecr:*` 个通配符权限。如果发现不合规的存储库策略声明，Lambda 会通知 AWS Config 向亚马逊发送事件，然后启动 EventBridge EventBridge 亚马逊简单通知服务 (Amazon SNS) Simple Notification Service 主题。SNS 主题通过电子邮件通知您有关不合规的存储库策略语句。

## 先决条件和限制
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account。
+ 已安装和配置 AWS 命令行界面（AWS CLI）。有关更新 Amazon CLI 的信息，请参阅 AWS CLI 文档中的[安装、更新和卸载 Amazon CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)。
+ 在测试环境中安装和配置的带有附加策略语句的现有 Amazon ECR 存储库。有关更多信息，请参阅 Amazon ECR 文档中的[创建私有存储库](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)和[设置存储库策略语句](https://docs.aws.amazon.com/AmazonECR/latest/userguide/set-repository-policy.html)。
+ AWS Config，已在您首选的 AWS 区域中配置。有关此内容的更多信息，请参阅 [AWS Config 文档中的 AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/getting-started.html) 入门。
+ `aws-config-cloudformation.template` 文件（附加）已下载到本地计算机。

 

**限制**
+ 此模式的解决方案是区域性的，您的资源必须在同一区域中创建。 

## 架构
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-architecture"></a>

下图显示了 AWS Config 如何评估 Amazon ECR 存储库策略语句。 

![\[AWS Config workflow with Lambda, Amazon ECR, EventBridge, SNS, and email notification components.\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/01bbf5f8-27aa-4c64-9a03-7fcccc0955b8/images/49bbf14b-0a18-4d4a-86ab-162d37708e01.png)


下图显示了如下工作流：

1. AWS Config 启动自定义规则。 

1. 自定义规则调用 Lambda 函数来评估 Amazon ECR 存储库策略语句的合规性。然后，Lambda 函数会识别不合规的存储库策略语句。

1. Lambda 函数将不合规状态发送到 AWS Config。

1. AWS Config 向发送事件 EventBridge。

1. EventBridge 向 SNS 主题发布不合规通知。

1. Amazon SNS 会向您或授权用户发送电子邮件提醒。

**自动化和扩缩**

此模式的解决方案可以监控任意数量的 Amazon ECR 存储库策略语句，但您要评估的所有资源必须在同一区域中创建。

## 工具
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-tools"></a>
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) — AWS CloudFormation 可帮助您建模和设置 AWS 资源，快速一致地配置这些资源，并在资源的整个生命周期中对其进行管理。您可以使用模板来描述资源及其依赖关系，然后将它们作为堆栈一起启动和配置，而不必单独管理资源。您可以跨多个 Amazon Web Services account 和 AWS 区域管理和预置堆栈。
+ [AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html) - AWS Config 提供 Amazon Web Services account 中 AWS 资源配置的详细视图。这些信息包括资源之间的关联方式以及资源以前的配置方式，让您了解资源的配置和关系如何随着的时间的推移而更改。
+ [Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)** **-** **Amazon Elastic Container Registry (Amazon ECR) 是一项安全、可扩展且可靠的 AWS 托管容器映像注册表服务。Amazon ECR 支持私有存储库，其具有使用 IAM 的基于资源的权限。                                
+ [Ama](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) zon EventBridge — Amazon EventBridge 是一项无服务器事件总线服务，可用于将应用程序与来自各种来源的数据连接起来。 EventBridge 将来自您的应用程序、软件即服务 (SaaS) 应用程序和 AWS 服务的实时数据流传输到目标，例如 AWS Lambda 函数、使用 API 目标的 HTTP 调用终端节点或其他账户中的事件总线。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) – AWS Lambda 是一项计算服务，支持无需预置或管理服务器即可运行代码。只有在需要时 Lambda 才运行您的代码，并且能自动扩缩，从每天几个请求扩展到每秒数千个请求。您只需为消耗的计算时间付费 - 代码未运行时不产生费用。
+ [Amazon SNS](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) – Amazon Simple Notiﬁcation Service (Amazon SNS) 可协调和管理发布者和客户端之间消息的传送或发送，包括 Web 服务器和电子邮件地址。订阅用户接收所有发布至他们所订阅主题的消息，并且一个主题的所有订阅用户收到的消息都相同。 

**代码**

此模式的代码可在 `aws-config-cloudformation.template` 文件（附件）中获取。

## 操作说明
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-epics"></a>

### 创建 AWS CloudFormation 堆栈
<a name="create-the-aws-cloudformation-stack"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 AWS CloudFormation 堆栈。 | 在 AWS CLI 中运行以下命令来创建 AWS CloudFormation 堆栈：<pre>$ aws cloudformation create-stack --stack-name=AWSConfigECR \<br />    --template-body  file://aws-config-cloudformation.template \<br />    --parameters ParameterKey=<email>,ParameterValue=<myemail@example.com> \<br />    --capabilities CAPABILITY_NAMED_IAM</pre> | AWS DevOps | 

### 测试 AWS Config 自定义规则
<a name="test-the-aws-config-custom-rule"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 测试 AWS Config 自定义规则。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config.html) | AWS DevOps | 

## 附件
<a name="attachments-01bbf5f8-27aa-4c64-9a03-7fcccc0955b8"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/01bbf5f8-27aa-4c64-9a03-7fcccc0955b8/attachments/attachment.zip)

# 使用 AWS CDK 和 GitHub 操作工作流程优化多账户无服务器部署
<a name="optimize-multi-account-serverless-deployments"></a>

*Sarat Chandra Pothula 和 VAMSI KRISHNA SUNKAVALLI，Amazon Web Services*

## Summary
<a name="optimize-multi-account-serverless-deployments-summary"></a>

在多个 AWS 账户 和环境中部署无服务器基础架构的组织经常会遇到诸如代码重复、手动流程和做法不一致之类的挑战。此模式的解决方案展示了如何使用 Go and Actions AWS Cloud Development Kit (AWS CDK) 中的可重复使用工作流程来简化多账户无服务器基础架构管理。 GitHub 此解决方案演示了如何将云资源定义为代码、实现标准化持续 integration/continuous 部署 (CI/CD) 流程以及如何创建模块化、可重复使用的组件。

借助这些工具，组织可以高效地管理跨账户资源，实施一致的部署管道，并简化复杂的无服务器架构。该方法还通过强制使用标准化实践来增强安全性和合规性 AWS 账户，从而最终提高工作效率并减少无服务器应用程序开发和部署中的错误。

## 先决条件和限制
<a name="optimize-multi-account-serverless-deployments-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ AWS Identity and Access Management (IAM) [角色和权限](https://docs.aws.amazon.com/AmazonECR/latest/userguide/security-iam.html)适用于部署过程。这包括访问亚马逊弹性容器注册表 (Amazon ECR) 存储库、 AWS Lambda 创建函数以及跨目标的任何其他所需资源的权限。 AWS 账户
+ AWS Command Line Interface [(AWS CLI) 版本 2.9.11 或更高版本，[已安装并配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)。](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ AWS Cloud Development Kit (AWS CDK) [版本 2.114.1 或更高版本，[已安装](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_install)并已引导。](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_bootstrap)
+ [已安装](https://go.dev/doc/install) Go 1.22 或更高版本。
+ [已安装](https://docs.docker.com/engine/install/) Docker 24.0.6 或更高版本。

**限制**
+ **语言兼容性** – Go 是无服务器应用程序的常用语言。但是，除了 Go 之外，还 AWS CDK 支持其他编程语言，包括 C\$1、Java、Python 和 TypeScript。如果您的组织已有其他语言的代码库或专业知识，则可能需要调整或学习 Go 才能充分使用模式中描述的解决方案。
+ **学习曲线** — 采用 AWS CDK、Go（如果对组织来说是新手）和 GitHub 可重复使用的工作流程可能会涉及开发人员和 DevOps 团队的学习曲线。可能需要参加培训和查阅文档，以确保顺利地采用和有效地使用这些技术。

## 架构
<a name="optimize-multi-account-serverless-deployments-architecture"></a>

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

![\[用于多账户无服务器基础设施管理的 AWS CDK 架构和 GitHub 操作工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/8d61917b-bd27-44fa-ae95-55358aaf8812/images/a4b36793-95c7-42f7-a92f-99b4722c9c64.png)


该解决方案将执行以下步骤：

1. 开发人员克隆存储库，创建新分支，并在本地环境中更改应用程序代码。

1. 开发者提交这些更改并将新分支推送到 GitHub 存储库。

1. 开发者在 GitHub 存储库中创建拉取请求，提议将其功能或新功能分支合并到主分支中。

1. 此拉取请求会触发持续集成 (CI) GitHub 操作工作流程。此模式中的 CI 和持续部署（CD）工作流采用可复用的工作流，这些预定义的模块化模板可在不同项目或存储库间共享并执行。可重复使用的工作流程促进了 CI/CD 流程的标准化和效率。

1. CI 工作流设置必要的环境，为映像生成 Docker 标签，并使用应用程序代码构建 Docker 映像。

1. CI 工作流程使用中央 AWS 账户 GitHub OIDC 角色进行身份验证。 AWS 对于 CI 工作流程， AWS 账户 GitHub OIDC 的中心角色使用 AWS Security Token Service (AWS STS) 来获取临时证书。这些证书允许该角色构建 Docker 镜像并将其推送到中央的 Amazon ECR 存储库。 AWS 账户

1. CI 工作流将构建的 Docker 映像推送到 Amazon ECR。

1. CI 工作流将映像标签存储到 Systems Manager Parameter Store。

1. CI 工作流成功完成后，系统将输出 Docker 映像标签。

1. 触发 CD 工作流时，开发人员手动输入要部署的 Docker 映像的映像标签。此映像标签对应于 CI 工作流中生成并推送到 Amazon ECR 的标签。

1. 开发人员手动触发 CD 工作流，使用 CD 可重用工作流。

1. CD 工作流程 AWS 使用中央 AWS 账户 GitHub OIDC 角色进行身份验证。对于 CD 工作流程， AWS STS 首先用于担任 AWS 账户 GitHub OIDC 的中心角色。然后，此角色将担任目标账户部署的 CDK 引导角色。

1. CD 工作流程 AWS CDK 使用合成 AWS CloudFormation 模板。

1. CD 工作流程使用 CDK 部署将应用程序部署 AWS 账户 到目标，使用手动为 Lambda 函数指定的图像标签。

## 工具
<a name="optimize-multi-account-serverless-deployments-tools"></a>

**AWS 服务**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)是一个软件开发框架，可帮助您在代码中定义和配置 AWS 云 基础架构。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在和的整个 AWS 账户 生命周期中对其进行管理 AWS 区域。 CloudFormation 是 AWS CDK 部署过程不可或缺的一部分。CDK 合成 CloudFormation 模板，然后 CloudFormation 用于创建或更新环境中的 AWS 资源。
+ [Amazon Elastic Container Registry（Amazon ECR）](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html)是一项安全、可扩展且可靠的托管容器映像注册表服务。
+ [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 Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) 为配置数据管理和密钥管理提供安全的分层存储。

**其他工具**
+ [Docker](https://www.docker.com/) 是一组平台即服务（PaaS）产品，它们利用操作系统级的虚拟化技术在容器中提供软件。
+ GitHub A@@ [c](https://docs.github.com/en/actions/writing-workflows/quickstart) tions 是一个持续集成和持续交付 (CI/CD) 平台，与 GitHub 存储库紧密集成。您可以使用 GitHub Actions 来自动执行构建、测试和部署管道。
+ [Go](https://go.dev/doc/install) 是谷歌支持的开源编程语言。

**代码存储库**

此模式的代码可在cicd-github-actions存储 GitHub [aws-cdk-golang-serverless库](https://github.com/aws-samples/aws-cdk-golang-serverless-cicd-github-actions)中找到。

## 最佳实践
<a name="optimize-multi-account-serverless-deployments-best-practices"></a>
+ **模块化设计** — 将您的 AWS CDK 代码组织成模块化和可重复使用的构造或堆栈，从而促进跨多个账户和项目的代码重用和可维护性。
+ **关注点分离** – 将基础设施代码与应用程序代码分开，允许独立部署和管理每个组件。
+ **版本控制和不可变性** – 将您的基础设施即代码（IaC），并使用 Git 控制版本。通过创建新资源（而非修改现有资源）来接受不可变的基础设施原则。
+ **测试和验证**-实施全面的测试策略，包括单元测试、集成 end-to-end测试和测试，以帮助支持 AWS CDK 代码和部署的正确性和可靠性。
+ **安全性与合规性**-遵循 AWS 安全最佳实践，例如最低权限访问、安全通信和数据加密。实施合规性检查和审计机制，确保遵守组织政策和监管要求。为容器映像实施安全最佳实践，例如扫描漏洞、强制执行映像签名以及遵守组织的合规性要求。
+ **监控和日志记录** – 设置监控和日志记录机制，跟踪无服务器应用程序和基础设施的运行状况及性能。 AWS 服务 像 Amazon CloudWatch、 AWS CloudTrail、一样使用， AWS X-Ray 用于监控和审计。
+ **自动化和 CI/CD** — 使用 GitHub 可重复使用的工作流程和其他 CI/CD 工具来自动执行构建、测试和部署流程，这有助于支持跨多个账户进行一致且可重复的部署。
+ **环境管理** – 维护单独的环境（例如开发、暂存、生产）。实施促进环境间变更的策略，确保在生产部署前进行充分的测试与验证。
+ **文档记录与协作** - 记录基础设施代码、部署流程和最佳实践，以促进团队内部的知识共享与协作。
+ **成本优化**-实施成本监控和优化策略，例如合理调整资源规模、使用自动缩放以及利用 AWS 成本优化服务（如 AWS Budgets 和）。 AWS Cost Explorer
+ **灾难恢复和备份** – 通过为无服务器应用程序和基础设施资源实施备份和还原机制，规划灾难恢复方案。
+ **持续改进** – 定期审查并更新实务、工具和流程，使其与无服务器生态系统中的最新最佳实践、安全建议和技术进步保持一致。
+ **改善安全状况** — 通过[AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html)为 Amazon ECR 和 P AWS Systems Manager arameter Store 配置接口 VPC 终端节点， AWS Lambda用于改善虚拟私有云 (VPC) 的安全状况。

## 操作说明
<a name="optimize-multi-account-serverless-deployments-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在中央 AWS 账户创建一个 Amazon ECR 存储库。 | 要跨多个容器镜像共享 AWS 账户，您必须为 Amazon ECR 配置跨账户访问权限。首先，在中央 AWS 账户创建一个 Amazon ECR 存储库。要创建 Amazon ECR 存储库，请运行以下命令：<pre>aws ecr create-repository --repository-name sample-repo</pre>在以后的任务中，向需要使用容器镜像的其他 AWS 账户 人授予拉取访问权限。 | AWS DevOps | 
| 向 Amazon ECR 存储库添加跨账户权限。 | 要向中心的 Amazon ECR 存储库添加跨账户权限 AWS 账户，请运行以下代码：<pre>{<br />  "Version": "2008-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Sid": "LambdaECRImageRetrievalPolicy",<br />      "Effect": "Allow",<br />      "Principal": {<br />        "Service": "lambda.amazonaws.com"<br />      },<br />      "Action": [<br />        "ecr:BatchGetImage",<br />        "ecr:GetDownloadUrlForLayer",<br />      ],<br />      "Condition": {<br />        "StringLike": {<br />          "aws:sourceArn": "arn:aws:lambda:<Target_Region>:<Target_Account_ID>:function:*"<br />        }<br />      }<br />    },<br />    {<br />      "Sid": "new statement",<br />      "Effect": "Allow",<br />      "Principal": {<br />        "AWS": "arn:aws:iam::<Target_Account_ID>:root"<br />        },<br />      "Action": [<br />        "ecr:BatchGetImage",<br />        "ecr:GetDownloadUrlForLayer",<br />      ],<br />    }<br />  ] <br />}</pre> | AWS DevOps | 
| 在中心为 GitHub OIDC 角色配置角色。 AWS 账户 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html) | AWS DevOps | 
| 引导目标 AWS 账户中的 AWS 环境。 | 在特定 AWS 账户 环境中设置 CDK 环境 AWS 区域 ，该环境允许从中央账户进行跨账户部署，并将最低权限原则应用于执行角色。 CloudFormation 要[引导](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html) AWS 环境，请运行以下命令：<pre>cdk bootstrap aws://<Target_Account_ID>/<Target_Region> --trust <Central_Account_ID> --cloudformation-execution-policies arn:aws:iam::aws:policy/<Least_Privilege_Policy></pre> | AWS DevOps | 
| 授予中央 AWS 账户 OIDC 角色对目标 AWS 账户 引导角色的访问权限。 | CDK bootstrap 创建了以下 IAM 角色，这些角色旨在由中央在 CDK AWS 账户 部署过程的各个阶段担任：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html)每个角色都有与其用途匹配的特定权限，并遵循最低权限原则。每个角色名称`Target_Region`中的`Target_Account_ID`和有助于表明这些角色在不同的 AWS 账户 地区中是唯一的。此方法支持在多账户、多区域环境中进行清晰的识别与管理。<pre>Target Account CDK Bootstrap Roles<br />arn:aws:iam::<Target_Account_ID>:role/cdk-deploy-role-<Target_Account_ID>-<Target_Region><br />arn:aws:iam::<Target_Account_ID>:role/cdk-file-publishing-role-<Target_Account_ID>-<Target_Region><br />arn:aws:iam::<Target_Account_ID>:role/cdk-image-publishing-role-<Target_Account_ID>-<Target_Region><br />arn:aws:iam::<Target_Account_ID>:role/cdk-lookup-role-<Target_Account_ID>-<Target_Region></pre>[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html)要在中心更新 OIDC 角色的权限策略 AWS 账户，请使用以下代码：<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Effect": "Allow",<br />            "Action": "sts:AssumeRole",<br />            "Resource": [<br />                "arn:aws:iam::<Target_Account_ID>:role/cdk-deploy-role-<Target_Account_ID>-<Target_Region>",<br />                "arn:aws:iam::<Target_Account_ID>:role/cdk-file-publishing-role-<Target_Account_ID>-<Target_Region>",<br />                "arn:aws:iam::<Target_Account_ID>:role/cdk-image-publishing-role-<Target_Account_ID>-<Target_Region>",<br />                "arn:aws:iam::<Target_Account_ID>:role/cdk-lookup-role-<Target_Account_ID>-<Target_Region>"<br />            ]<br />        }<br />    ]<br /> }<br /></pre> | AWS DevOps | 

### 构建 Docker 映像。
<a name="build-the-docker-image"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆项目存储库。 | 要克隆此模式的[GitHub 存储库](https://github.com/aws-samples/aws-cdk-golang-serverless-cicd-github-actions)，请运行以下命令：<pre>git clone https://github.com/aws-samples/aws-cdk-golang-serverless-cicd-github-actions.git</pre> | AWS DevOps | 
| 前往 Dockerfile 路径。 | 要导航到 Dockerfile 路径，请运行以下命令：<pre>cd lambda</pre> | AWS DevOps | 
| 使用 Amazon ECR 对 Docker 进行身份验证。 | Amazon ECR 需要安全访问您的私有容器存储库。通过这种方式登录，您就允许本地计算机或 CI/CD 环境上的 Docker 安全地与 Amazon ECR 进行交互。要使用 Amazon ECR 对 Docker 进行身份验证，请运行以下命令：<pre>aws ecr get-login-password --region <AWS_REGION> | docker login --username AWS --password-stdin <AWS_ACCOUNT_ID>.dkr.ecr.<AWS_REGION>.amazonaws.com</pre>使用您的信息修改占位符 `AWS_REGION` 和 `AWS_Account_ID`。 | AWS DevOps | 
| 构建 Docker 映像。 | 要构建 Docker 映像，请运行以下命令：<pre>docker build --platform linux/arm64 -t sample-app .</pre> | AWS DevOps | 
| 标记和推送 Docker 映像。 | 要标记 Docker 映像并将其推送至 Amazon ECR 存储库，请运行以下命令：<pre>docker tag sample-app:latest <AWS_ACCOUNT_ID>.dkr.ecr.<AWS_REGION>.amazonaws.com/<ECR_REPOSITORY>:<DOCKER_TAG></pre><pre>docker push <AWS_ACCOUNT_ID>.dkr.ecr.<AWS_REGION>.amazonaws.com/<ECR_REPOSITORY>:<DOCKER_TAG></pre>使用您的信息修改占位符 `AWS_Account_ID`、`AWS_REGION`、`ECR_REPOSITORY` 和 `DOCKER_TAG`。 | AWS DevOps | 

### 部署 AWS CDK 应用程序
<a name="deploy-the-cdk-app"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用特定于环境的变量合成 CDK 堆栈。 | 要按照 CDK 代码中的定义为基础架构生成 CloudFormation 模板，请运行以下命令：<pre>ENV=<environment> IMAGETAG=<image_tag> ECR_ARN=<ecr_repo_arn> cdk synth</pre>使用您的信息修改以下占位符：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html) | AWS DevOps | 
| 部署 CDK 堆栈。 | 要将 CDK 堆栈部署到您的 AWS 账户，请运行以下命令。`--require-approval never` 标志表示 CDK 将自动批准并执行*所有*更改。这包括 CDK 通常会标记为需要人工审查的更改（例如 IAM 策略变更或资源移除）。在生产环境中使用该`--require-approval never`标志之前，请确保您的 CDK 代码和 CI/CD 管道经过充分测试且安全。<pre>ENV=<environment> IMAGETAG=<image_tag> ECR_ARN=<ecr_repo_arn> cdk deploy --require-approval never</pre> | AWS DevOps | 

### CI/CD 使用 GitHub 操作工作流程实现自动化
<a name="automate-ci-cd-using-github-actions-workflows"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建功能分支，然后添加您的更改。 | 使用之前创建的克隆存储库，创建功能分支，然后将更改添加到应用程序代码中。使用以下命令：<pre>git checkout -b <feature_branch><br />git add .<br />git commit -m "add your changes"<br />git push origin <feature_branch></pre>以下是更改的示例：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html)GitHub 操作将使用可重复使用的工作流程并触发 CI/CD 管道。 | AWS DevOps | 
| 合并您的更改。 | 创建拉取请求，并将您的更改合并到主分支。 | AWS DevOps | 

## 问题排查
<a name="optimize-multi-account-serverless-deployments-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| `AccessDenied`例如 AWS 账户，跨部署资源时会出错`AccessDenied: User not authorized to perform: "sts:AssumeRole"`。 | 要帮助解决此问题，请执行以下操作来验证跨账户权限：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html) | 
| 由于版本不匹配而导致的兼容性问题，例如与过时的 CDK 版本相关的 `undefined: awscdkStack` 错误。 | 要帮助解决此问题，请执行以下操作以验证您使用的是 AWS CDK 和 Go 的必需版本：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html) | 
| CI/CD 管道故障，例如 YAML 配置不正确导致的 `Error: No such file or directory`，或者针对受保护分支的 `Permission denied`。 | 为了帮助解决 GitHub 操作配置问题，请验证是否正确引用和配置了可重复使用的工作流程。 | 

## 相关资源
<a name="optimize-multi-account-serverless-deployments-resources"></a>

**AWS 资源**
+ [AWS 安全性、身份和合规性最佳实践](https://aws.amazon.com/architecture/security-identity-compliance/)
+ [AWS CDK 工作坊](https://cdkworkshop.com/60-go.html)
+ [AWS Cloud 开发套件库](https://pkg.go.dev/github.com/aws/aws-cdk-go/awscdk/v2)
+ [使用容器映像创建 Lambda 函数](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html)
+ [适用于亚马逊弹性容器注册表的身份和访问管理](https://docs.aws.amazon.com/AmazonECR/latest/userguide/security-iam.html)
+ [在 Go 中使用 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-go.html)

**其他资源**
+ [在亚马逊 Web Services 中配置 OpenID Connect](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)（文档）GitHub 
+ [Golang 文档](https://golang.org/doc/)
+ [ GitHub 操作快速入门](https://docs.github.com/en/actions/writing-workflows/quickstart)（GitHub 文档）
+ [重复使用工作流程](https://docs.github.com/en/actions/sharing-automations/reusing-workflows)（GitHub 文档）

# 使用 GitHub 操作基于 AWS CloudFormation 模板配置 AWS Service Catalog 产品
<a name="provision-aws-service-catalog-products-using-github-actions"></a>

*Ashish Bhatt 和 Ruchika Modi，Amazon Web Services*

## Summary
<a name="provision-aws-service-catalog-products-using-github-actions-summary"></a>

这种模式为组织提供了一种简化的方法，使用[AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html)产品和产品组合来 AWS 服务 跨团队进行标准化和合规的配置。 [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)有助于整合 Service Catalog 产品和产品组合中的基本组件，用于配置基础网络基础架构 AWS 云。这种模式还通过使用 Actions 将基础设施即代码 (IaC) 集成到自动化开发工作流程中，从而促进 DevOps 实践[GitHub 。](https://github.com/features/actions)

AWS Service Catalog 使组织能够在上创建和管理经批准的 IT 服务 AWS，从而提供标准化、集中控制、自助服务配置和成本管理等好处。通过操作自动部署 Service Catalog 产品组合和产品，公司可以执行以下 GitHub 操作：
+ 确保部署一致且可重复。
+ 对 IaC 使用版本控制。
+ 整合云资源管理与现有开发工作流。

这种组合可简化云端运营、增强合规性、加快经批准服务的交付，同时减少人为错误并提升整体效率。

## 先决条件和限制
<a name="provision-aws-service-catalog-products-using-github-actions-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户 
+ 访问[GitHub 存储库](https://docs.github.com/en/get-started/quickstart/create-a-repo)
+ 对 AWS CloudFormation 和的基本理解 AWS Service Catalog
+ 用于托管模板的亚马逊简单存储服务 (Amazon S3) Service 存储桶 CloudFormation 
+ 一个名为的 AWS Identity and Access Management (IAM) 角色`github-actions`，用于 GitHub 和之间的连接 AWS

**限制**
+ 此模式的可重用代码仅通过 Actions 进行了 GitHub 测试。
+ 有些 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)，然后选择相应服务的链接。

**产品版本**

此模式的解决方案是使用以下 [GitHub Marketplace](https://github.com/marketplace) 操作及其相应的版本创建的：
+ `actions/checkout@v4`
+ `aws-actions/configure-aws-credentials@v2`
+ `aws-actions/aws-cloudformation-github-deploy@v1.2.0`

## 架构
<a name="provision-aws-service-catalog-products-using-github-actions-architecture"></a>

下图显示了该解决方案的架构。

![\[使用 GitHub 操作根据 CloudFormation 模板配置 Service Catalog 产品。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/49f82fa7-0c74-4581-bf92-95505dca264c/images/a13c7b41-534e-4a9e-bdca-2974fa40a49a.png)


1. 管理员或平台工程师将标准化 CloudFormation 模板推送到 GitHub 存储库，在那里维护这些模板。该 GitHub 存储库还包含 AWS Service Catalog 使用 GitHub 操作自动配置的工作流程。

1. GitHub 操作会触发一个工作流，该工作流 AWS 云 使用 OpenID Connect (OIDC) 提供程序连接到以配置 Service Catalog。

1. Service Catalog 包含开发人员可以直接用来配置标准化 AWS 资源的产品组合和产品。这种模式捆绑了虚拟私有云 (VPCs)、子网、NAT 和 Internet 网关以及路由表等 AWS 资源。

1. 开发者创建服务目录产品后，Service Catalog 会将其转换为预先配置的标准化 AWS 资源。因此，开发人员可以节省时间，因为他们无需手动逐个预调配和配置资源。

## 工具
<a name="provision-aws-service-catalog-products-using-github-actions-tools"></a>

**AWS 服务**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在和的整个 AWS 账户 生命周期中对其进行管理 AWS 区域。它是一种基础设施即代码 (IaC) 服务，可以很容易地用作产品类型之一。 AWS Service Catalog
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/getstarted.html)帮助您集中管理已获批准的 IT 服务目录 AWS。最终用户可在遵循组织设定约束的情况下快速部署他们所需已获得批准的 IT 服务。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**其他**
+ GitHub A@@ [c](https://docs.github.com/en/actions) tions 是一个持续集成和持续交付 (CI/CD) 平台，与 GitHub 存储库紧密集成。您可以使用 GitHub Actions 来自动执行构建、测试和部署管道。

**代码存储库**

此模式的代码可在 GitHub [service-catalog-with-github-](https://github.com/aws-samples/service-catalog-with-github-actions) actions 存储库中找到。存储库包含以下相关文件：
+ `github/workflows`:
  + `e2e-test.yaml` – 此文件调用 `workflow.yaml`，这是[可重用的工作流](https://docs.github.com/en/actions/sharing-automations/reusing-workflows)。当分支上有提交和推送操作时，就会触发此工作流。
  + `workflow.yaml` – 此文件包含该解决方案的可重用工作流，并配置为以 `workflow_call` 作为其触发器。作为可重用的工作流，`workflow.yaml` 可从任何其他工作流调用。
+ `templates`:
  + `servicecatalog-portfolio.yaml`— 此 CloudFormation 模板包括用于配置服务目录产品组合和服务目录产品的资源。模板包含在预调配 Service Catalog 组合和产品时使用的一组参数。一个参数接受用于上传 `vpc.yaml` 模板的 Amazon S3 文件 URL。尽管此模式包括 AWS 用于配置资源的`vpc.yaml`文件，但您也可以使用参数 S3 文件 URL 进行配置。
  + `vpc.yaml`— 此 CloudFormation 模板包含要添加到 Service Catalog 产品中的 AWS 资源。 AWS 资源包括子网 VPCs、互联网网关、NAT 网关和路由表。该`vpc.yaml`模板是如何将任何模板与 Service Catalog 产品和产品组合 CloudFormation 模板配合使用的示例。

## 最佳实践
<a name="provision-aws-service-catalog-products-using-github-actions-best-practices"></a>
+ 请参阅 AWS Service Catalog 文档 AWS Service Catalog中的[安全最佳实践](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/security-best-practices.html)。
+ 有关[ GitHub 操作的信息，请参阅 GitHub 文档中的安全加固](https://docs.github.com/en/actions/security-for-github-actions/security-guides/security-hardening-for-github-actions)。

## 操作说明
<a name="provision-aws-service-catalog-products-using-github-actions-epics"></a>

### 设置本地工作站
<a name="set-up-local-workstation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在本地工作站上设置 Git。 | 要在本地工作站上安装和配置 Git，请遵照 Git 文档中的[开始使用 – 安装 Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 说明操作。 | 应用程序开发人员 | 
| 克隆 GitHub 项目存储库。 | 要克隆 GitHub 项目存储库，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | DevOps 工程师 | 

### 设置 OIDC 提供程序
<a name="set-up-the-oidc-provider"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置 OIDC 提供程序。 | 创建一个 OpenID Connect (OIDC) 提供程序，允许 GitHub 操作工作流程访问其中的资源 AWS，而无需将 AWS 凭据存储为长期存在的机密。 GitHub 有关说明，请参阅文档[中的在亚马逊 Web Services 中配置 OpenID Connect](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)。 GitHub OIDC 提供程序配置完成后，先前在[先决条件](#provision-aws-service-catalog-products-using-github-actions-prereqs)部分提到的 IAM 角色`github-actions`的信任策略将更新。 | AWS 管理员、AWS DevOps、常规 AWS | 

### 触发 GitHub 操作管道以部署 Service Catalog 产品组合和产品
<a name="trigger-github-actions-pipeline-to-deploy-sc-portfolio-and-products"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新 `e2e-test.yaml` | `e2e-test.yaml` 文件会触发 `workflow.yaml` 中的可重用工作流。更新并验证 `e2e-test.yaml` 中以下输入参数的值：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证 Service Catalog 资源。 | 要验证 Service Catalog 资源，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | AWS DevOps | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除 CloudFormation 堆栈。 | 要删除 CloudFormation 堆栈，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html)有关更多信息，请参阅 CloudFormation 文档[中的从 CloudFormation 控制台删除堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html) | DevOps 工程师，AWS 管理员 | 

## 问题排查
<a name="provision-aws-service-catalog-products-using-github-actions-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| `e2e-test``Can't find 'action.yml', 'action.yaml' or 'Dockerfile' under '*/home/runner/work/service-catalog-with-github-actions/service-catalog-with-github-actions``Did you forget to run actions/checkout before running your local action?` | 要确保启用正确的存储库设置，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | 

## 相关资源
<a name="provision-aws-service-catalog-products-using-github-actions-resources"></a>

**AWS 文档**
+ [Service Catalog 概述](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/what-is_concepts.html)

**其他资源**
+ [关于触发工作流程的事件](https://docs.github.com/en/actions/writing-workflows/choosing-when-your-workflow-runs/events-that-trigger-workflows#about-events-that-trigger-workflows)（GitHub 文档）
+ [重复使用工作流程](https://docs.github.com/en/actions/sharing-automations/reusing-workflows)（GitHub 文档）

## 附加信息
<a name="provision-aws-service-catalog-products-using-github-actions-additional"></a>

要查看与 [Epics](#provision-aws-service-catalog-products-using-github-actions-epics) 相关的屏幕截图，请转到此模式存储**库中的 Images** 文件夹。 GitHub 以下屏幕截图可用：
+ [AWS Service Catalog 投资组合，管理部分](https://github.com/aws-samples/service-catalog-with-github-actions/blob/main/images/SC_portfolio.png)
+ [AWS Service Catalog 产品，“管理” 部分](https://github.com/aws-samples/service-catalog-with-github-actions/blob/main/images/SC_Product.png)
+ [AWS Service Catalog 产品， User/Provisioning 部分](https://github.com/aws-samples/service-catalog-with-github-actions/blob/main/images/SC_Product_User.png)

# 通过部署角色自动分配机器解决方案，预调配最低权限 IAM 角色
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution"></a>

*Benjamin Morris、Nima Fotouhi、Aman Kaur Gandhi 和 Chad Moon，Amazon Web Services*

## Summary
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-summary"></a>

管道的超范围 AWS Identity and Access Management （IAM）角色权限可能会给组织带来不必要的风险。开发人员有时会在开发过程中授予广泛的权限，但在对代码进行问题排查后却忘记缩小权限范围。这导致了一个问题：存在一些强大的角色，它们在业务上没有必要，而且可能从未经过安全工程师的审查。

此模式提供了可解决这个问题的方案：角色自动分配机器（RVM）。RVM 使用安全的集中式部署模型，演示了如何以最少的开发人员努力为各个 GitHub 仓库的管道配置权限最低的 IAM 角色。由于 RVM 是集中式解决方案，您可以将安全团队配置为必要的审核人员，负责审批变更。此方法允许安全机制拒绝权限过高的管道角色请求。

RVM 将 Terraform 代码作为输入，生成可用于管道的 IAM 角色作为输出。所需的输入是 AWS 账户 ID、 GitHub 存储库名称和权限策略。RVM 使用这些输入来创建角色的信任策略和权限策略。由此产生的信任策略允许指定的 GitHub 存储库担任该角色并将其用于管道操作。

RVM 使用 IAM 角色（在引导期间配置）。该角色有权在组织 role-provisioning-role中的每个账户中扮演一个。该角色可通过 Account Factor AWS Control Tower y for Terraform (AFT) 或。 AWS CloudFormation StackSets role-provisioning-roles这些角色实际上是为开发人员创建管道角色。

## 先决条件和限制
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ 一种用于通过 GitHub 操作部署基础设施即代码 (IaC) 的 GitHub 组织。 （GitHub Enterprise/Premium/Ultimate*不是*****必填项。）
+ 多账户 AWS 环境。这个环境不一定是其中的一部分 AWS Organizations。
+ 一种用于在所有角色中部署 IAM 角色的机制 AWS 账户 （例如，AFT 或 CloudFormation StackSets）。
+ [已安装并配置](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) Terraform 版本 1.3 或更高版本。
+ [安装](https://github.com/hashicorp/terraform-provider-aws/releases)[并配置了 Terraform P AWS rovider 版本 4 或更高版本。](https://developer.hashicorp.com/terraform/language/providers/configuration)

**限制**
+ 此模式的代码特定于 Actions 和 Terraform。 GitHub 但是，此模式的一般概念可以在其他持续集成和交付（CI/CD）框架中重复使用。
+ 有些 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="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-architecture"></a>

下图说明了此模式的工作流。

![\[使用 GitHub 操作自动创建和部署 IAM 角色的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/215c590e-0c84-411d-be6e-b1739f1e19d2/images/82fcdc9f-9576-4e7c-b7fe-b45046ba79d2.png)


角色自动分配机器的典型使用工作流包含以下步骤：

1. 开发人员将包含新请求的 IAM 角色的 Terraform 代码的代码推送到 R GitHub VM 存储库。此操作会触发 RVM GitHub 操作管道。

1. 管道使用 OpenID Connect（OIDC）信任策略来担任 RVM 角色假设角色。

1. 当 RVM 管道运行时，在预调配开发人员新 IAM 角色的账户中担任 RVM 工作流角色。（RVM 工作流程角色是使用 AFT 或 CloudFormation StackSets配置的。）

1. RVM 创建具有适当权限和信任的开发人员 IAM 角色，以便其他应用程序管道可以担任该角色。

1. 应用程序开发人员可以配置其应用程序管道，以承担这个 RVM 预调配的角色。

创建的角色包括开发人员请求的权限和 `ReadOnlyAccess` 策略。只有针对开发人员指定存储库 `main` 分支运行的管道才能担任该角色。这种方法有助于确保必须完成分支保护和审查，才能使用该角色。

**自动化和扩展**

根据最低权限机制，我们必须注意正在预调配的每个角色的细节。此模型降低了创建这些角色所需的复杂性，使得开发人员无需额外学习或付出太多努力，即可创建所需角色。

## 工具
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-tools"></a>

**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 账户 到一个由您创建和集中管理的组织中。

**其他工具**
+ [Git](https://git-scm.com/docs) 是开源分布式版本控制系统。其中包括创建[组织账户](https://docs.github.com/en/get-started/learning-about-github/types-of-github-accounts#organization-accounts)的功能。
+ GitHub A@@ [c](https://docs.github.com/en/actions/writing-workflows/quickstart) tions 是一个持续集成和持续交付 (CI/CD) 平台，与 GitHub 存储库紧密集成。您可以使用 GitHub Actions 来自动执行构建、测试和部署管道。
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。

**代码存储库**

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

## 最佳实践
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-best-practices"></a>
+ **让正确的路易走，让错误的路难行** – 让做正确的事变得容易。如果开发人员在 RVM 预调配过程中遇到困难，可能会尝试通过其他方式创建角色，这会削弱 RVM 的核心价值。请确保您的安全团队就如何安全有效地使用 RVM 提供明确指导。

  您还应该让开发人员难做错事。使用服务控制策略 (SCPs) 或权限边界来限制哪些角色可以创建其他角色。这种方法可帮助将角色创建权限仅限于 RVM 和其他可信来源。
+ **提供良好范例** – 不可避免地，有些开发人员会将 RVM 存储库中的现有角色作为非正式模板，用于为其新角色授予权限。若能提供可供参考的最低权限示例，便能降低开发人员申请范围过广、包含大量通配符权限的风险。如果一开始就使用权限很高的角色和大量的通配符，随着时间的推移，这个问题会成倍增长。
+ **使用命名约定和条件** – 即使开发人员不知道其应用程序将创建的所有资源名称，他们仍然应该通过使用命名约定来限制角色权限。例如，当他们创建 Amazon S3 存储桶时，其资源键的值可能设置为 `arn:aws:s3:::myorg-myapp-dev-*`，这样该角色的权限就仅限于匹配该名称的存储桶。通过 IAM 策略强制执行命名规范，还具有增强命名规范合规性的额外优势。之所以出现这种改进，是因为系统不允许创建不匹配的资源。
+ **需要拉取请求（PR）审查** – RVM 解决方案的价值在于，它创建了一个中心位置，可以在此审查新的管道角色。但是，仅当有护栏帮助确保将安全、高质量的代码提交到 RVM 时，这种设计才有用。保护用于部署代码的分支（例如 `main`），禁止直接推送操作，并要求所有针对这些分支的合并请求必须经过审批。
+ **配置只读角色** – 默认情况下，RVM 会为每个请求的角色预调配一个 `readonly` 版本。此角色可以在不写入数据的 CI/CD 管道中使用，例如`terraform plan`管道工作流。如果只读工作流出现异常，这种方法有助于防止发生不必要的更改。

  默认情况下， AWS 托管`ReadOnlyAccess`策略同时附加到只读角色和读写角色。在确定所需权限时，此策略减少了迭代需求，但对某些组织而言可能过于宽松。如果需要，可以从 Terraform 代码中移除该策略。
+ **授予最低权限** – 遵循最低权限原则，并授予执行任务所需的最低权限。有关详情，请参阅 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="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将示例存储库复制到您的 GitHub 组织。 | [克隆](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository)此模式的存储库[或](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/working-with-forks/fork-a-repo)将此存储库分支到您的 GitHub 组织，以便您可以根据需要对其进行调整。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html) | DevOps 工程师 | 
| 确定 R AWS 账户 VM 的。 | 确定 AWS 账户 要为 RVM 使用哪种基础架构部署。请勿使用管理账户或根账户。 | 云架构师 | 
| （可选）允许组织创建管道 PRs。 | 只有在要允许创建`generate_providers_and_account_vars`工作流程时，才需要执行此步骤 PRs。要允许贵组织的管道创建 PRs，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html)有关更多信息，请参阅 GitHub 文档中的[管理存储库的 GitHub 操作设置](https://docs.github.com/en/enterprise-server@3.10/repositories/managing-your-repositorys-settings-and-features/enabling-features-for-your-repository/managing-github-actions-settings-for-a-repository#preventing-github-actions-from-creating-or-approving-pull-requests)。 | DevOps 工程师 | 
| 授予 RVM 账户的只读权限。 | 在您的管理账户中创建授予 RVM 账户只读权限的委托策略。这允许你的 RVM GitHub 工作流程在`generate_providers_and_account_vars.py`脚本运行时动态提取 AWS 组织账户列表。使用以下代码并`<YOUR RVM Account ID>`替换为您在步骤 2 中选择的 AWS 账户 ID：<pre>{<br />  "Version": "2012-10-17",		 	 	 <br />  "Statement": [<br />    {<br />      "Sid": "Statement",<br />      "Effect": "Allow",<br />      "Principal": {<br />        "AWS": "arn:aws:iam::<YOUR RVM Account ID>:root"<br />      },<br />      "Action": [<br />        "organizations:ListAccounts",<br />        "organizations:DescribeOrganization",<br />        "organizations:DescribeOrganizationalUnit",<br />        "organizations:ListRoots",<br />        "organizations:ListAWSServiceAccessForOrganization",<br />        "organizations:ListDelegatedAdministrators"<br />      ],<br />      "Resource": "*"<br />    }<br />  ]<br />}</pre> | 云管理员 | 
| 更新示例存储库中的默认值。 | 要将 RVM 配置为在您的特定环境中运行 AWS 区域，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html) | DevOps 工程师 | 

### 初始化基础设施
<a name="initialize-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 引导 RVM 存储库。 | 此步骤对于创建 RVM 管道本身使用的 OIDC 信任和 IAM 角色非常必要，这样才能开始运行并分配其他角色。在您的 RVM 账户环境中，请从 `scripts/bootstrap` 目录手动运行 `terraform apply` 命令。根据变量文档提供任何必要的值。 | DevOps 工程师 | 

### 配置操作
<a name="configure-operations"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将 `github-workflow-rvm` 和 `github-workflow-rvm-readonly` 角色部署到所有账户。 | 选择符合组织实践的部署方法，例如 AFT 或 StackSets。使用该方法将 `scripts/assumed_role/main.tf` 文件中的两个 IAM 角色（默认名称为 `github-workflow-rvm` 和 `github-workflow-rvm-readonly`）部署到您希望 RVM 能够在其中创建管道角色的每个账户。这些 IAM 角色具有信任策略，允许 RVM 账户的角色承担角色（或其 `readonly` 等效角色）担任该角色。这些角色还具有 IAM 权限策略，允许他们读取和写入匹配 `readonly` 的角色（除非使用 `github-workflow-role-*` 角色）。 | AWS 管理员 | 
| 运行 `generate_providers_and_account_vars` 工作流。 | 要配置 RVM 以使其准备好创建管道角色，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html)工作流完成后，RVM 已准备好：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html) | DevOps 工程师 | 

## 问题排查
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 我使用 RVM 创建了一个角色，但 GitHub 无法假设。 | 验证 GitHub 存储库的名称是否与提供给`github_workflow_roles`模块的名称相匹配。角色有范围限制，只有一个存储库可以承担。同样，请验证 GitHub 管道中使用的分支是否与提供给`github_workflow_roles`模块的分支名称相匹配。通常情况下，RVM 创建的具有写入权限的角色只能由 `main` 分支范围内的工作流使用（即源自 `main` 的部署）。 | 
| 我的只读角色无法运行管道，因其缺乏读取特定资源的权限。 | 尽管该`ReadOnlyAccess`策略提供了广泛的只读权限，但该策略没有一些读取操作（例如，某些 AWS Security Hub CSPM 操作）。可以使用 `github-workflow-roles` 模块的 `inline_policy_readonly` 参数添加特定的操作权限。 | 

## 相关资源
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-resources"></a>
+ [使用的最佳实践 AWS CloudFormation StackSets](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-bestpractices.html)
+ [使用多个账户组织您的 AWS 环境](https://docs.aws.amazon.com/whitepapers/latest/organizing-your-aws-environment/organizing-your-aws-environment.html)
+ [适用于 Terraform (AFT) 的 Account Factory 概述 AWS Control Tower](https://docs.aws.amazon.com/controltower/latest/userguide/aft-overview.html)
+ [政策最佳实践](https://docs.aws.amazon.com/codepipeline/latest/userguide/security_iam_service-with-iam-policy-best-practices.html) 

## 附加信息
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-additional"></a>

**使用 GitHub 环境**

GitHub 环境是替代基于分支的角色访问限制的另一种方法。如果您更喜欢使用 GitHub 环境，以下是 IAM 信任策略中附加条件的语法示例。此语法指定只有在`Production`环境中运行 GitHub 操作时才能使用该角色。

```
"StringLike": {
    "token.actions.githubusercontent.com:sub": "repo:octo-org/octo-repo:environment:Production"
}
```

示例语法使用以下占位符值：
+ `octo-org`是 GitHub 组织名称。
+ `octo-repo` 是存储库名称。
+ `Production`是特定的 GitHub 环境名称。

# 将亚马逊 CloudWatch 指标发布到 CSV 文件
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file"></a>

*Abdullahi Olaoye，Amazon Web Services*

## Summary
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-summary"></a>

此模式使用 Python 脚本来检索 Amazon CloudWatch 指标，并将指标信息转换为逗号分隔值 (CSV) 文件以提高可读性。该脚本将应检索其指标的 Amazon Web Services 作为必需参数。您可将 AWS 区域和 AWS 凭证配置文件指定为可选参数。如果您不指定这些参数，脚本将使用为运行脚本的工作站配置的默认区域和配置文件。脚本运行后，它会生成 CSV 文件并将其存储在同一目录中。

有关此模式提供的脚本和关联文件，请参阅*附件*部分。

## 先决条件和限制
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-prereqs"></a>

**先决条件**
+ Python 3.x
+ AWS 命令行界面（AWS CLI）

**限制**

脚本当前支持以下 Amazon Web Services：
+ AWS Lambda
+ 亚马逊弹性计算云（亚马逊 EC2）
  + 默认情况下，脚本不收集Amazon Elastic Block Store(Amazon EBS) 卷指标。要收集 Amazon EBS 指标，您必须修改所附 `metrics.yaml` 文件。
+ Amazon Relational Database Service(Amazon RDS)
  + 但是，该脚本不支持 Amazon Aurora。
+ 应用程序负载均衡器
+ 网络负载均衡器
+ Amazon API Gateway

## 工具
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-tools"></a>
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 是一项专为 DevOps 工程师、开发人员、站点可靠性工程师 (SREs) 和 IT 经理构建的监控服务。 CloudWatch 提供数据和切实可行的见解，帮助您监控应用程序、响应系统范围的性能变化、优化资源利用率并获得统一的运营状况视图。 CloudWatch 以日志、指标和事件的形式收集监控和运营数据，并提供在 AWS 和本地服务器上运行的 AWS 资源、应用程序和服务的统一视图。

## 操作说明
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-epics"></a>

### 安装并配置先决条件
<a name="install-and-configure-the-prerequisites"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装先决条件。 | 运行如下命令：<pre>$ pip3 install -r requirements.txt</pre> | 开发者版 | 
| 配置 AWS CLI。 | 运行如下命令： <pre>$ aws configure</pre> | 开发者版 | 

### 配置 Python 脚本
<a name="configure-the-python-script"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 打开脚本。 | 要更改脚本的默认配置，请打开 `metrics.yaml`。 | 开发者版 | 
| 为脚本设置周期。 | 即获取时间范围。默认值为 5 分钟 (300 秒)。您可更改时间段，但请注意以下限制： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/publish-amazon-cloudwatch-metrics-to-a-csv-file.html)否则，API 操作不会返回任何数据点。 | 开发者版 | 
| 设置脚本时间。 | 此值指定您想要获取多少小时的指标。默认值为 1 小时。要检索多天指标，请提供以小时为单位的值。例如对于 2 天，指定 48。 | 开发者版 | 
| 更改脚本的统计数据值。 | （可选）全局统计值为 `Average`，在获取未分配特定统计值的指标时使用该值。该脚本支持统计值 `Maximum`、`SampleCount` 和 `Sum`。 | 开发者版 | 

### 运行 Python 脚本
<a name="run-the-python-script"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 运行 脚本。 | 使用以下命令： <pre>$ python3 cwreport.py <service> </pre>要查看服务值列表以及可选 `profile ` 参数和 `region ` 参数，请运行以下命令：<pre> $ python3 cwreport.py -h</pre>有关可选参数的更多信息，请参阅*其他信息*部分。 | 开发者版 | 

## 相关资源
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-resources"></a>
+ [配置 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ [使用亚马逊 CloudWatch 指标](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html)
+ [亚马逊 CloudWatch 文档](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)
+ [EC2 CloudWatch Metrics](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/viewing_metrics_with_cloudwatch.html#ec2-cloudwatch-metrics)
+ [AWS Lambda 指标](https://docs.aws.amazon.com/lambda/latest/operatorguide/logging-metrics.html)
+ [Amazon RDS 指标](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/rds-metrics.html#rds-cw-metrics-instance)
+ [应用程序负载均衡器指标](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-cloudwatch-metrics.html)
+ [网络负载均衡器指标](https://docs.aws.amazon.com/elasticloadbalancing/latest/network/load-balancer-cloudwatch-metrics.html)
+ [Amazon API Gateway 指标](https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-metrics-and-dimensions.html)

## 附加信息
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-additional"></a>

**脚本用法**

```
$ python3 cwreport.py -h
```

**语法示例**

```
python3 cwreport.py <service> <--region=Optional Region> <--profile=Optional credential profile>
```

**参数**
+ **服务（必填）** - 您要运行脚本的服务。该脚本目前支持以下服务：AWS Lambda、Amazon、A EC2 mazon RDS、应用程序负载均衡器、网络负载均衡器和 API Gateway。
+ **区域（可选）** - 要从中获取指标的 AWS 区域。默认选项是 `ap-southeast-1`。
+ **配置文件（可选）** - 要使用的 AWS CLI 命名配置文件。如果未指定此参数，则使用默认配置凭证配置文件。

**示例**
+ 要使用默认区域和`ap-southeast-1`默认配置的凭证来获取 Amazon EC2 指标，请执行以下操作：`$ python3 cwreport.py ec2`
+ 若要指定区域并获取 API Gateway 指标：`$ python3 cwreport.py apigateway --region us-east-1`
+ 要指定 AWS 配置文件并获取亚马逊 EC2 指标，请执行以下操作：`$ python3 cwreport.py ec2 --profile testprofile`
+ 要指定区域和概况以获取 Amazon EC2 指标，请执行以下操作：`$ python3 cwreport.py ec2 --region us-east-1 --profile testprofile`

## 附件
<a name="attachments-0a915a9d-2eef-4da1-8283-3cf4a115b3b2"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/0a915a9d-2eef-4da1-8283-3cf4a115b3b2/attachments/attachment.zip)

# 使用 AWS Lambda 自动化功能 AWS 账户 从 AWS Managed Microsoft AD 正面移除 Amazon EC2 条目
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad"></a>

*Rahul Sharad Gaikwad 博士和 Tamilselvan P，Amazon Web Services*

## Summary
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-summary"></a>

Active Directory（AD）是 Microsoft 脚本工具，旨在管理域信息以及用户与网络服务的交互。它在托管服务提供商 (MSPs) 中被广泛用于管理员工凭证和访问权限。由于 AD 攻击者可能利用不活跃的账户尝试入侵组织，因此我们必须找到不活跃的账户并在例行维护计划中将其禁用。使用 AWS Directory Service for Microsoft Active Directory，你可以将 Microsoft Active Directory 作为托管服务运行。此模式可以帮助您配置 AWS Lambda 自动化，以快速查找和删除不活跃的帐户。

如果您的组织中存在以下情况，则此模式可以为您提供帮助：
+ **集中式广告管理** — 如果您的组织有多个账户 AWS 账户，每个都有自己的 AD 部署，那么在所有账户中一致地管理用户帐户和访问权限可能会很困难。借助跨账户 AD 清理解决方案，您可以集中禁用或删除所有 AD 实例中的不活跃账户。
+ **AD 重组或迁移** – 如果您的组织计划重组或迁移其 AD 部署，则跨账户 AD 清理解决方案可助您做好环境准备。此解决方案可以帮助您删除不必要或不活跃的账户、简化迁移过程并减少潜在的冲突或问题。

使用此模式时，可以获得以下好处：
+ 提高数据库和服务器性能，修复来自不活动账户的安全漏洞。
+ 如果您的 AD 服务器托管在云中，移除不活跃的账户还可以降低存储成本，同时提高性能。您的月度支出可能减少，因为带宽费用和计算资源都可能下降。
+ 借助干净的 Active Directory 将潜在攻击者拒之门外。

## 先决条件和限制
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-prereqs"></a>

**先决条件**
+ 一个活跃的家长 AWS 账户 和一个或多个子女账户。在此模式中，*父账户*是创建 Active Directory 的位置。*子账户*托管 Windows 服务器，并通过父账户 Active Directory 加入。
+ 已在本地工作站上[安装](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)和配置 Git。
+ 已在本地工作站上[安装](https://learn.hashicorp.com/tutorials/terraform/install-cli)和配置 Terraform。
+ AWS Managed Microsoft AD 在家长帐户中配置并共享给所有子女帐户的目录。*有关更多详细信息，请参阅《管理指南》中的[教程：共享您的 AWS Managed Microsoft AD 目录以实现无缝 EC2 域加入](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_tutorial_directory_sharing.html)。AWS Directory Service *
+ （父账户）的 VPC 和亚马逊弹性计算云 (Amazon) 实例 AWS Directory Service （子账户）的 VPC 之间可用的虚拟私有云 (VPC EC2) 对等 AWS Transit Gateway 连接或连接。有关详细信息，请参阅《AWS Directory Service 管理指南》中的[在目录拥有者与目录使用者账户之间配置 VPC 对等连接](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step1_setup_networking.html#step1_configure_owner_account_vpc)。**
+ 一台 Windows 计算机，其所有父账户和子账户上都配置了 `EC2WindowsUserdata` 脚本。脚本文件位于此模式[代码存储库](https://github.com/aws-samples/aws-lambda-ad-cleanup-terraform-samples/tree/main/multiple-account-cleanup)的根目录中。
+ 每个子账户上都有一个跨账户 AWS Identity and Access Management (IAM) 角色，该账户配置了信任策略，允许使用父账户中的 AWS Lambda 功能。有关更多信息，请参阅《亚马逊* EventBridge 用户指南》 AWS 账户 *[中的在亚马逊 EventBridge之间发送和接收事件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEvents-CrossAccountEventDelivery.html)。
+ 父账户的 AWS Systems Manager 参数存储中提供以下密钥值：
  + `domainJoinUser` – 目录服务的用户名
  + `domainJoinPassword` – 目录服务的密码

  有关密钥的更多信息，请参阅《*AWS Secrets Manager 用户指南》*中的[创建 AWS Secrets Manager 密钥](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html)。

**限制**
+ Terraform 无法自动在子账户中创建资源。必须通过 AWS 管理控制台手动创建以下资源：
  + 亚马逊 EventBridge 规定将亚马逊终 EC2 止事件发送到母账户
  + 使用信任政策在子 EC2 账户中创建亚马逊跨账户角色
  + VPC 对等连接或 Transit Gateway 连接
+ 有些 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)，然后选择相应服务的链接。

**产品版本**
+ [Terraform 版本 1.1.9 或更高版本](https://developer.hashicorp.com/terraform/install)
+ [Terraform P AWS rovider 3.0 或更高版本](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/version-3-upgrade)

## 架构
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-architecture"></a>

下图显示了解决方案的高层级架构。

![\[使用 Lambda 自动化从 AWS 账户中删除 EC2 条目的流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/c397d873-e10d-44b6-8352-5f1380ab94ca/images/bd6c80a7-e490-47db-bd47-165314e1ea8a.png)


架构图展示了以下流程：

1. 在儿童账户中，该 EventBridge 规则会收集所有 Amazon EC2 终止事件。该规则将父账户中存在的事件发送到 EventBridge 这些事件。

1. 从父账户 EventBridge 收集所有事件并包含触发 Lambda 函数的规则。`ADcleanup-Lambda`

1. 父账户从父账户或子账户接收任何终止事件，并触发 Lambda 函数。

1. Lambda 函数使用 Python boto 模块调用 Amazon A EC2 uto Scaling 群组并获取随机实例 ID。实例 ID 用于执行 Systems Manager 命令。

1. Lambda 函数使用 boto 模块再次调 EC2 用亚马逊。Lambda 函数获取正在运行的 Windows 服务器的私有 IP 地址，并将这些地址存储在临时变量中。在步骤 5.1 和 5.2 中，正在运行的 Windows EC2 实例是从子账户中收集的。

1. Lambda 函数 再次调用 Systems Manager 以获取连接至 AWS Directory Service的计算机的信息。

1.  AWS Systems Manager 文档有助于在 Amazon EC2 Windows 服务器上执行 PowerShell 命令，以获取连接到 AD 的计算机的私有 IP 地址。（Systems Manager 文档使用在第 4 步中获得的实例 ID。）

1. AD 域用户名和密码存储在 AWS Systems Manager 参数存储中。 AWS Lambda 然后 Systems Manager 调用 Parameter Store 并获取用于连接 AD 的用户名和密码值。

1. 使用 Systems Manager 文档，使用先前在步骤 4 中获得的实例 ID 在亚马逊 EC2 Windows 服务器上执行 PowerShell 脚本。

1. Amazon 使用 PowerShell 命令 EC2 连接并移除未使用或处于非活动状态的计算机。 AWS Directory Service 

## 工具
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-tools"></a>

**AWS 服务**
+ [AWS Directory Service](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/what_is.html)提供了多种使用微软 Active Directory (AD) 的方法， AWS 服务 例如亚马逊弹性计算云 (亚马逊 EC2)、适用于 SQL Server 的亚马逊关系数据库服务 (Amazon RDS) 和 FSx 适用于 Windows 文件服务器的亚马逊。
+ [AWS Directory Service for Microsoft Active Directory](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_microsoft_ad.html)允许你的目录感知工作负载和 AWS 资源使用中的 Microsoft Active Directory。 AWS 云
+ [亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) 在中提供可扩展的计算容量 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 资源，从而帮助您安全地管理对资源的访问权限。借助 IAM，您可以指定谁或什么人可以访问中的服务和资源 AWS，集中管理细粒度的权限，并分析访问权限以优化权限。 AWS
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 可帮助您管理在 AWS 云端运行的应用程序和基础设施。它简化了应用程序和资源管理，缩短了检测和解决操作问题的时间，并帮助您大规模安全地管理 AWS 资源。
+ [AWS Systems Manager 文档](https://docs.aws.amazon.com/systems-manager/latest/userguide/documents.html)定义了 Systems Manager 对您的托管实例执行的操作。Systems Manager 包括 100 个预先配置的文档，您可以在运行时通过指定参数进行使用。
+ [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) 是一项 AWS Systems Manager 功能，可为配置数据管理和密钥管理提供安全的分层存储。

**其他工具**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款基础设施即代码（IaC）工具，可帮助您使用代码来预调配和管理云基础设施和资源。
+ [PowerShell](https://learn.microsoft.com/en-us/powershell/)是一款在 Windows、Linux 和 macOS 上运行的微软自动化和配置管理程序。
+ [Python](https://www.python.org/) 是通用的计算机编程语言。

**代码存储库**

此模式的代码可在 GitHub [aws-lambda-ad-cleanup-terraform-](https://github.com/aws-samples/aws-lambda-ad-cleanup-terraform-samples/tree/main/multiple-account-cleanup) samples 存储库中找到。

## 最佳实践
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-best-practices"></a>
+ **自动加入域。**当您启动要成为 Directory Service 域一部分的 Windows 实例时，请在实例创建过程中加入该域，而不是稍后手动添加该实例。要自动加入域，只需在启动新实例时从**域加入目录**下拉菜单中选择正确的目录。有关更多详细信息，请参阅《*Directory Service 管理指南》*中的 “[将 Amazon EC2 Windows 实例无缝加入您的 AWS Managed Microsoft AD 活动目录](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/launching_instance.html)”。
+ **删除未使用的账户。**在 AD 中经常能发现从未使用过的账户。与留在系统中的已禁用或非活动账户一样，被忽视的未使用账户可能会减慢 AD 系统的速度，或者导致您的组织数据容易被泄露。
+ **自动清理 Active Directory。**为降低安全风险并防止过期账户影响 AD 性能，应定期执行 AD 清理工作。可以通过编写脚本来完成大部分 AD 管理和清理任务。任务示例包括移除已禁用和非活动账户、删除空组和非活动组，以及查找过期的用户账户和密码。

## 操作说明
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-epics"></a>

### 设置子账户
<a name="set-up-child-accounts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在子账户中创建一个跨账户角色。 | 要在子账户中创建跨账户角色，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 工程师 | 
| 在子账户中创建一个事件规则。 | 要为每个子女账户创建 EventBridge 规则，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html)有关更多详细信息，请参阅《亚马逊* EventBridge 用户指南*》[中的创建对亚马逊 EventBridge事件做出反应的规则](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule.html)。 | DevOps 工程师 | 
| 创建 EC2 实例并加入 AD。 | 要为 Windows 创建 EC2 实例，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 工程师 | 

### 设置本地工作站
<a name="set-up-the-local-workstation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建项目文件夹，然后添加文件。 | 要克隆存储库并创建项目文件夹，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 工程师 | 
| 构建 `adcleanup.zip` 文件。 | 要压缩 `lambda_function.py` 文件，请运行以下命令：`zip -r adcleanup.zip lambda_function.py` | DevOps 工程师 | 

### 使用 Terraform 配置来预调配目标架构
<a name="provision-the-target-architecture-using-the-terraform-configuration"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 提供 Terraform 变量的值。 | 对于子账户，在 `terraform.tfvars` 文件中提供以下 `arn` 变量的值作为字符串类型：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 工程师 | 
| 初始化 Terraform 配置。 | 要初始化包含 Terraform 文件的工作目录，请运行以下命令：`terraform init` | DevOps 工程师 | 
| 预览更改。 | 在部署基础设施之前，您可以预览 Terraform 将对基础设施所做的更改。要验证 Terraform 是否会按要求进行更改，请运行以下命令：`terraform plan —-var-file=examples/terraform.tfvars` | DevOps 工程师 | 
| 执行建议的操作。 | 要验证 `terraform plan` 命令的结果是否符合预期，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 执行并测试 Lambda 函数。 | 要验证部署是否成功完成，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html)执行结果将显示函数的输出。 | DevOps 工程师 | 
| 查看父账户执行 EventBridge 规则的结果。 | 要查看基于父账户的 Amazon EC2 终止事件的 EventBridge 规则结果，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html)在 CloudWatch 控制台中，**日志组**页面显示 Lambda 函数的结果。 | DevOps 工程师 | 
| 查看子账号执行 EventBridge 规则的结果。 | 要查看基于子女账户的 Amazon EC2 终止事件的 EventBridge 规则结果，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html)在 CloudWatch 控制台中，**日志组**页面显示 Lambda 函数的结果。 | DevOps 工程师 | 

### 使用后清理基础设施
<a name="clean-up-infrastructure-after-use"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理基础设施。 | 要清理您创建的基础设施，请使用以下命令：`terraform destroy`要确认 `destroy` 命令，请键入 `yes`。 | DevOps 工程师 | 
| 清理后验证。 | 验证资源是否已成功移除。 | DevOps 工程师 | 

## 问题排查
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
|  AWS Directory Service （父账户）和 Amazon EC2 实例（子账户）之间的连接问题 — 即使 VPC 对等连接可用，您也无法将子账户的计算机加入到 AD。 | 在中添加路由 VPCs。有关说明，请参阅 AWS Directory Service 文档中的[在目录所有者和目录使用者账户之间配置 VPC 对等连接](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step1_setup_networking.html#step1_configure_owner_account_vpc)。 | 

## 相关资源
<a name="remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad-resources"></a>

**AWS 文档**
+ [Amazon EventBridge 和 AWS Identity and Access Management](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-iam.html)
+ [配置 Systems Manager 所需的实例权限](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)
+ [的身份和访问管理 Directory Service](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/iam_auth_access.html)
+ [适用于 Lambda 的基于身份的 IAM 策略](https://docs.aws.amazon.com/lambda/latest/dg/access-control-identity-based.html)
+ [手动将 Amazon EC2 Windows 实例加入您的 AWS Managed Microsoft AD 活动目录](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/join_windows_instance.html)
+ [使用 AWS Lambda 自动化功能 AWS 账户 从 AWS Managed Microsoft AD 中移除 Amazon EC2 条目](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.html)

**其他资源**
+ [AWS 提供者](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)（Terraform 文档）
+ [后端配置](https://developer.hashicorp.com/terraform/language/backend)（Terraform 文档）
+ [安装 Terraform](https://learn.hashicorp.com/tutorials/terraform/install-cli)（Terraform 文档）
+ [Python boto 模块](https://pypi.org/project/boto/)（Python 包索引存储库）
+ [Terraform 二进制文件下载](https://www.terraform.io/downloads)（Terraform 文档）

# 使用 AWS Lambda 自动化功能 AWS 账户 从 AWS Managed Microsoft AD 中移除 Amazon EC2 条目
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad"></a>

*Rahul Sharad Gaikwad 博士和 Tamilselvan P，Amazon Web Services*

## Summary
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-summary"></a>

Active Directory（AD）是 Microsoft 脚本工具，旨在管理域信息以及用户与网络服务的交互。它在托管服务提供商 (MSPs) 中被广泛用于管理员工凭证和访问权限。由于 AD 攻击者可能利用不活跃的账户尝试入侵组织，因此我们必须找到不活跃的账户并在例行维护计划中将其禁用。使用 AWS Directory Service for Microsoft Active Directory，你可以将 Microsoft Active Directory 作为托管服务运行。

此模式可以帮助您配置 AWS Lambda 自动化，以快速查找和删除不活跃的帐户。使用此模式时，可以获得以下好处：
+ 提高数据库和服务器性能，修复来自不活动账户的安全漏洞。
+ 如果您的 AD 服务器托管在云中，移除不活跃的账户还可以降低存储成本，同时提高性能。您的月度支出可能减少，因为带宽费用和计算资源都可能下降。
+ 借助干净的 Active Directory 将潜在攻击者拒之门外。

## 先决条件和限制
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ 已在本地工作站上[安装](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)和配置 Git。
+ 已在本地工作站上[安装](https://learn.hashicorp.com/tutorials/terraform/install-cli)和配置 Terraform。
+ 带 Active Directory 模块的 Windows 计算机（`ActiveDirectory`）。
+ 中的目录 AWS Managed Microsoft AD 和存储在参数存储区[AWS Systems Manager 参数中的凭证。](https://docs.aws.amazon.com/systems-manager/latest/userguide/parameter-create-console.html)
+ AWS Identity and Access Management (IAM) 角色拥有[工具](#remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-tools)中 AWS 服务 列出的权限*。*有关 IAM 的更多信息，请参阅[相关资源](#remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-resources)。

**限制**
+ 此模式不支持跨账户设置。
+ 有些 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)，然后选择相应服务的链接。

**产品版本**
+ [Terraform 版本 1.1.9 或更高版本](https://developer.hashicorp.com/terraform/install)
+ [Terraform AWS Provider 版本 3.0 或更高版本](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/version-3-upgrade)

## 架构
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-architecture"></a>

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

![\[使用 Lambda 自动化从托管的 Microsoft AD 中删除 EC2 条目的流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/6b50dcc5-4f4b-4eea-85a7-04cebc9f7454/images/b7fc5962-bfb8-4f5a-968e-7487b1d48c4f.png)


下图显示了如下工作流：

1. Amazon 根据 cron 表达式 EventBridge 触发该 AWS Lambda 函数。（对于此模式，cron 表达式的执行频率为每天一次。）

1. 所需的 IAM 角色和策略是 AWS Lambda 通过 Terraform 创建并附加到的。

1. 使用 Python boto 模块执行该 AWS Lambda 函数并调用亚马逊弹性计算云 (Amazon EC2) Auto Scaling Groups。Lambda 函数获取随机实例 ID。实例 ID 用于执行 AWS Systems Manager 命令。

1. AWS Lambda EC2 使用 boto 模块再次调用 Amazon，获取正在运行的 Windows 服务器的私有 IP 地址，并将这些地址存储在临时变量中。

1. AWS Lambda 再次调用 Systems Manager 以获取所连接的计算机信息 Directory Service。

1.  AWS Systems Manager 文档有助于在 Amazon EC2 Windows 服务器上执行 PowerShell 脚本，以获取与 AD 连接的计算机的私有 IP 地址。

1. AD 域用户名和密码存储在 AWS Systems Manager 参数存储中。 AWS Lambda 然后 Systems Manager 调用 Parameter Store 并获取用于连接 AD 的用户名和密码值。

1. 使用 Systems Manager 文档，使用先前在步骤 3 中获得的实例 ID 在亚马逊 EC2 Windows 服务器上执行 PowerShell 脚本。

1. Amazon 使用 PowerShell 命令 Directory Service 进行 EC2 连接，并移除未使用或处于非活动状态的计算机。

## 工具
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-tools"></a>

**AWS 服务**
+ [AWS Directory Service](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/what_is.html)提供了多种使用微软 Active Directory (AD) 的方法， AWS 服务 例如亚马逊弹性计算云 (亚马逊 EC2)、适用于 SQL Server 的亚马逊关系数据库服务 (Amazon RDS) 和 FSx 适用于 Windows 文件服务器的亚马逊。
+ [AWS Directory Service for Microsoft Active Directory](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_microsoft_ad.html)允许你的目录感知工作负载和 AWS 资源使用中的 Microsoft Active Directory。 AWS 云
+ [亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) 在中提供可扩展的计算容量 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资源，从而帮助您安全地管理对资源的访问权限。借助 IAM，您可以指定谁或什么人可以访问中的服务和资源 AWS，集中管理细粒度的权限，并分析访问权限以优化权限。 AWS
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 可帮助您管理在 AWS 云端运行的应用程序和基础设施。它简化了应用程序和资源管理，缩短了检测和解决操作问题的时间，并帮助您大规模安全地管理 AWS 资源。
+ [AWS Systems Manager 文档](https://docs.aws.amazon.com/systems-manager/latest/userguide/documents.html)定义了 Systems Manager 对您的托管实例执行的操作。Systems Manager 包括 100 个预先配置的文档，您可以在运行时通过指定参数进行使用。
+ [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) 是一项 AWS Systems Manager 功能，可为配置数据管理和密钥管理提供安全的分层存储。

**其他工具**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款开源基础设施即代码 (IaC) 工具，可帮助您使用代码来配置和管理云基础架构和资源。
+ [PowerShell](https://learn.microsoft.com/en-us/powershell/)是一款在 Windows、Linux 和 macOS 上运行的微软自动化和配置管理程序。
+ [Python](https://www.python.org/) 是通用的计算机编程语言。

**代****码存储库**

此模式的代码可在 GitHub [自定义 AD 清理自动化解决方案](https://github.com/aws-samples/aws-lambda-ad-cleanup-terraform-samples/)存储库中找到。

## 最佳实践
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-best-practices"></a>
+ **自动加入域。**当您启动要成为 Directory Service 域一部分的 Windows 实例时，请在实例创建过程中加入该域，而不是稍后手动添加该实例。要自动加入域，只需在启动新实例时从**域加入目录**下拉菜单中选择正确的目录。有关更多详细信息，请参阅《*Directory Service 管理指南》*中的 “[将 Amazon EC2 Windows 实例无缝加入您的 AWS Managed Microsoft AD 活动目录](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/launching_instance.html)”。
+ **删除未使用的账户。**在 AD 中经常能发现从未使用过的账户。与留在系统中的已禁用或非活动账户一样，被忽视的未使用账户可能会减慢 AD 系统的速度，或者导致您的组织数据容易被泄露。
+ **自动清理 Active Directory。**为降低安全风险并防止过期账户影响 AD 性能，应定期执行 AD 清理工作。可以通过编写脚本来完成大部分 AD 管理和清理任务。任务示例包括移除已禁用和非活动账户、删除空组和非活动组，以及查找过期的用户账户和密码。

## 操作说明
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建项目文件夹，然后添加文件。 | 要克隆存储库并创建项目文件夹，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.html) | DevOps 工程师 | 

### 使用 Terraform 配置预调配目标架构
<a name="provision-the-target-architecture-by-using-the-terraform-configuration"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 初始化 Terraform 配置。 | 要初始化包含 Terraform 文件的工作目录，请运行以下命令。`terraform init` | DevOps 工程师 | 
| 预览更改。 | 在部署基础设施之前，您可以预览 Terraform 将对基础设施所做的更改。要验证 Terraform 是否会按要求进行更改，请运行以下命令。`terraform plan` | DevOps 工程师 | 
| 执行建议的操作。 | 要验证 `terraform plan` 命令的结果是否符合预期，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.html) | DevOps 工程师 | 
| 清理基础设施。 | 要清理您创建的基础设施，请使用以下命令。`terraform destroy`要确认销毁命令，请键入 `yes`。 | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 执行并测试 Lambda 函数。 | 要验证部署是否成功完成，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.html)执行结果将显示函数的输出。 | DevOps 工程师 | 
| 查看 Lambda 函数的结果。 | 在这种模式中， EventBridge 规则每天执行 Lambda 函数一次。要查看 Lambda 函数的结果，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.html)在 CloudWatch 控制台中，**日志组**页面显示 Lambda 函数的结果。 | DevOps 工程师 | 

### 使用后清理基础设施
<a name="clean-up-infrastructure-after-use"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理基础设施。 | 要清理您创建的基础设施，请使用以下命令。`terraform destroy`要确认销毁命令，请键入 `yes`。 | DevOps 工程师 | 
| 清理后验证。 | 验证资源是否已成功移除。 | DevOps 工程师 | 

## 问题排查
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 如果您尝试移除 AD 计算机，会收到“访问被拒绝”的消息。无法移除 AD 计算机，因为默认情况下，该操作会尝试移除两个私有 IP 地址，而这些地址作为 AD 服务的一部分被绑定。 | 为避免此错误，请使用以下 Python 操作：在列出 AD 计算机输出与运行 Windows 的计算机输出之间的差异时，忽略前两台计算机。<pre>Difference = Difference[2:]</pre> | 
| 当 Lambda 在 Windows 服务器上执行 PowerShell 脚本时，它预计 Active Directory 模块在默认情况下可用。如果模块不可用，Lambda 函数会生成一个错误，指出 “未在实例上安装 G AdComputer et-”。 | 为避免此错误，请使用 EC2 实例的用户数据安装所需的模块。使用此模式 GitHub 存储库中的[EC2WindowsUserdata](https://github.com/aws-samples/aws-lambda-ad-cleanup-terraform-samples/blob/main/EC2WindowsUserdata)脚本。 | 

## 相关资源
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-resources"></a>

**AWS 文档**
+ [亚马逊 EventBridge 和 AWS Identity and Access Management](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-iam.html)
+ [配置 Systems Manager 所需的实例权限](https://docs.aws.amazon.com/systems-manager/latest/userguide/setup-instance-profile.html)
+ [的身份和访问管理 Directory Service](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/iam_auth_access.html)
+ [手动将亚马逊 EC2 Windows 实例加入您的 AWS Managed Microsoft AD 活动目录](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/join_windows_instance.html)
+ [在中使用基于身份的 IAM 策略 AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/access-control-identity-based.html)

**其他资源**
+ [AWS 提供者](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)（Terraform 文档）
+ [后端配置](https://developer.hashicorp.com/terraform/language/backend)（Terraform 文档）
+ [安装 Terraform](https://learn.hashicorp.com/tutorials/terraform/install-cli)（Terraform 文档）
+ [Python boto 模块](https://pypi.org/project/boto/)（Python 包索引存储库）
+ [Terraform 二进制文件下载](https://www.terraform.io/downloads)（Terraform 文档）

# AWS Glue 使用 pytest 框架对 Python ETL 作业运行单元测试
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework"></a>

*Praveen Kumar Jeyarajan 和 Vaidy Sankaran，Amazon Web Services*

## Summary
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-summary"></a>

您可以在[本地开发环境 AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html)中为 Python 提取、转换和加载 (ETL) 作业运行单元测试，但是在 DevOps 管道中复制这些测试可能既困难又耗时。在技术堆栈上 AWS 对大型机 ETL 流程进行现代化改造时，单元测试可能特别具有挑战性。此模式向您展示了如何简化单元测试，同时保持现有功能完好无损，在发布新功能时避免中断关键应用程序功能，并维护高质量的软件。您可以使用此模式中的步骤和代码示例， AWS Glue 通过使用中的 pytest 框架，为 Python ETL 作业运行单元测试。 AWS CodePipeline您也可以使用此模式来测试和部署多个 AWS Glue 作业。

## 先决条件和限制
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+  AWS Glue 您的库的亚马逊 Elastic Container Registry (Amazon ECR) 图片 URI，从[亚马逊](https://gallery.ecr.aws/glue/aws-glue-libs) ECR 公共画廊下载
+ 带有目标 AWS 账户 配置文件的 Bash 终端（在任何操作系统上）和 AWS 区域
+ [Python 3.10](https://www.python.org/downloads/) 或更高版本
+ [Pytest](https://github.com/pytest-dev/pytest)
+ 用于测试的 [Moto](https://github.com/getmoto/moto) Python 库 AWS 服务

## 架构
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-architecture"></a>

下图描述了如何将基于 Python 的 AWS Glue ETL 流程的单元测试整合到典型的企业级管道 AWS DevOps 中。

![\[AWS Glue ETL 流程的单元测试。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/82781ca8-4da0-4df0-bf23-32992fece231/images/6286dafc-f1e0-4967-beed-4dedc6047c10.png)


下图显示了如下工作流：

1. 在源代码阶段， AWS CodePipeline 使用版本控制的亚马逊简单存储服务 (Amazon S3) 存储桶来存储和管理源代码资产。这些资源包括 Python ETL 作业示例 (`sample.py`)、单元测试文件 (`test_sample.py`) 和 AWS CloudFormation 模板。然后，将最新的代码从主分支 CodePipeline 传输到 AWS CodeBuild 项目以进行进一步处理。

1. 在构建和发布阶段，在 AWS Glue 公共 Amazon ECR 映像的帮助下，对上一个源代码阶段的最新代码进行了单元测试。然后，将测试报告发布到 CodeBuild 报告组。面向 AWS Glue 图书馆的公共 Amazon ECR 存储库中的容器镜像包括本地运行所需的所有二进制文件和[PySpark基于单元测试的](https://spark.apache.org/docs/latest/api/python/) ETL 任务。 AWS Glue 公共容器存储库有三个映像标签， AWS Glue支持的每个版本各有一个映像标签。出于演示目的，此模式使用了 `glue_libs_4.0.0_image_01` 映像标签。要在中 CodeBuild将此容器映像用作运行时映像，请复制与您要使用的图像标签相对应的图像 URI，然后更新`TestBuild`资源 GitHub 存储库中的`pipeline.yml`文件。

1. 在部署阶段， CodeBuild 项目将启动，如果所有测试都通过，它将代码发布到 Amazon S3 存储桶。

1. 用户使用`deploy`文件夹中的 CloudFormation 模板部署 AWS Glue 任务。

## 工具
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-tools"></a>

**AWS 服务**
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.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)是一项安全、可扩展且可靠的托管容器映像注册表服务。
+ [AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/what-is-glue.html) 是一项完全托管的 ETL 服务。它可以帮助您在数据存储和数据流之间对数据进行可靠地分类、清理、扩充和移动。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一种对象存储服务，提供行业领先的可扩展性、数据可用性、安全性和性能。

**其他工具**
+ [Python](https://www.python.org/) 是一种高级解释型通用编程语言。
+ [Moto](https://github.com/getmoto/moto) 是一个用于测试的 Python 库 AWS 服务。
+ [Pytest](https://github.com/pytest-dev/pytest) 是一个用于编写小型单元测试的框架，单元测试可扩展以支持应用程序和库的复杂功能测试。
+ 的 [Python ETL 库](https://github.com/awslabs/aws-glue-libs) AWS Glue 是 Python 库的存储库，这些库用于本地开发的 PySpark 批处理作业。 AWS Glue

**代码存储库**

此模式的代码可在 GitHub [aws-glue-jobs-unit-](https://github.com/aws-samples/aws-glue-jobs-unit-testing) testing 存储库中找到。存储库包含以下资源：
+ 文件夹中基于 Python 的 AWS Glue 作业示例 `src`
+ `tests` 文件夹中的关联单元测试用例（使用 pytest 框架构建）
+ 文件夹中的 CloudFormation 模板（用 YAML 编写）`deploy`

## 最佳实践
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-best-practices"></a>

** CodePipeline 资源安全**

最佳做法是对连接到您的管道的源存储库使用加密和身份验证 CodePipeline。有关更多信息，请参阅 CodePipeline 文档中的[安全最佳实践](https://docs.aws.amazon.com/codepipeline/latest/userguide/security-best-practices.html)。

**监控和记录 CodePipeline 资源**

最佳做法是使用 AWS 日志记录功能来确定用户在您的账户中执行了哪些操作以及他们使用了哪些资源。日志文件显示以下内容：
+ 操作的时间和日期
+ 操作的源 IP 地址
+ 由于权限不足而失败的操作

 AWS CloudTrail 和 Amazon Ev CloudWatch ents 中提供了日志功能。您可以使用 CloudTrail 记录由您或代表您进行的 AWS API 调用和相关事件 AWS 账户。有关更多信息，请参阅 CodePipeline 文档 AWS CloudTrail中的[使用记录 CodePipeline API 调用](https://docs.aws.amazon.com/codepipeline/latest/userguide/monitoring-cloudtrail-logs.html)。

您可以使用 CloudWatch 事件来监控您的 AWS 云 资源和正在运行的应用程序 AWS。您也可以在 CloudWatch 事件中创建警报。有关更多信息，请参阅 CodePipeline 文档中的[监控 CodePipeline 事件](https://docs.aws.amazon.com/codepipeline/latest/userguide/detect-state-changes-cloudwatch-events.html)。

## 操作说明
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-epics"></a>

### 部署源代码
<a name="deploy-the-source-code"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 准备代码存档以进行部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.html) | DevOps 工程师 | 
| 创建 CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.html)堆栈使用 Amazon S3 作为源来创建 CodePipeline 视图。在上面的步骤中，管道是 **aws-glue-unit-test-pipelin** e。 | AWS DevOps， DevOps 工程师 | 

### 运行单元测试
<a name="run-the-unit-tests"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 运行管线中的单元测试。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.html) | AWS DevOps， DevOps 工程师 | 

### 清理所有 AWS 资源
<a name="clean-up-all-aws-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在环境中清理资源。 | 为避免额外的基础设施成本，请务必在尝试此模式中提供的示例后删除堆栈。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.html) | AWS DevOps， DevOps 工程师 | 

## 问题排查
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
|  CodePipeline 服务角色无法访问 Amazon S3 存储桶。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework.html) | 
| CodePipeline 返回一个错误，指示 Amazon S3 存储桶未进行版本控制。 | CodePipeline 要求对源 Amazon S3 存储桶进行版本控制。对 Amazon S3 存储桶启用版本控制。有关说明，请参阅[在存储桶上启用版本控制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/manage-versioning-examples.html)。 | 

## 相关资源
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-resources"></a>
+ [AWS Glue](https://aws.amazon.com/glue/)
+ [在本地开发和测试 AWS Glue 作业](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-etl-libraries.html)
+ [AWS CloudFormation 适用于 AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/populate-with-cloudformation-templates.html)

## 附加信息
<a name="run-unit-tests-for-python-etl-jobs-in-aws-glue-using-the-pytest-framework-additional"></a>

此外，您可以使用 AWS Command Line Interface (AWS CLI) 部署 AWS CloudFormation 模板。有关更多信息，请参阅 CloudFormation 文档中的[使用转换快速部署模板](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-deploy.html)。

# 使用 AWS CodePipeline 和 AWS CDK 设置 CI/CD 管道
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk"></a>

*Konstantin Zarudaev、Yasha Dabas、Lars Kinder 和 Cizer Pereira，Amazon Web Services*

## 主页
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-summary"></a>

通过持续集成和持续交付实现软件构建和发布过程的自动化（CI/CD) supports repeatable builds and rapid delivery of new features to your users. You can quickly and easily test each code change, and you can catch and fix bugs before releasing your software. By running each change through your staging and release process, you can verify the quality of your application or infrastructure code. CI/CD体现了一种文化、一套操作原则和[一系列实践](https://aws.amazon.com/devops/#cicd)，可帮助应用程序开发团队更频繁、更可靠地交付代码变更。该实现也被称之为 *CI/CD* 管线。

此模式定义了亚马逊网络服务 (AWS) 上与 AWS 存储库的可重复使用的持续集成和持续交付 (CI/CD) 管道。 CodeCommit AWS CodePipeline 管道是使用 AW [S Cloud Development Kit (AWS CDK) v2](https://aws.amazon.com/cdk/) 编写的。

使用 CodePipeline，您可以通过 AWS 管理控制台界面、AWS 命令行界面 (AWS CLI)、AWS 或 AWS 对软件发布过程的不同阶段进行建模。 CloudFormation SDKs此模式演示了使用 AWS CDK 的实现 CodePipeline 及其组件。除了构造库外，AWS CDK 还包括一个工具包（CLI 命令 `cdk`），它是与您的 AWS CDK 应用程序交互的主要工具。除其他功能外，该工具包还提供将一个或多个堆栈转换为 CloudFormation 模板并将其部署到 AWS 账户的功能。

该管线包括验证第三方库安全性的测试，有助于确保在指定环境中快速、自动发布。您可通过对应用程序进行验证来提高应用程序的整体安全性。

这种模式的目的是加快使用 CI/CD 管道来部署代码，同时确保部署的资源符合 DevOps 最佳实践。实施[示例代码](https://github.com/aws-samples/aws-codepipeline-cicd)后，您将拥有一个 [AWS](https://aws.amazon.com/codepipeline/)， CodePipeline其中包含整理、测试、安全检查、部署和部署后流程。此模式还包括 Makefile 步骤。使用 Makefile，开发人员可以在本地重现 CI/CD 步骤并提高开发过程的速度。

## 先决条件和限制
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 基本定义如下：
  + AWS CDK
  + AWS CloudFormation
  + AWS CodePipeline
  + TypeScript

**限制**

此模式 TypeScript 仅将 [AWS CDK](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html) 用于。它不包含 AWS CDK 支持的其他语言。

**产品版本**

使用以下工具的最新版本：
+ AWS 命令行界面（AWS CLI）
+ cfn\$1nag
+ git-remote-codecommit
+ Node.js

## 架构
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-architecture"></a>

**目标技术堆栈**
+ AWS CDK
+ AWS CloudFormation
+ AWS CodeCommit
+ AWS CodePipeline

**目标架构**

该管道由 AWS CodeCommit 存储库的更改触发 (`SampleRepository`)。一开始， CodePipeline 构建工件，更新自身，然后启动部署过程。生成的管线将解决方案部署至三个独立的环境：
+ 开发 – 在活跃的开发环境进行三步代码检查
+ 测试 - 集成和回归测试环境
+ Prod – 生产环境

开发阶段包含的三个步骤是 linting、安全性和单元测试。这些步骤并行运行，以加快流程。为确保管线仅提供可运行的构件，每当流程中的某个步骤失败时，它就会停止运行。开发阶段部署后，管线运行验证测试以验证结果。如果成功，管线会将构件部署到测试环境，其中包含部署后验证。最后一步是将构件部署至 Prod 环境。

下图显示了从 CodeCommit 存储库到由执行的构建和更新过程的工作流程 CodePipeline、三个开发环境步骤，以及三个环境中每个环境中的后续部署和验证。

![\[开发环境包含代码检查、安全性测试和单元测试，所有这些环节均涵盖部署和验证步骤。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/d617e735-8624-4722-8a3d-073bcc356328/images/92504aac-03e3-4c95-b225-74505f8dd136.png)


## 工具
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-tools"></a>

**Amazon Web Services**
+ [AWS Cloud Development Kit（AWS CDK）](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一个软件开发框架，可帮助您在代码中定义并预调配 AWS 云基础设施。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可帮助您设置 AWS 资源，快速一致地配置这些资源，并在 AWS 账户和区域的整个生命周期中对其进行管理。在这种模式中， CloudFormation 模板可用于创建 CodeCommit 存储库和 C CodePipeline I/CD 管道。
+ [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) 是一项 CI/CD 服务，可帮助您快速建模和配置软件发布的不同阶段，并自动执行持续发布软件更改所需的步骤。
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它可帮助您通过命令行 Shell 中的命令与 Amazon Web Services 交互。

**其他工具**
+ [cfn\$1nag](https://github.com/stelligent/cfn_nag) 是一个开源工具，可在 CloudFormation 模板中查找模式以识别潜在的安全问题。
+ [git-remote-codecommit](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-git-remote-codecommit.html)是一个通过扩展 Git 从 CodeCommit 存储库中推送和提取代码的实用工具。
+ [Node.js](https://nodejs.org/en/docs/) 是一个事件驱动的 JavaScript 运行时环境，专为构建可扩展的网络应用程序而设计。

**代码**

此模式的代码可在[ CodePipeline 带有 CI/CD 实践存储库的 GitHub AWS](https://github.com/aws-samples/aws-codepipeline-cicd) 中找到。

## 最佳实践
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-best-practices"></a>

查看资源（例如 AWS Identity and Access Management (IAM) 策略），以确认它们符合您的组织最佳实践。

## 操作说明
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-epics"></a>

### 安装工具
<a name="install-tools"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 macOS 或 Linux 上安装工具。 | 如果您使用的是 macOS 或 Linux，则可以通过在首选终端中运行以下命令或使用 [Homebrew for Linux](https://docs.brew.sh/Homebrew-on-Linux) 安装这些工具。<pre>brew install<br />brew install git-remote-codecommit<br />brew install ruby brew-gem<br />brew-gem install cfn-nag</pre> | DevOps 工程师 | 
| 设置 AWS CLI。 | 要设置 AWS CLI，请使用适合操作系统的说明：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.html) | DevOps 工程师 | 

### 设置初始部署
<a name="set-up-the-initial-deployment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 下载或克隆代码。 | 要获取此模式使用的代码，请执行以下操作之一：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.html)<pre>git clone --depth 1 https://github.com/aws-samples/aws-codepipeline-cicd.git</pre>从克隆的存储库中删除 `.git` 目录。<pre>cd ./aws-codepipeline-cicd<br />rm -rf ./.git</pre>稍后，您将使用新创建的 AWS CodeCommit 存储库作为远程来源。 | DevOps 工程师 | 
| 连接至 Amazon Web Services account。 | 您可使用临时安全令牌或登录区身份验证进行连接。要确认您使用的是正确的账户和 AWS 区域，请运行以下命令。<pre>AWS_REGION="eu-west-1"<br />ACCOUNT_NUMBER=$(aws sts get-caller-identity --query Account --output text)<br />echo "${ACCOUNT_NUMBER}"</pre> | DevOps 工程师 | 
| 引导 环境。 | 要引导 AWS CDK 环境，请运行以下命令。<pre>npm install<br />npm run cdk bootstrap "aws://${ACCOUNT_NUMBER}/${AWS_REGION}"</pre>成功引导环境后，应该显示以下输出。<pre>⏳  Bootstrapping environment aws://{account}/{region}...<br />✅  Environment aws://{account}/{region} bootstrapped</pre>有关更多信息，请参阅 AWS CDK 文档中的 [AWS CDK 引导](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)。 | DevOps 工程师 | 
| 合成模板。 | 要合成 AWS CDK 应用程序，请使用 `cdk synth` 命令。<pre>npm run cdk synth</pre>您应当看到如下输出。<pre>Successfully synthesized to <path-to-directory>/aws-codepipeline-cicd/cdk.out<br />Supply a stack id (CodePipeline, Dev-MainStack) to display its template.</pre> | DevOps 工程师 | 
| 部署 CodePipeline 堆栈。 | 现在，您已经引导并合成了 CloudFormation 模板，可以对其进行部署。部署将创建 CodePipeline 管道和 CodeCommit 存储库，这将是管道的来源和触发器。<pre>npm run cdk -- deploy CodePipeline --require-approval never</pre>运行命令后，您应该会看到 CodePipeline 堆栈的成功部署和输出信息。`CodePipeline.RepositoryName`为您提供 AWS 账户中 CodeCommit 存储库的名称。<pre>CodePipeline: deploying...<br />CodePipeline: creating CloudFormation changeset...<br />✅  CodePipeline<br />Outputs:<br />CodePipeline.RepositoryName = SampleRepository<br />Stack ARN:<br />arn:aws:cloudformation:REGION:ACCOUNT-ID:stack/CodePipeline/STACK-ID</pre> | DevOps 工程师 | 
| 设置远程 CodeCommit 存储库和分支。 | 成功部署后， CodePipeline 将启动管道的首次运行，您可以在 [AWS CodePipeline 控制台](https://eu-west-1.console.aws.amazon.com/codesuite/codepipeline/pipelines)中找到该管道。由于 AWS CDK 且 CodeCommit 不启动默认分支，因此此初始管道运行将失败并返回以下错误消息。<pre>The action failed because no branch named main was found in the selected AWS CodeCommit repository SampleRepository. Make sure you are using the correct branch name, and then try again. Error: null</pre>要修复此错误，请将远程源设置为 `SampleRepository`，然后创建所需 `main` 分支。<pre>RepoName=$(aws cloudformation describe-stacks --stack-name CodePipeline --query "Stacks[0].Outputs[?OutputKey=='RepositoryName'].OutputValue" --output text)<br />echo "${RepoName}"<br />#<br />git init<br />git branch -m master main<br />git remote add origin codecommit://${RepoName}<br />git add .<br />git commit -m "Initial commit"<br />git push -u origin main</pre> | DevOps 工程师 | 

### 测试已部署的 CodePipeline 管道
<a name="test-the-deployed-codepipeline-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 提交更改，以激活管线。 | 成功完成初始部署后，您应该拥有一个完整的 CI/CD 管道，其中包含一个用于`SampleRepository`作为源`main`分支的分支。一旦您提交对 `main` 分支的更改，管线就会启动并运行以下操作序列：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.html) | DevOps 工程师 | 

### 使用 Makefile 在本地测试
<a name="test-locally-by-using-a-makefile"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 Makefile 运行开发过程。 | 您可使用 `make` 命令在本地运行整个管线，也可以运行单个步骤（例如 `make linting`）。要使用 `make` 进行测试，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.html) | 应用程序开发者、 DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除 AWS CDK 应用程序资源。 | 要清理您的 AWS CDK 应用程序，请运行以下命令。<pre>cdk destroy --all</pre>请注意，引导启动期间创建的 Amazon Simple Storage Service (Amazon S3) 存储桶将不会自动删除。它们需要允许删除的保留策略，或者您需要在您的 Amazon Web Services account 中手动删除它们。 | DevOps 工程师 | 

## 问题排查
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 该模板未按预期工作。 | 如果出现问题且模板无法正常工作，请确保您具备以下条件：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk.html) | 

## 相关资源
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-resources"></a>
+ [IAM Identity Center 中的常见任务入门](https://docs.aws.amazon.com/singlesignon/latest/userguide/getting-started.html)
+ [AWS CodePipeline 文档](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html)
+ [AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/home.html)

# 使用 Terraform 设置企业级规模的集中式日志记录
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform"></a>

*Aarti Rajput、Yashwant Patel 和 Nishtha Yadav，Amazon Web Services*

## Summary
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-summary"></a>

集中式日志记录对于组织的云基础设施至关重要，因为它能让企业清晰掌握自身的运营状况、安全态势及合规情况。随着您的组织跨多个账户扩展其 AWS 环境，结构化的日志管理策略成为运行安全操作、满足审计要求和实现卓越运营的基础。

这种模式提供了一个可扩展的安全框架，用于集中来自多个 AWS 账户 和服务的日志，从而在复杂 AWS 的部署中实现企业级日志管理。该解决方案使用Terraform实现自动化，Terraform是一种基础设施即代码（IaC）工具，可 HashiCorp 确保一致和可重复的部署，并最大限度地减少手动配置。通过结合亚马逊 CloudWatch 日志、Amazon Data Firehose 和亚马逊简单存储服务 (Amazon S3) Service，您可以实施一个强大的日志聚合和分析管道，该管道可提供：
+ 在整个组织中集中管理日志 AWS Organizations
+ 自动日志收集，内置安全控件
+ 可扩展的日志处理和持久存储功能
+ 简化的合规报告和审计跟踪记录
+ 实时运营洞察和监控

该解决方案通过日志收集来自亚马逊 Elastic Kubernetes Service（Amazon EKS） AWS Lambda 容器、函数和亚马逊关系数据库服务（Amazon RDS）数据库实例的日志。 CloudWatch 它使用 CloudWatch 订阅过滤器自动将这些日志转发到专用的日志帐户。Firehose 管理高吞吐量的日志流传输管道，将日志数据传输至 Amazon S3 进行长期存储。将 Amazon Simple Queue Service（Amazon SQS）配置为在创建对象后接收 Amazon S3 事件通知。这样可实现与分析服务的集成，包括：
+ 用于日志搜索、可视化和实时分析的 Amazon OpenSearch 服务
+ Amazon Athena，用于基于 SQL 的查询操作
+ Amazon EMR，用于大规模数据处理
+ Lambda，用于自定义转换
+ 适用于仪表板的 Amazon Quick

所有数据均使用 AWS Key Management Service (AWS KMS) 进行加密，整个基础架构通过使用 Terraform 进行部署，以实现跨环境的一致配置。

这种集中式日志记录方法使组织能够改善其安全状况，保持合规性要求，并优化其 AWS 基础架构的运营效率。

## 先决条件和限制
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-prereqs"></a>

**先决条件**
+ 通过使用 [AWS Control Tower](https://docs.aws.amazon.com/controltower/latest/userguide/getting-started-with-control-tower.html) 为组织构建的登录区
+ 已部署并配置了所需账户的 [Account Factory for Terraform（AFT）](https://docs.aws.amazon.com/controltower/latest/userguide/aft-getting-started.html)
+ 用于预调配基础设施的 [Terraform](https://developer.hashicorp.com/terraform/downloads)
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started.html) 跨账户访问的角色和策略

有关设置 AWS Control Tower、AFT 和应用程序账户的说明，请参阅 [Epics 部分](#set-up-centralized-logging-at-enterprise-scale-by-using-terraform-epics)。

**所需账户**

您的组织中 AWS Organizations 应包括以下账户：
+ **应用程序账户** — AWS 服务 （Amazon EKS、Lambda 和 Amazon RDS）运行和生成日志的一个或多个源账户
+ **日志存档账户** - 用于集中存储和管理日志的专用账户

**产品版本**
+ [AWS Control Tower 版本 3.1](https://docs.aws.amazon.com/controltower/latest/userguide/2023-all.html#lz-3-1) 或更高版本
+ [Terraform 版本 0.15.0](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) 或更高版本

## 架构
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-architecture"></a>

下图说明了一种 AWS 集中式日志架构，该架构提供了一种可扩展的解决方案，用于收集、处理来自多个应用程序帐户的日志，并将其存储到一个专用的日志存档帐户中。该架构可以有效地处理来自 AWS 服务 Amazon RDS、Amazon EKS 和 Lambda 的日志，并通过简化的流程将这些日志路由到日志存档账户中的区域 S3 存储桶。

![\[AWS 集中式日志记录架构，用于从多个应用程序账户收集日志。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/9fc71a10-65d6-437b-9128-cc27bda11af4/images/2e916040-0f11-4712-a8dd-31c95194ce5d.png)


该工作流包括五个流程：

1. **日志流流程**
   + 日志流过程从应用程序账户开始，在那里 AWS 服务 生成各种类型的日志，例如来自 Amazon RDS 的常规日志、错误日志、审计日志、慢速查询日志、来自 Amazon EKS 的控制平面日志以及来自 Lambda 的函数执行和错误日志。
   + CloudWatch 用作初始收集点。它在每个应用程序账户中按日志组级别收集这些日志。
   + 在中 CloudWatch，[订阅筛选器](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Subscriptions.html)决定应将哪些日志转发到中央账户。这些筛选条件支持对日志转发进行精细控制，因此您可指定确切的日志模式或完整的日志流，以实现日志的集中管理。

1. **跨账户日志传输**
   + 日志将移至日志存档帐户。 CloudWatch 订阅过滤器便于跨账户转账并保留区域背景。
   + 该架构建立了多个并行流，以高效地处理不同的日志源，从而确保实现最佳性能和可扩展性。

1. **日志存档账户中的日志处理**
   + 在日志存档账户中，Firehose 处理传入的日志流。
   + 每个区域均维护专用 Firehose 传输流，可以根据需要转换或丰富日志。
   + 这些 Firehose 传输流会将处理后的日志传输至日志存档账户中的 S3 存储桶，该账户与源应用程序账户位于同一区域（图中的区域 A），以满足数据主权要求。

1. **通知和其他工作流**
   + 当日志到达目标 S3 存储桶后，该架构会通过 Amazon SQS 实现通知系统。
   + 区域 SQS 队列支持异步处理，并且可以根据存储的日志触发其他工作流、分析或提醒系统。

1. **AWS KMS 为了安全**

    AWS KMS 为了安全起见，该架构包含在内。 AWS KMS 为 S3 存储桶提供加密密钥。这样可以确保所有存储的日志均实现静态加密，同时按区域进行加密以满足数据驻留要求。

## 工具
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-tools"></a>

**AWS 服务**
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 是一项监控和可观察性服务，它以日志、指标和事件的形式收集监控和操作数据。它提供了在 AWS 和本地服务器上运行的 AWS 资源、应用程序和服务的统一视图。
+ [CloudWatch 日志订阅过滤器](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html)是匹配传入日志事件中的模式并将匹配的日志事件传送到指定 AWS 资源以供进一步处理或分析的表达式。
+ AWS Control Tower Account F@@ [actory For Terraform (AFT) 设置了 Terraform 管道来帮助你在中配置和自定义账户](https://docs.aws.amazon.com/controltower/latest/userguide/aft-overview.html)。 AWS Control Tower AFT 提供基于 Terraform 的账户配置，同时允许您使用管理账户。 AWS Control Tower
+ [Amazon Data Firehos](https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html) e 向亚马逊 S3、亚马逊 Redshift 和亚马逊服务等目的地提供实时流数据。 OpenSearch 它可自动扩展以满足数据吞吐量要求，并且无需进行日常管理。
+ [Amazon Elastic Kubernetes Service（Amazon EKS）](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html)是一项托管式容器编排服务，可让您轻松地使用 Kubernetes 部署、管理和扩展容器化应用程序。它会自动管理 Kubernetes 控制面板节点的可用性和可扩展性。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 创建和控制用于加密数据的加密密钥。 AWS KMS 与其他服务集成 AWS 服务 ，以帮助您保护使用这些服务存储的数据。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项无服务器计算服务，使您无需预调配或管理服务器即可运行代码。它会通过响应每个触发器来运行代码，从而自动扩展应用程序，且仅按您使用的计算时间收费。
+ [Amazon Relational Database Service（Amazon RDS）](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html)是一项托管式关系数据库服务，用户能够在云中轻松地设置、操作和扩展关系数据库。它提供经济高效且可调整的容量，同时自动执行耗时的管理任务。
+ [Amazon Simple Queue Service（Amazon SQS）](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/welcome.html)是一种消息队列服务，可解耦和扩展微服务、分布式系统和无服务器应用程序。它消除了管理和操作面向消息的中间件的复杂性。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一种基于云的对象存储服务，可提供出色的可扩展性、数据可用性、安全性和性能。该服务可在 Web 上的任何位置存储和检索任意数量的数据。

**其他工具**
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。

**代码**

此模式的代码可在 GitHub[集中式日志](https://github.com/aws-samples/sample-centralised-logging-at-enterprise-scale-using-terraform)存储库中找到。

## 最佳实践
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-best-practices"></a>
+ [AWS 账户 在中的单个组织中使用多](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts.html)个 AWS Organizations。此实践可实现跨账户的集中式管理和标准化日志记录。
+ [为 S3 存储桶配置版本控制、生命周期策略和跨区域复制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/replication.html)。实施加密和访问日志记录，以确保安全性及合规性。
+ [通过使用带有标准时间戳和字段的 JSON 格式实施通用日志记录标准](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CWL_AnalyzeLogData-discoverable-fields.html)。使用一致的前缀结构和相关性 IDs ，便于跟踪和分析。
+ 通过[AWS KMS 加密和最低权限访问启用安全控制](https://docs.aws.amazon.com/AmazonS3/latest/userguide/security-best-practices.html)。保持 AWS CloudTrail 监控和定期轮换密钥以增强安全性。
+ 设置配送跟踪的[CloudWatch 指标和提醒](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html)。通过自动通知监控成本与性能。
+ 配置 [Amazon S3 保留策略](https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-lifecycle-mgmt.html)以满足合规性要求，并启用 Amazon S3 服务器访问日志记录，跟踪对 S3 存储桶发起的所有请求。保留 S3 存储桶策略和生命周期规则的相关文档。定期审查访问日志、存储桶权限和存储配置，以帮助确保合规性与[安全最佳实践](https://docs.aws.amazon.com/AmazonS3/latest/userguide/security-best-practices.html)。

## 操作说明
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-epics"></a>

### 设置 AWS Control Tower、AFT 和应用程序账户
<a name="set-up-ctowerlong-aft-and-application-accounts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 AFT 设置 AWS Control Tower 环境。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | AWS 管理员 | 
| 为组织启用资源共享。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | AWS 管理员 | 
| 验证或预调配应用程序账户。 | 要为您的使用案例预调配新的应用程序账户，请通过 AFT 创建这些账户。有关更多信息，请参阅 AWS Control Tower 文档中的[向 AFT 开通新账户](https://docs.aws.amazon.com/controltower/latest/userguide/aft-provision-account.html)。 | AWS 管理员 | 

### 为应用程序账户设置配置文件
<a name="set-up-configuration-files-for-application-accounts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将 `Application_account` 文件夹内容复制到 `aft-account-customizations` 存储库中。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 
| 查看并编辑用于设置应用程序账户的输入参数。 | 在此步骤中，您将设置用于在应用程序账户中创建资源的配置文件，包括 CloudWatch 日志组、 CloudWatch 订阅筛选条件、IAM 角色和策略以及 Amazon RDS、Amazon EKS 和 Lambda 函数的配置详细信息。在 `aft-account-customizations` 存储库的 `Application_account` 文件夹中，根据组织的要求配置 `terraform.tfvars` 文件中的输入参数：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 

### 为日志存档账户设置配置文件
<a name="set-up-configuration-files-for-the-log-archive-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将 `Log_archive_account` 文件夹内容复制到 `aft-account-customizations` 存储库中。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 
| 查看并编辑用于设置日志存档账户的输入参数。 | 在此步骤中，您需要设置用于在日志存档账户中创建资源的配置文件，包括 Firehose 传输流、S3 存储桶、SQS 队列以及 IAM 角色和策略。在 `aft-account-customizations` 存储库的 `Log_archive_account` 文件夹中，根据组织的要求配置 `terraform.tfvars` 文件中的输入参数：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 

### 运行 Terraform 命令预调配资源
<a name="run-terraform-commands-to-provision-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 选项 1 - 从 AFT 部署 Terraform 配置文件。 | 在 AFT 中，AFT 管道是在您将包含配置更改的代码推送到 GitHub `aft-account-customizations`存储库后触发的。AFT 会自动检测更改并启动账户自定义流程。对 Terraform（`terraform.tfvars`）文件进行更改后，提交更改并将其推送到 `aft-account-customizations` 存储库：<pre>$ git add *<br />$ git commit -m "update message"<br />$ git push origin main</pre>如果您使用的是其他分支（例如 `dev`），请将 `main` 替换为分支名称。 | DevOps 工程师 | 
| 选项 2 - 手动部署 Terraform 配置文件。 | 如果您不使用 AFT 或想要手动部署解决方案，则可以使用 `Application_account` 和 `Log_archive_account` 文件夹中的以下 Terraform 命令：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 

### 验证资源
<a name="validate-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证订阅筛选条件。 | 要验证订阅筛选条件是否正确地将日志从应用程序账户日志组转发到日志存档账户，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 
| 验证 Firehose 流。 | 要验证日志存档账户中的 Firehose 流是否成功处理应用程序日志，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 
| 验证集中式 S3 存储桶。 | 要验证集中式 S3 存储桶是否正确接收并整理日志，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 
| 验证 SQS 队列。 | 要验证 SQS 队列是否收到新日志文件的通知，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 选项 1 - 从 AFT 停用 Terraform 配置文件。 | 当您删除 Terraform 配置文件并推送更改时，AFT 会自动启动资源删除流程。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 
| 选项 2 – 手动清理 Terraform 资源。 | 如果您不使用 AFT 或想要手动清理资源，则可以使用 `Application_account` 和 `Log_archive_account` 文件夹中的以下 Terraform 命令：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程师 | 

## 问题排查
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
|  CloudWatch 日志目标未创建或处于非活动状态。 | 请验证以下内容：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | 
| 订阅筛选条件失败或停留在待处理状态。 | 请检查以下事项：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | 
| Firehose 传输流未显示任何传入记录。 | 请验证以下内容：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | 

## 相关资源
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-resources"></a>
+ [Terraform 基础设施设置](https://developer.hashicorp.com/terraform/tutorials/aws-get-started)（Terraform 文档）
+ [部署 Terraform 版 Ac AWS Control Tower count Factory (AFT)（文档AWS Control Tower ）](https://docs.aws.amazon.com/controltower/latest/userguide/aft-getting-started.html)
+ [IAM 教程： AWS 账户 使用 IAM 角色委派访问权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html) (IAMdocumentation)

# 使用证书管理器和 “让我们加 end-to-end密” 为 Amazon EKS 上的应用程序设置加密
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt"></a>

*Mahendra Revanasiddappa 和 Vasanth Jeyaraj，Amazon Web Services*

## Summary
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-summary"></a>

实施 end-to-end加密可能很复杂，您需要管理微服务架构中每项资产的证书。尽管您可以使用网络负载均衡器或 Amazon API Gateway 终止亚马逊网络服务 (AWS) 网络边缘的传输层安全 (TLS) 连接，但有些组织需要 end-to-end加密。

此模式使用 Nginx Ingress Controller 作为入口。这是因为当您创建 Kubernetes 入口时，入口资源使用网络负载均衡器。网络负载均衡器不允许上传客户端证书。因此，您无法通过 Kubernetes 入口实现双向 TLS。

这种模式旨在针对需要在其应用程序中所有微服务之间相互认证的组织。双向 TLS 减轻了用户名或密码的维护负担，还可以使用交钥匙安全框架。如果您的组织具有大量连接的设备或必须遵守严格的安全指南，则此模式的方法是兼容的。

这种模式通过对在 Amazon Elastic Kubernetes Service (Amazon EKS) 上运行的应用程序实施 end-to-end加密，有助于提高组织的安全状况。此模式在 [Amazon EKS 存储库中的 GitHub End-to-end 加密](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme)中提供了示例应用程序和代码，以显示微服务如何在 Amazon EKS 上通过 end-to-end加密运行。该模式的方法使用 [cert-manager](https://cert-manager.io/docs/)（Kubernetes 的附加组件），将 [Let 's Encrypt](https://letsencrypt.org/) 作为证书颁发机构 (CA)。Let's Encrypt 是一款经济实惠的证书管理解决方案，它提供有效期为 90 天的免费证书。当在 Amazon EKS 上部署新的微服务时，CERT-MANAGER自动化证书的按需供应和旋转。 

**目标受众**

建议使用 Kubernetes、TLS、Amazon Route 53 和域名系统（DNS）的用户使用此模式。

## 先决条件和限制
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account。
+ 现有 Amazon EKS 集群。
+ 已在 macOS、Linux 或 Windows 上安装和配置的 AWS 命令行界面（AWS CLI）1.7 或更高版本
+ `kubectl` 命令行实用程序，已安装并配置以便访问 Amazon EKS 集群。有关这方面的更多信息，请参阅 Amazon EKS 文档中的[安装 kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)。
+ 用于测试应用程序的现有 DNS 名称。有关更多信息，请参阅 Amazon Route 53 文档中的[使用 Amazon Route 53 注册域名](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/registrar.html)。 
+ 最新 [Helm](https://docs.aws.amazon.com/eks/latest/userguide/helm.html) 版本，安装在您的本地计算机上。有关这方面的更多信息，请参阅 [Amazon EKS 文档和 Helm 存储库中的将 Hel GitHub [m](https://github.com/helm/helm) 与 Amazon EKS 配合使用](https://docs.aws.amazon.com/eks/latest/userguide/helm.html)。 
+ [Amazon EKS 存储库上的 GitHub End-to-end 加密](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme)已克隆到您的本地计算机。 
+ 替换 [Amazon EKS 存储库中克隆 GitHub End-to-end 加密](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme)的`policy.json`和`trustpolicy.json`文件中的以下值：
  + `<account number>` — 替换为您要在其中部署解决方案的账户的 Amazon Web Services account ID。 
  + `<zone id>` — 替换为域名的 Route 53 区域 ID。 
  + `<node_group_role>` – 替换为与 Amazon EKS 节点关联的 AWS Identity and Access Management（IAM） 角色的名称。
  + `<namespace>` — 替换为在其中部署 NGINX Ingress Controller和示例应用程序的 Kubernetes 命名空间。
  + `<application-domain-name>` — 替换为 Route 53 中的 DNS 域名。

**限制**
+ 该模式无法描述如何旋转证书，而仅演示如何在 Amazon EKS 上使用微服务的证书。 

## 架构
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-architecture"></a>

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

![\[使用证书管理器和 Let's Encrypt 为 Amazon EKS 上的应用程序设置加密的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/9aa3ee9e-73db-41f5-a467-b5c47fef496e/images/40692ede-6fb3-474e-8c9e-85c51529e8ad.png)


下图显示了如下工作流：

1. 客户端发送请求将应用程序访问到DNS名称。

1. Route 53 记录为网络负载均衡器的别名记录。

1. 网络负载均衡器将请求转发至配置了 TLS 侦听器的 NGINX Ingress Controller。NGINX Ingress Controller与网络负载均衡器之间的通信遵循 HTTPS 协议。

1. NGINX Ingress Controller 根据客户端对应用程序服务的请求进行基于路径的路由。

1. 应用程序服务将请求转发至应用程序容器组（pod）。该应用程序旨在通过调用秘密使用相同的证书。

1. 容器组（pod）使用证书管理器证书运行示例应用程序。NGINX Ingress Controller 和容器组（pod）之间的通信使用 HTTPS。


| 
| 
| 注意：证书管理器在自己的命名空间运行。它使用 Kubernetes 集群角色来提供特定名称空间中的秘密证书。您可以将这些名称空间附加到应用程序容器组（pod）和 Nginx Ingress Controller。 | 
| --- |

## 工具
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-tools"></a>

**Amazon Web Services**
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) 是一项托管服务，可让您在 AWS 上轻松运行 Kubernetes，而无需安装、操作或维护您自己的 Kubernetes 控制面板或节点。
+ [弹性负载均衡](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html)会自动将您的传入流量分配到多个目标、容器和 IP 地址。
+ [AWS Identity and Access Management (AWS IAM) ](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)通过控制验证和授权使用您 AWS 资源的用户，帮助您安全地管理对您 AWS 资源的访问。
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一种可用性高、可扩展性强的 DNS Web 服务。

**其他工具**
+ [cert-manager](https://cert-manager.io/docs/installation/supported-releases/) 是 Kubernetes 的附加组件，用于请求证书、将证书分发到 Kubernetes 容器和自动续订证书。
+ [NGINX Ingress Controller](https://kubernetes.github.io/ingress-nginx/) 是一款适用于 Kubernetes 和容器化环境中的云原生应用程序的流量管理解决方案。

## 操作说明
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-epics"></a>

### 使用 Route 53 创建与配置公共托管区域
<a name="create-and-configure-a-public-hosted-zone-with-route-53"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 Route 53 中创建一个公有托管区。 | 登录 AWS 管理控制台，打开 Amazon Route 53 控制台，选择**托管区域**，然后选择**创建托管区域**。创建公共托管区域，并记录区域 ID。有关更多信息，请参阅 Amazon Route 53 文档中的[创建公有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingHostedZone.html)。ACME DNS01 使用 DNS 提供程序发布质疑，要求证书管理器颁发证书。这项挑战要求您通过将特定值放在该域名下的TXT记录中来证明您控制域名的 DNS。在 Let's Encrypt 向您的 ACME 客户端提供令牌后，您的客户端会创建一条从该令牌和您的账户密钥派生的 TXT 记录，并将该记录置于 `_acme-challenge.<YOURDOMAIN>`。然后 Let's Encrypt 在 DNS 中查询此记录。如找到匹配项，则可以继续颁发证书。 | AWS DevOps | 

### 配置 IAM 角色，以允许证书管理员访问公共托管区域
<a name="configure-an-iam-role-to-allow-cert-manager-to-access-the-public-hosted-zone"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为证书管理器创建 IAM policy。 | 要求 IAM policy 为证书管理器提供许可，以验证您拥有53号公路域。A [mazon EKS 存储库中的克隆 GitHub End-to-end 加密`1-IAMRole`](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme)目录中提供了`policy.json`示例 IAM 策略。在 AWS CLI 中输入以下命令以创建 IAM policy。<pre>aws iam create-policy \<br />  --policy-name PolicyForCertManager \<br />  --policy-document file://policy.json</pre> | AWS DevOps | 
| 为证书管理器创建 IAM 角色。 | 创建 IAM policy后，必须创建 IAM 角色。`1-IAMRole` 目录中提供了 `trustpolicy.json` 示例 IAM 角色。在 AWS CLI 中输入以下命令以创建 IAM 角色。<pre>aws iam create-role \<br />  --role-name RoleForCertManager \<br />  --assume-role-policy-document file://trustpolicy.json</pre> | AWS DevOps | 
| 将 策略附加到该角色。 | 在 AWS CLI 中输入以下命令以将 IAM policy 附加到 IAM 角色。将 `AWS_ACCOUNT_ID` 替换为您的 Amazon Web Services account 的 ID。<pre>aws iam attach-role-policy \<br />  --policy-arn arn:aws:iam::AWS_ACCOUNT_ID:policy/PolicyForCertManager \<br />  --role-name RoleForCertManager</pre> | AWS DevOps | 

### 在Amazon EKS 中设置 NGINX Ingress Controller
<a name="set-up-the-nginx-ingress-controller-in-amazon-eks"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 NGINX Ingress Controller。 | 使用 Helm 安装最新版`nginx-ingress`。在部署 `nginx-ingress` 配置之前，您可以根据自己的要求对其进行修改。此模式使用带注释的、面向内部的网络负载均衡器，该网络负载均衡器可在 `5-Nginx-Ingress-Controller` 目录中找到。 通过从 `5-Nginx-Ingress-Controller` 目录中运行以下 Helm 命令来安装 NGINX Ingress Controller。`helm install test-nginx nginx-stable/nginx-ingress  -f  5-Nginx-Ingress-Controller/values_internal_nlb.yaml` | AWS DevOps | 
| 验证 NGINX Ingress Controller 是否已安装。 | 输入 `helm list`命令。输出应显示 NGINX Ingress Controller 已安装。 | AWS DevOps | 
| 创建 Route 53 A 记录。 | 创建指向 NGINX Ingress Controller 的网络负载均衡器的别名记录。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt.html) | AWS DevOps | 

### 在 VirtualServer 亚马逊 EKS 上设置 NGINX
<a name="set-up-nginx-virtualserver-on-amazon-eks"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 NGINX VirtualServer。 | NGINX VirtualServer 资源是一种负载平衡配置，可以替代入口资源。创建 NGINX VirtualServer 资源的配置可在目录中的`nginx_virtualserver.yaml`文件中找到。`6-Nginx-Virtual-Server`在中输入以下命令`kubectl`以创建 NGINX 资源 VirtualServer 。`kubectl apply -f  nginx_virtualserver.yaml`请务必更新 `nginx_virtualserver.yaml` 文件中的应用程序域名、证书密钥和应用程序服务名称。 | AWS DevOps | 
| 验证是否已创建 NGINX VirtualServer 。 | 在中输入以下命令`kubectl`以验证 NGINX VirtualServer 资源是否已成功创建。`kubectl get virtualserver`请确认 `Host` 列与您的应用程序的域名相匹配。 | AWS DevOps | 
| 在启用 TLS 的情况下部署 NGINX Web 服务器。 | 此模式使用启用了 TLS 的 NGINX Web 服务器作为测试 end-to-end加密的应用程序。部署测试应用程序所需配置文件可在 `demo-webserver` 目录中找到。 在 `kubectl` 中输入以下命令以部署测试应用程序。`kubectl apply -f nginx-tls-ap.yaml` | AWS DevOps | 
| 验证测试应用程序资源是否已创建。 | 在 `kubectl` 中输入以下命令，以验证是否为测试应用程序创建了所需资源：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt.html) | AWS DevOps | 
| 验证应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt.html) | AWS DevOps | 

## 相关资源
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-resources"></a>

**AWS 资源**
+ [使用 Amazon Route 53 控制台创建记录](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html)（Amazon Route 53 文档）
+ [在 Amazon EKS 上使用带有 NGINX 入口控制器的网络负载均衡器](https://aws.amazon.com/blogs/opensource/network-load-balancer-nginx-ingress-controller-eks/)（AWS Blog 文章）

**其他资源**
+ [Route 53](https://cert-manager.io/docs/configuration/acme/dns01/route53/)（证书管理器文档）
+ [配置 DNS01 Challenge 提供程序](https://cert-manager.io/docs/configuration/acme/dns01/)（证书管理器文档）
+ [Let’s encrypt DNS 问题](https://letsencrypt.org/docs/challenge-types/#dns-01-challenge) (Let’s Encrypt 文档)

# 使用 Flux 简化 Amazon EKS 多租户应用程序部署
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux"></a>

*Nadeem Rahaman、Aditya Ambati、Aniket Dekate 和 Shrikant Patil，Amazon Web Services*

## Summary
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-summary"></a>

许多提供产品和服务的公司隶属于受数据监管的行业，这类行业要求在其内部业务职能之间建立数据壁垒。此模式描述了如何使用 Amazon Elastic Kubernetes Service（Amazon EKS）中的多租户功能来构建数据平台，在共享单个 Amazon EKS 集群的租户或用户之间实现逻辑隔离与物理隔离。此模式通过以下方法实现隔离：
+ Kubernetes 命名空间隔离
+ 基于角色的访问控制 (RBAC)
+ 网络策略
+ 资源配额
+ AWS Identity and Access Management 服务账户的 (IAM) 角色 (IRSA)

此外，此解决方案使用 Flux，确保在部署应用程序时保持租户配置不可变。您可通过在配置中指定包含 Flux `kustomization.yaml` 文件的租户存储库来部署租户应用程序。

此模式实现以下内容：
+ 通过手动部署 Terraform 脚本创建的 AWS CodeCommit 存储库、 AWS CodeBuild 项目和 AWS CodePipeline 管道。
+ 托管租户所需的网络和计算组件。它们是 CodeBuild 通过 CodePipeline 和使用 Terraform 创建的。
+ 通过 Helm 图表配置的租户命名空间、网络策略和资源配额。
+ 使用 Flux 部署的、分属不同租户的应用程序。

建议您根据自身的独特需求和安全考量，仔细规划并构建适合自己的多租户架构。此模式为您的实现提供了起点。

## 先决条件和限制
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ AWS Command Line Interface [(AWS CLI) 版本 2.11.4 或更高版本，[已安装并配置](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](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) 版本 0.12 或更高版本
+ [Terraform AWS Provider](https://registry.terraform.io/providers/hashicorp/aws/latest) 版本 3.0.0 或更高版本
+ [Kubernetes Provider](https://registry.terraform.io/providers/hashicorp/kubernetes/latest/docs) 版本 2.10 或更高版本
+ [Helm Provider](https://registry.terraform.io/providers/hashicorp/helm/latest/docs) 版本 2.8.0 或更高版本
+ [Kubectl Provider](https://registry.terraform.io/providers/gavinbunney/kubectl/latest/docs) 版本 1.14 或更高版本

**限制**
+ 对 **Terraform 手动部署的依赖：**工作流程的初始设置（包括创建 CodeCommit 存储库、 CodeBuild 项目和 CodePipeline 管道）依赖于手动 Terraform 部署。这在自动化和可扩展性方面存在潜在的限制，因为需要手动干预才能进行基础设施更改。
+ **CodeCommit 存储库依赖关系：**工作流程依赖于 CodeCommit 存储库作为源代码管理解决方案，并与之紧密结合 AWS 服务。

## 架构
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-architecture"></a>

**目标架构**

此模式通过部署三个模块来为数据平台构建管道、网络和计算基础设施，如下图所示。

*管道架构：*

![\[适用于 Amazon EKS 多租户架构的管道基础设施\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/97b700a7-74b6-4f9d-b53a-76de42409a8e/images/76a4a23d-4275-427a-ae36-51c9a3803128.png)


*网络架构：*

![\[适用于 Amazon EKS 多租户架构的网络基础设施\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/97b700a7-74b6-4f9d-b53a-76de42409a8e/images/e542249a-19a3-4c99-b6f5-fdf80fee4edf.png)


*计算架构：*

![\[适用于 Amazon EKS 多租户架构的计算基础设施\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/97b700a7-74b6-4f9d-b53a-76de42409a8e/images/91bd1ca8-17f0-433c-8600-4c8e6c474e31.png)


## 工具
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-tools"></a>

**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) 可帮助您快速对软件发布过程的不同阶段进行建模和配置，并自动执行持续发布软件变更所需步骤。
+ [亚马逊 Elastic Kubernetes Service（亚马逊](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) EKS）可帮助你在上面运行 AWS Kubernetes，而无需安装或维护自己的 Kubernetes 控制平面或节点。
+ [AWS Transit Gateway](https://docs.aws.amazon.com/vpc/latest/tgw/what-is-transit-gateway.html)是连接虚拟私有云 (VPCs) 和本地网络的中央集线器。
+ [Amazon Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。该虚拟网络类似于您在数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。

**其他工具**
+ [Cilium 网络策略](https://cilium.io/use-cases/network-policy/#:~:text=Cilium%20implements%20Kubernetes%20Network%20Policies,%2C%20Kafka%2C%20gRPC%2C%20etc.)支持 Kubernetes L3 和 L4 网络策略。它们可通过 L7 策略进行扩展，为 HTTP、Kafka 和 gRPC 以及其他类似协议提供 API 级安全防护。
+ [Flux](https://fluxcd.io/) 是一款基于 Git 的持续交付（CD）工具，可自动完成 Kubernetes 上的应用程序部署。
+ [Helm](https://helm.sh/docs/) 是 Kubernetes 的开源软件包管理器，可帮助您在 Kubernetes 集群上安装和管理应用程序。
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。

**代码存储库**

此模式的代码可在 GitHub [EKS 多租户 Terraform](https://github.com/aws-samples/aws-eks-multitenancy-deployment) 解决方案存储库中找到。

## 最佳实践
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-best-practices"></a>

有关此实施方案的使用指南和最佳实践，请参阅以下内容：
+ [Amazon EKS 多租户最佳实践](https://aws.github.io/aws-eks-best-practices/security/docs/multitenancy/)
+ [Flux 文档](https://fluxcd.io/flux/get-started/)

## 操作说明
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-epics"></a>

### 为 Terraform 构建、测试和部署阶段创建管道
<a name="create-pipelines-for-terraform-build-test-and-deploy-stages"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆项目存储库。 | 在终端 GitHub [窗口中运行以下命令，克隆 EKS 多租户 Terraform 解决方案](https://github.com/aws-samples/aws-eks-multitenancy-deployment)存储库：<pre>git clone https://github.com/aws-samples/aws-eks-multitenancy-deployment.git</pre> | AWS DevOps | 
| 引导 Terraform S3 存储桶和 Amazon DynamoDB。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | AWS DevOps | 
| 更新 `run.sh` 和 `locals.tf` 文件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | AWS DevOps | 
| 部署管道模块。 | 要创建管道资源，请手动运行以下 Terraform 命令。目前尚无自动运行这些命令的编排。<pre>./run.sh -m pipeline -e demo -r <AWS_REGION> -t init<br />./run.sh -m pipeline -e demo -r <AWS_REGION> -t plan<br />./run.sh -m pipeline -e demo -r <AWS_REGION> -t apply</pre> | AWS DevOps | 

### 创建网络基础设施
<a name="create-the-network-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动管道。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html)第一次运行后，每当你向 CodeCommit 存储库主分支提交更改时，管道就会自动启动。该管道包括以下[阶段](https://docs.aws.amazon.com/codepipeline/latest/userguide/concepts.html#concepts-stages)：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | AWS DevOps | 
| 验证通过网络模块创建的资源。 | 确认以下 AWS 资源是在成功部署管道后创建的：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | AWS DevOps | 

### 创建计算基础设施
<a name="create-the-compute-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更新`locals.tf`以启用 CodeBuild 项目对 VPC 的访问权限。 | 要为 Amazon EKS 私有集群部署插件，必须将该 CodeBuild 项目连接到 Amazon EKS VPC。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | AWS DevOps | 
| 更新 `buildspec` 文件以构建计算模块。 | 在 `templates` 文件夹中，在所有 `buildspec` YAML 文件中，将 `TF_MODULE_TO_BUILD` 变量的值从 `network` 设置为 `compute`：<pre>TF_MODULE_TO_BUILD: "compute"</pre> | AWS DevOps | 
| 更新租户管理 Helm 图表的 `values` 文件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | AWS DevOps | 
| 验证计算资源。 | 在前面的步骤中更新文件后，将自动 CodePipeline 启动。确认它已为计算基础设施创建了以下 AWS 资源：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | AWS DevOps | 

### 检查租户管理及其他资源
<a name="check-tenant-management-and-other-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证 Kubernetes 中的租户管理资源。 | 运行以下命令，检查借助 Helm 是否成功创建了租户管理资源。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | AWS DevOps | 
| 验证租户应用程序部署。 | 运行以下命令，验证租户应用程序是否已部署。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) |  | 

## 问题排查
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 您会遇到类似于以下内容的错误消息：`Failed to checkout and determine revision: unable to clone unknown error: You have successfully authenticated over SSH. You can use Git to interact with AWS CodeCommit.` | 请按照以下步骤解决问题：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | 

## 相关资源
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-resources"></a>
+ [适用于 Terraform 的 Amazon EKS 蓝图](https://github.com/aws-ia/terraform-aws-eks-blueprints)
+ [Amazon EKS 最佳实践指南，多租户部分](https://aws.github.io/aws-eks-best-practices/security/docs/multitenancy/)
+ [Flux 网站](https://fluxcd.io/)
+ [Helm 网站](https://helm.sh/)

## 附加信息
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-additional"></a>

以下是部署租户应用程序的存储库结构示例：

```
applications
sample_tenant_app
├── README.md
├── base
│   ├── configmap.yaml
│   ├── deployment.yaml
│   ├── ingress.yaml
│   ├── kustomization.yaml
│   └── service.yaml
└── overlays
    ├── tenant-1
    │   ├── configmap.yaml
    │   ├── deployment.yaml
    │   └── kustomization.yaml
    └── tenant-2
        ├── configmap.yaml
        └── kustomization.yaml
```

# 使用自动化工作流简化 Amazon Lex 机器人的开发和部署
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow"></a>

*Balaji Panneerselvam、Attila Dancso、Pavan Dusanapudi、Anand Jumnani 和 James O'Hara，Amazon Web Services*

## Summary
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-summary"></a>

当需要管理多个功能、开发人员及环境时，开发和部署 Amazon Lex 对话式机器人可能会面临挑战。使用基础设施即代码（IaC）原则的自动化工作流程有助于简化这一流程。此模式可通过以下方式提升 Amazon Lex 开发人员的工作效率，并实现高效的机器人生命周期管理：
+ **支持多项功能的并行开发** - 借助自动化工作流，开发人员可在独立分支中并行开发不同的功能。后续可合并变更并部署，且不会阻碍其他工作的推进。
+ **使用 Amazon Lex 控制台 UI** - 开发人员可使用用户友好的 Amazon Lex 控制台来构建和测试机器人，随后通过基础设施代码定义机器人以完成部署。
+ **跨环境推广机器人** - 该工作流可自动将机器人版本从开发、测试等较低级别的环境推广至生产环境。这种方法降低了手动推广的风险和开销。
+ **维护版本控制** - 在 Git 中管理机器人定义，而不仅仅是通过 Amazon Lex 服务，可以为您提供版本控制和审计跟踪记录。与仅使用 AWS 管理控制台 或修改存储在中的机器人不同，更改会跟踪 APIs 到各个开发者 AWS。

通过自动执行 Amazon Lex 机器人的发布流程，团队可以更快地交付功能，同时降低风险和工作量。机器人仍处于版本控制之下，而非孤立存在于 Amazon Lex 控制台中。

## 先决条件和限制
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-prereqs"></a>

**先决条件**
+ 该工作流程涉及多个 AWS 账户 不同的环境（开发、生产和 DevOps），这需要账户管理和跨账户访问配置。
+ Python 3.9 可在您的部署环境或管道中使用。
+ 已在本地工作站上[安装](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)并配置 Git 以进行源代码控制。
+ AWS Command Line Interface (AWS CLI) [已安装](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)并配置为使用命令行或 Python 进行身份验证。

**限制**
+ **存储库访问权限** - 该工作流假设持续集成和持续交付（CI/CD）管道具有向源代码存储库提交更改所需的权限。
+ **初始机器人版本** — 该工具要求使用 AWS CloudFormation 模板部署机器人的初始版本。在自动化工作流接管前，您必须创建机器人的第一个版本迭代并将其提交到存储库。
+ **合并冲突** – 尽管该工作流旨在支持并行开发，但在整合来自不同分支的更改时，仍有可能出现合并冲突。可能需要手动干预来解决机器人配置中的冲突。

**产品版本**
+ [Python 3.9](https://www.python.org/downloads/) 或更高版本
+ [AWS CDK v2 2.12](https://docs.aws.amazon.com/cdk/api/versions.html) 4.0 或更高版本
+ [适用于 Python (Boto3) 的 AWS SDK](https://docs.aws.amazon.com/pythonsdk/)1.28 或更高版本

## 架构
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-architecture"></a>

下图展示了该解决方案的高层级架构及关键组件。

![\[自动开发和部署 Amazon Lex 机器人的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/3c7f9d16-9708-43c4-afa6-9d804d6b9dad/images/cdc73e82-a777-4e88-8bf8-a73c9bacb47f.png)


关键组件包括：
+ **Lex 机器人存储库** – 用于存储 Amazon Lex 机器人的 IaC 定义的 Git 存储库。
+ **DevOps**— AWS 账户 专门为开发和部署过程提供 CI/CD 管道和相关资源。
+ Pipelin@@ **es** — 自动执行机器人开发和部署生命周期各个阶段的 AWS CodePipeline 实例，例如创建新机器人、导出机器人定义、导入机器人定义和删除机器人。
+ **工单机器人和主机器人** – Amazon Lex 机器人资源，其中，工单机器人是由各个团队或开发人员开发的、针对特定功能的机器人；主机器人则是整合了所有功能的基准机器人。

该架构图展示了以下工作流：

1. **基准主机器人** – 该工作流的起点是在开发（Dev）环境中对主机器人进行基准测试。主机器人是后续开发和功能新增的基础。

1. **创建工单机器人** – 当需要开发新功能或进行变更时，将创建一个工单机器人。工单机器人本质上是主机器人的副本或分支，开发人员可基于它开展工作，且不会影响主机器人版本。

1. **导出工单机器人** - 工单机器人开发完成后，从 Amazon Lex 服务中导出。随后，包含该工单机器人的分支会基于主分支进行变基操作。此步骤可确保纳入工单机器人开发期间对主机器人所做的任何更改，从而减少潜在的冲突。

1. **导入变基后的工单机器人并验证** – 将变基后的工单机器人重新导入开发环境，并进行验证，确保其能与主分支的最新变更协同工作且功能正常。如果验证成功，则会创建拉取请求（PR），将工单机器人更改合并到主分支中。

1. **删除工单机器人** – 将更改成功合并到主分支后，便不再需要工单机器人了。此时可删除工单机器人，以保持环境整洁且易于管理。

1. **将主机器人部署到开发环境中并测试** – 将更新后的主机器人（现在包括新功能或更改）部署到开发环境中。在此环境中对其进行全面测试，以确保所有功能均能按预期运行。

1. **将主机器人部署到生产环境中** – 在开发环境中完成测试并成功后，将主机器人部署到生产环境中。此步骤是该工作流的最终阶段，新功能将在此阶段对最终用户开放使用。

**自动化和扩展**

自动化工作流支持开发人员在独立分支中并行开发不同的功能。这为并行开发提供了便利，助力团队实现高效协作并更快地交付功能。由于各分支相互隔离，因此可在不阻碍或干扰其他进行中工作的前提下完成更改的合并与部署。

该工作流可自动完成机器人版本在不同环境（例如开发环境、测试环境和生产环境）中的部署与推广。

将机器人定义存储在 Git 等版本控制系统中，可提供完整的审计跟踪记录并实现高效协作。更改可追溯至具体开发人员，确保整个开发生命周期的透明度和问责制。此外，这种方法还便于开展代码审查，帮助团队在部署到生产环境前发现并解决问题。

通过使用 AWS CodePipeline 和其他 AWS 服务，自动化工作流程可以扩展以适应不断增加的工作负载和团队规模。

## 工具
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-tools"></a>

**AWS 服务**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)是一个开源软件开发框架，用于通过使用熟悉的编程语言在代码中定义 AWS 云 基础架构，并通过它进行配置 CloudFormation。此模式中的示例实现使用 Python。
+ [AWS CDK 命令行界面 (AWS CDK CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)- AWS CDK 工具包是与您的 AWS CDK 应用程序交互的主要工具。它执行您的应用程序，查询您定义的应用程序模型，并生成和部署 CDK 生成的 CloudFormation 模板。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在和的整个 AWS 账户 生命周期中对其进行管理 AWS 区域。此模式 CloudFormation 用于使用基础设施即代码部署 Amazon Lex 机器人配置和相关资源。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 是一项完全托管式构建服务，可编译源代码、运行单元测试和生成部署就绪的构件。此模式 CodeBuild 用于构建和打包部署工件。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可帮助您快速对软件发布过程的不同阶段进行建模和配置，并自动执行持续发布软件变更所需步骤。这种模式 CodePipeline 用于协调持续交付管道。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您AWS 服务 通过命令行 shell 中的命令进行交互。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [Amazon Lex V2](https://docs.aws.amazon.com/lexv2/latest/dg/what-is.html) AWS 服务 用于为使用语音和文本的应用程序构建对话界面（机器人）。
+ [适用于 Python (Boto3) 的 AWS SDK](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html)是一个软件开发套件，可帮助您将 Python 应用程序、库或脚本与集成 AWS 服务。

**其他工具**
+ [Git](https://git-scm.com/docs) 是开源分布式版本控制系统。

**代码存储库**

此模式的代码可在-ama GitHub [management-framework-sample-forzon-](https://github.com/aws-samples/management-framework-sample-for-amazon-lex) lex 存储库中找到。代码库包含以下文件夹和文件：
+ `prerequisite`文件夹-包含用于设置所需资源和环境的 CloudFormation 堆栈定义（使用 AWS CDK）。
+ `prerequisite/lexmgmtworkflow` 文件夹 – Lex 管理工作流项目的主目录，包含堆栈定义和 Python 代码。
+ `prerequisite/tests` – 包含单元测试代码。
+ `src` 文件夹 - 源代码目录，包含 Amazon Lex 机器人管理封装程序和实用工具。
+ `src/dialogue_lambda` – 对话钩子 Lambda 函数的源代码目录，该函数在用户与 Amazon Lex 机器人对话期间拦截并处理用户输入。

## 最佳实践
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-best-practices"></a>
+ **关注点分离**
  + 在开发环境和生产环境之间保持明确的 DevOps责任分工。
  +  AWS 账户 为每个环境单独使用以强制适当的隔离和安全边界。
  + 使用跨账户角色和最低权限访问原则，确保环境之间的访问受控。
+ **基础设施即代码**
  + 定期审查并更新基础设施代码，确保其符合最佳实践并适配不断变化的需求。
  + 为源代码存储库制定明确的分支与合并策略
+ **测试和验证**
  + 在管道的各个阶段实施自动化测试，以便在开发周期的早期发现问题。
  + 在将机器人推广到级别更高的环境前，使用 Amazon Lex 控制台或自动化测试框架来验证机器人的配置和功能。
  + 考虑为生产环境或关键环境的部署设置手动审批环节。
+ **监控和记录**
  + 为管道、部署和机器人交互设置监控和日志记录机制。
  + 监控管道事件、部署状态和机器人性能指标，以便及时发现并解决问题。
  + 使用 AWS 服务（例如 Amazon CloudWatch AWS CloudTrail、和） AWS X-Ray 进行集中记录和监控。
  + 定期审查并分析自动化工作流的性能、效率及有效性。
+ **安全与合规**
  + 实施安全编码实践，并遵循 Amazon Lex 机器人开发和部署 AWS 的安全最佳实践。
  + 定期审查并更新 IAM 角色、策略及权限，使其符合最低权限原则。
  + 考虑在管道中集成安全扫描与合规性检查。

## 操作说明
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-epics"></a>

### 为 Amazon Lex 机器人管理设置 IaC
<a name="set-up-iac-for-lex2-bot-management"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置本地 CDK 环境 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.html) | AWS DevOps | 
| 在 `devops` 环境中创建跨账户角色。 | 该`devops`账户负责托管和管理 CI/CD 管道。要使 CI/CD 管道能够与`dev`和`prod`环境交互，请运行以下命令在账户中创建跨账户角色。`devops`<pre>cdk bootstrap --profile=devops<br /><br />cdk deploy LexMgmtDevopsRoleStack -c dev-account-id=2222222222222 -c prod-account-id=333333333333 --profile=devops</pre> | AWS DevOps | 
| 在 `dev` 环境中创建跨账户角色。 | 在 `dev` 账户中创建具有必要权限的 IAM 角色，以允许`devops` 账户承担此角色。 CI/CD 管道使用此角色在`dev`账户中执行操作，例如部署和管理 Amazon Lex 机器人资源。要创建 IAM 角色，请运行以下命令：<pre>cdk bootstrap --profile=dev<br /><br />cdk deploy LexMgmtCrossaccountRoleStack -c devops-account-id=1111111111111 --profile=dev</pre> | AWS DevOps | 
| 在 `prod` 环境中创建跨账户角色。 | 在 `prod` 账户中创建具有必要权限的 IAM 角色，以允许`devops` 账户承担此角色。 CI/CD 管道使用此角色在`prod`账户中执行操作，例如部署和管理 Amazon Lex 机器人资源。<pre>cdk bootstrap --profile=prod<br /><br />cdk deploy LexMgmtCrossaccountRoleStack -c devops-account-id=1111111111111 --profile=prod</pre> | AWS DevOps | 
| 在 `devops` 环境中创建管道。 | 要管理 Amazon Lex 机器人的开发工作流，请运行以下命令在 `devops` 环境中设置管道。<pre>cdk deploy LexMgmtWorkflowStack -c devops-account-id=1111111111111 -c dev-account-id=2222222222222 -c prod-account-id=333333333333 --profile=devops</pre> | AWS DevOps | 

### 为主机器人建立基准
<a name="establish-the-baseline-for-the-main-bot"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 定义主机器人的初始版本。 | 要定义主机器人的初始版本，请[触发](https://docs.aws.amazon.com/codepipeline/latest/userguide/concepts.html#concepts-triggers) `BaselineBotPipeline` 管道。该管道部署 CloudFormation 模板中定义的基本机器人定义，将主机器人定义导出为.json 文件。并将主机器人代码存储在版本控制系统中。 | AWS DevOps | 

### 实施功能开发工作流
<a name="implement-the-feature-development-workflow"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建工单机器人以开发并测试功能。 | `TicketBot` 是从功能分支中的现有主机器人定义导入的新机器人实例。这种方法可确保新机器人具有主机器人当前所有的功能和配置。要定义工单机器人的初始版本，请触发 `CreateTicketBotPipeline` 管道。该管道会在版本控制系统中创建新的功能分支，并基于主机器人创建新的工单机器人实例。 | Lex 机器人开发人员 | 
| 开发并测试工单机器人的功能。 | 要开发和测试该功能，请登录 AWS 管理控制台 并打开 Amazon Lex 控制台，网址为[https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/)。有关更多信息，请参阅 Amazon Lex 文档中的[使用控制台测试机器人](https://docs.aws.amazon.com/lexv2/latest/dg/test-bot.html)。通过 `TicketBot` 实例，您现在可以添加、修改或扩展机器人的功能以实现新特性。例如，您可以创建或修改意图、话语、槽位和对话流。有关更多信息，请参阅 Amazon Lex 文档中的[添加意图](https://docs.aws.amazon.com/lexv2/latest/dg/add-intents.html)。 | Lex 机器人开发人员 | 
| 导出工单机器人定义。 | 导出的机器人定义本质上是以 JSON 格式表示的机器人的配置和功能。要导出工单机器人定义，请触发 `ExportTicketBotPipeline` 管道。该管道将工单机器人定义导出为 .json 文件，并将工单机器人代码存储在版本控制系统的功能分支中。 | Lex 机器人开发人员 | 
| 基于最新主分支对功能分支执行变基操作。 | 在开发新功能的过程中，主分支可能会收到来自不同开发人员或团队的其他更改。要将这些更改整合到功能分支中，请执行 Git `rebase` 操作。此操作本质上是将功能分支中的提交记录“重放”到主分支的最新提交记录之上，确保功能分支包含所有最新更改。 | Lex 机器人开发人员 | 
| 导入并验证变基后的工单机器人。 | 对功能分支执行变基操作后，必须将其导入工单机器人实例。此次导入会用变基分支的最新更改来更新现有工单机器人。要导入变基后的工单机器人，请触发 `ImportTicketBotPipeline` 管道。该管道会将版本控制系统功能分支中的工单机器人定义 .json 文件导入到 `TicketBot` 实例中。 | Lex 机器人开发人员 | 
| 验证变基后的机器人定义。 | 导入变基后的机器人定义后，验证其功能至关重要。您需要确保新功能按预期运行，且不会与现有功能产生冲突。此验证通常包括使用各种输入场景测试机器人、检查响应以及验证机器人的行为是否符合预期。您可以通过以下任一方式执行验证：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.html) | Lex 机器人开发人员 | 
| 将功能分支合并到主分支中。 | 在独立的 `TicketBot` 实例中完成新功能的开发与测试后，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.html) | Lex 机器人开发人员、存储库管理员 | 
| 删除功能分支和工单机器人。 | 当功能分支成功合并到主分支后，从源代码存储库中删除该功能分支和工单机器人。要删除功能分支和工单机器人，请触发 `DeleteTicketBotPipeline` 管道。该管道会删除开发过程中创建的临时机器人资源（例如，工单机器人）。此操作有助于保持存储库的整洁，避免与未来的功能分支产生混淆或冲突。 | Lex 机器人开发人员 | 

### 维护主机器人
<a name="maintain-the-main-bot"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将最新的主机器人定义导入到 `dev` 环境中。 | 要将主分支中最新的主机器人定义导入到 `dev` 环境中，请触发 `DeployBotDevPipeline` 管道。该管道还会在审批通过后创建一个 Git 标签。 | AWS DevOps | 
| 将最新的主机器人定义导入到 `prod` 环境中。 | 要将主分支中最新的机器人定义导入到 `prod` 环境中，请提供上一个任务中的标签引用作为参数并触发 `DeployBotProdPipeline` 管道。该管道将最新的机器人定义从特定标签导入到 `prod` 环境中。 | AWS DevOps | 

## 问题排查
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 当您将 Amazon Lex 机器人部署到其他账户时 AWS 账户，工具服务必须具有访问这些账户中的资源的必要权限。 | 要授予跨账户访问权限，请使用 IAM 角色和策略。在目标账户中创建 IAM 角色，并将策略附加到授予所需权限的角色。然后，从部署 Amazon Lex 机器人的账户承担这些角色。有关更多信息，请参阅 Amazon Lex 文档中的[导入所需的 IAM 权限](https://docs.aws.amazon.com/lexv2/latest/dg/import.html#import-permissions)以及[在 Lex V2 中导出机器人所需的 IAM 权限](https://docs.aws.amazon.com/lexv2/latest/dg/export.html#export-permissions)。 | 

## 相关资源
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-resources"></a>
+ [在 Amazon Lex V2 中导入机器人](https://docs.aws.amazon.com/lexv2/latest/dg/import.html)
+ [在中启动管道 CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-about-starting.html)
+ [使用 Amazon Lex V2 机器人](https://docs.aws.amazon.com/lexv2/latest/dg/building-bots.html)

# 使用 AWS Fargate WaitCondition 挂钩构造协调资源依赖关系和任务执行
<a name="use-the-aws-fargate-waitcondition-hook-construct"></a>

*Stan Fan，Amazon Web Services*

## Summary
<a name="use-the-aws-fargate-waitcondition-hook-construct-summary"></a>

此模式描述了 WaitCondition hook (`waitcondition-hook-for-aws-fargate-task`) npm 包，它是一种云原生解决方案，专为在亚马逊弹性容器服务 (Amazon ECS) 集群[AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html)中编排任务而设计。

 WaitCondition 钩子是专门为与集成而量身定制的 AWS Cloud Development Kit (AWS CDK) 构造 AWS CloudFormation。该 WaitCondition 挂钩提供以下关键功能：
+ 充当等待条件机制，在指定的 Fargate 任务完成之前暂停 CloudFormation 堆栈执行，这有助于有序部署和资源配置。
+ 支持 TypeScript 和 Python，使其成为 AWS CDK 项目的理想之选。
+ 能够让开发人员和架构师为 AWS上的容器化应用程序协调任务完成和资源管理，从而编排部署。
+ 允许在 CloudFormation 生命周期中嵌入一个或多个容器的情况下运行 Fargate 任务。并且可以处理任务失败并在任务失败后回滚 CloudFormation 堆栈。
+ 能够灵活地添加资源与 Fargate 任务执行结果之间的依赖关系，从而支持自定义任务或调用其他端点。例如，您可以暂停 CloudFormation 堆栈并等待数据库迁移（由 Fargate 任务完成），然后配置其他可能取决于数据库迁移成功与否的资源。

## 先决条件和限制
<a name="use-the-aws-fargate-waitcondition-hook-construct-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ AWS Cloud Development Kit (AWS CDK) 命令行界面 (CLI) 安装在本地工作站上。有关更多信息，请参阅 AWS CDK 文档中的 [AWS CDK CLI 参考](https://docs.aws.amazon.com/cdk/v2/guide/cli.html)。
+ 节点包管理器 (npm)，安装在本地工作站上并配置为[AWS CDK 中。 TypeScript](https://docs.aws.amazon.com/cdk/v2/guide/work-with-cdk-typescript.html)有关详情，请参阅 npm 文档中的[下载和安装 Node.js 和 npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)。
+ 已在本地工作站上安装 Yarn。有关详情，请参阅 Yarn 文档中的[安装](https://yarnpkg.com/getting-started/install)。

**限制**
+ 此解决方案已部署到单个 AWS 账户。
+ 容器的预期返回代码是 `0`，表示成功。任何其他返回代码都表示失败， CloudFormation 堆栈将回滚。
+ 有些 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="use-the-aws-fargate-waitcondition-hook-construct-architecture"></a>

下图显示了此构造的架构。

![\[-f waitcondition-hook-for-aws argate-task 结构的 AWS Step Functions 工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e58680e3-f89f-422f-b0e1-e85605ae8bf9/images/598020df-908c-4486-9844-c05af759c18a.png)


下图显示了 `waitcondition-hook-for-aws-fargate-task` 的工作流：

1. `WaitCondition`并`WaitConditionHandler`被设置为监听来自 AWS Lambda 函数的响应。

1. 根据任务的结果，完成 Fargate 任务之后将会触发 `CallbackFunction` 或 `ErrorHandlerFunction`。

1. Lambda 函数将向 `WaitConditionHandler` 发送一个“成功”或“失败”信号。

1. 如果 Fargate 任务的执行结果成功，`WaitConditionHandler` 会继续预调配资源；如果任务失败，将回滚堆栈。

下图显示了一个用于执行数据库迁移的工作流的示例。

![\[使用 WaitCondition 钩子构造迁移 Amazon RDS 数据库的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e58680e3-f89f-422f-b0e1-e85605ae8bf9/images/3b83fc2a-80bb-4ba9-9637-782060493cf0.png)


此示例工作流使用 `waitcondition-hook-for-aws-fargate-task` 构造来执行数据库迁移，如下所示：

1. 预调配了一个 Amazon Relational Database Service（Amazon RDS）实例。

1. 此 `waitcondition-hook-for-aws-fargate-task` 构造运行数据库迁移任务，并将堆栈作为 Amazon Elastic Compute Cloud（Amazon EC2）实例暂停。

1. 如果迁移任务成功完成，则会向发送成功信号 CloudFormation。否则，它会向堆栈发送 Fail 信号，然后回滚堆栈。 CloudFormation 

## 工具
<a name="use-the-aws-fargate-waitcondition-hook-construct-tools"></a>

**AWS 服务**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html)是一个软件开发框架，可帮助您在代码中定义云基础架构并通过它进行配置 CloudFormation。
+ [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在和的整个 AWS 账户 生命周期中对其进行管理 AWS 区域。
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可帮助您实时监控您的 AWS 资源和运行的应用程序 AWS 的指标。
+ [Amazon Elastic Container Service（Amazon ECS）](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/Welcome.html)是一项快速、可扩展的容器管理服务，可帮助您运行、停止和管理集群上的容器。
+ [AWS Fargate](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/AWS_Fargate.html) 可帮助您运行容器，无需管理服务器或 Amazon EC2 实例。它与 Amazon ECS 结合使用。
+ [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)是一项无服务器编排服务，可帮助您组合 AWS Lambda 功能和其他功能 AWS 服务 来构建关键业务应用程序。
+ [Amazon Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。此虚拟网络类似于您在自己的数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。

**其他工具**
+ [npm](https://docs.npmjs.com/about-npm) 是在 Node.js 环境中运行的软件注册表，用于共享或借用软件包以及管理私有软件包的部署。
+ [Yarn](https://yarnpkg.com/) 是一个开源软件包管理器，你可以用它来管理 JavaScript 项目中的依赖关系。Yarn 可帮助您安装、更新、配置和移除软件包依赖关系。

**代码存储库**

此模式的代码可在 GitHub [waitcondition-hook-for-aws-fargate-](https://github.com/aws-samples/waitcondition-hook-for-aws-fargate-task) task 存储库中找到。

## 最佳实践
<a name="use-the-aws-fargate-waitcondition-hook-construct-best-practices"></a>
+ 在构建 AWS CDK 应用程序时，请按照 AWS CDK v2 文档 AWS CDK中的[开发和部署云基础架构的最佳实践进行](https://docs.aws.amazon.com/cdk/v2/guide/best-practices.html)操作。
+ 对于此 AWS Fargate 任务，请按照 Amazon ECS 文档中的 [Amazon ECS 容器映像最佳实践](https://docs.aws.amazon.com/AmazonECS/latest/bestpracticesguide/application.html)进行操作。

## 操作说明
<a name="use-the-aws-fargate-waitcondition-hook-construct-epics"></a>

### 设置 AWS CDK
<a name="set-up-the-cdk"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装 AWS CDK。 | 要 AWS CDK 在本地计算机或其他环境中安装，请运行以下命令：<pre>npm install -g aws-cdk@latest</pre> | 云架构师、应用程序开发人员 | 
| Bootstrap 的。 AWS CDK | [引导](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)是指让[环境](https://docs.aws.amazon.com/cdk/v2/guide/environments.html)为部署工作做好准备的过程。要为目标引导 AWS CDK 工具包 AWS 账户 AWS 区域，请运行以下命令：<pre>cdk bootstrap aws://ACCOUNT-NUMBER-1/REGION-1 </pre>此命令创建一个名为的 CloudFormation 堆栈`CDKToolkit`。 | 云架构师 | 

### 运行 AWS Fargate 任务构造 WaitCondition 挂钩
<a name="run-the-waitcondition-hook-for-fargatelong-tasks-construct"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 CDK 项目。 | 使用您的首选语言创建一个 CDK 项目。此模式使用 TypeScript. 要使用创建 CDK 项目 TypeScript，请运行以下命令：`cdk init app —language typescript` | 云架构师 | 
| 安装软件包。 | 在 CDK 项目的根路径上，执行 `npm install`。安装 CDK 库之后，运行如下命令以便安装 `waitcondition-hook-for-aws-fargate-task`：`yarn add waitcondition-hook-for-aws-fargate-task` | 云架构师 | 
| 构建您的 CDK 应用程序和 Amazon ECS 组件。 | 构建您的 CDK 项目。需要一个 Amazon ECS 任务定义资源。有关如何创建任务定义的信息，请参阅 Amazon ECS 文档中的 [Amazon ECS 任务定义](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html)。如下示例将使用此构造：<pre>import * as cdk from 'aws-cdk-lib';<br />import { Vpc } from 'aws-cdk-lib/aws-ec2';<br />import * as ecr from 'aws-cdk-lib/aws-ecr';<br />import * as ecs from 'aws-cdk-lib/aws-ecs';<br />import { Construct } from 'constructs';<br />import { FargateRunner } from 'waitcondition-hook-for-aws-fargate-task';<br />import { Queue } from 'aws-cdk-lib/aws-sqs';<br /><br />export class FargateRunnerStack extends cdk.Stack {<br />    constructor(scope: Construct, id: string, props?: cdk.StackProps) {<br />        super(scope, id, props);<br />        // Define the VPC<br />        const vpc = new Vpc(this, 'MyVpc')<br />        // Define the Fargate Task<br />        const taskDefinition = new ecs.FargateTaskDefinition(this, 'MyTask', {});<br />        // Import exiting ecr repo<br />        const repo = ecr.Repository.fromRepositoryName(this, 'MyRepo', 'RepoName');<br />        // Add a container to the task<br />        taskDefinition.addContainer('MyContainer', {<br />            image: ecs.ContainerImage.fromEcrRepository(repo),<br />        });<br />        // Create the Fargate runner<br />        const myFargateRunner = new FargateRunner(this, 'MyRunner', {<br />            fargateTaskDef: taskDefinition,<br />            timeout: `${60 * 5}`,<br />            vpc: vpc,<br />        });<br />        // Create the SQS queue<br />        const myQueue = new Queue(this, 'MyQueue', {});<br />        // Add dependency<br />        myQueue.node.addDependency(myFargateRunner);<br />    }<br />}</pre> | 云架构师 | 
| 合成并启动 CDK 应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)`waitcondition-hook-for-aws-fargate-task` 构造将运行 Fargate 任务。 | 云架构师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理资源。 | 要清理上一步中预调配的资源，请运行如下命令：<pre>cdk destroy </pre> | 云架构师 | 

## 故障排除
<a name="use-the-aws-fargate-waitcondition-hook-construct-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 一般 CloudFormation 堆栈故障 | 要帮助排除一般 CloudFormation 堆栈故障，请添加`--no-rollback`标志，如以下示例所示：<pre>cdk deploy --no-rollback</pre>此命令将暂停 CloudFormation 堆栈回滚，从而为您提供故障排除资源。有关更多信息，请参阅 CloudFormation 文档中的[选择配置资源时如何处理故障](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stack-failure-options.html)。 | 
| AWS Step Functions 失败 |  AWS Step Functions 状态机可能由于不同的原因而无法执行。配置 `—disable-rollback` 之后，请按照以下步骤进行问题排查：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)有关更多信息，请参阅 AWS Step Functions 文档中的 Step F [unctions 中的问题疑难解答](https://docs.aws.amazon.com/step-functions/latest/dg/troubleshooting.html)和[在 Step Functions 控制台中查看执行详情](https://docs.aws.amazon.com/step-functions/latest/dg/concepts-view-execution-details.html#exec-details-intf-step-details)。 | 
| AWS Lambda 功能失败 | 此构造将预调配两个 Lambda 函数：`CallbackFunction` 和 `ErrorhandlerFunction`。它们可能由于各种原因而失败，例如未处理的异常。使用以下步骤进行问题排查：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)有关更多信息，请参阅文档[中的 Lambda 问题疑难解答](https://docs.aws.amazon.com/lambda/latest/dg/lambda-troubleshooting.html)。 AWS Lambda  | 

## 相关资源
<a name="use-the-aws-fargate-waitcondition-hook-construct-resources"></a>

**AWS 文档**
+ [AWS CDK 构建 API 参考](https://docs.aws.amazon.com/cdk/api/v2/docs/aws-construct-library.html)
+ [开始使用 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html)
+ [学习如何创建和使用 Amazon ECS 资源](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/getting-started.html)
+ [学习如何开始使用 Step Functions](https://docs.aws.amazon.com/step-functions/latest/dg/getting-started-with-sfn.html)
+ [什么是 AWS CDK？](https://docs.aws.amazon.com/cdk/v2/guide/home.html)

**其他资源**
+ [AWS Fargate 任务的等待条件挂钩](https://pypi.org/project/waitcondition-hook-for-aws-fargate-task/) (npm)
+ [waitcondition-hook-for-aws-fargate-task](https://pypi.org/project/waitcondition-hook-for-aws-fargate-task/) 1.0.6 (pypi.org)

# 在 AWS 中使用第三方 Git 源存储库 CodePipeline
<a name="use-third-party-git-source-repositories-in-aws-codepipeline"></a>

*Kirankumar Chandrashekar，Amazon Web Services*

## Summary
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-summary"></a>

此模式描述了如何将 AWS CodePipeline 与第三方 Git 源存储库配合使用。

[AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/concepts-continuous-delivery-integration.html) 是一项持续交付服务，可自动执行构建、测试和部署软件的任务。该服务目前支持由 [AWS CodeCommit](https://aws.amazon.com/codecommit) 和 Atlassian Bit GitHub bucket 管理的 Git 存储库。但是，部分企业使用与其单点登录（SSO）服务和 Microsoft Active Directory 集成的第三方 Git 存储库进行身份验证。您可以 CodePipeline 通过创建自定义操作和 webhook 将这些第三方 Git 存储库用作来源。

Webhook 是一种 HTTP 通知，用于检测其他工具（例如 GitHub 存储库）中的事件，并将这些外部事件连接到管道。当您在中创建 webhook 时 CodePipeline，该服务会返回一个网址，您可以在 Git 存储库 webhook 中使用该网址。**如果您将代码推送到 Git 存储库的特定分支，Git webhook 会通过此 URL 启动 CodePipeline webhook，并将管道的源代码阶段设置为 “进行中”。**当管道处于此状态时，作业工作人员会轮 CodePipeline 询自定义作业，运行该作业，并将成功或失败状态发送到 CodePipeline。在本示例中，由于管道处于源代码阶段，因此作业工作程序使用所轮询的作业提供的对象密钥获取 Git 存储库的内容，压缩内容，然后将其上传到存储管道构件的 Amazon Simple Storage Service (Amazon S3) 存储桶。您还可以将自定义操作的过渡与 Amazon 中的事件关联起来 CloudWatch，并根据该事件启动任务工作人员。通过此设置，您可以使用该服务本身不支持的第三方 Git 存储库作为来源。 CodePipeline

## 先决条件和限制
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户
+ 支持 webhook 的 Git 存储库，可通过互联网连接到 CodePipeline webhook 网址 
+ AWS 命令行界面（AWS CLI）[已安装](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html)并[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)以使用 AWS 账户

## 架构
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-architecture"></a>

此模式涉及这些步骤：

1. 用户将代码提交到至 Git 存储库。

1. 调用 Git 网络钩子。

1.  CodePipeline webhook 被称为。

1. 管道设置为**进行中**，源阶段设置为**进行中**状态。

1. 源阶段操作启动 CloudWatch 事件规则，表示该规则已启动。

1. 该 CloudWatch 事件启动一个 Lambda 函数。

1. Lambda 函数获取自定义操作作业详细信息。

1. Lambda 函数启动 AW CodeBuild S 并将所有与工作相关的信息传递给它。

1. CodeBuild 从 Secrets Manager 获取访问 HTTPS Git 的 SSH 公钥或用户证书。

1. CodeBuild 克隆特定分支的 Git 存储库。

1. CodeBuild 压缩存档并将其上传到用作 CodePipeline 项目存储的 S3 存储桶。

![\[使用第三方 Git 源代码存储库作为 AWS CodePipeline 源代码的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/84284bec-b39d-466a-9fd9-994be2c953df/images/85555dab-7317-40f5-86a7-ccb8987c5bf3.png)


 

## 工具
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-tools"></a>
+ [AWS CodePipeline](https://aws.amazon.com/codepipeline/) — AWS CodePipeline 是一项完全托管的[持续交付](https://aws.amazon.com/devops/continuous-delivery/)服务，可帮助您自动执行发布管道，实现快速可靠的应用程序和基础设施更新。 CodePipeline 根据您定义的发布模型，针对每次代码变更自动执行发布过程的构建、测试和部署阶段。这让您可以快速而可靠地交付各种功能和更新。您可以将 AWS CodePipeline 与第三方服务（例如 GitHub 您自己的自定义插件）集成。
+ [AWS Lambda](https://aws.amazon.com/lambda/) – AWS Lambda 让您无需预调配或管理服务器即可运行代码。借助 Lambda，您可以为几乎任何类型的应用程序或后端服务运行代码，而无需进行任何管理。您只需上传您的代码，Lambda 就会处理以高可用性运行和扩展您的代码所需一切。您可以将您的代码设置为自动从其他 Amazon Web Services 启动，或者直接从任何 Web 或移动应用程序调用。
+ [AWS CodeBuild](https://aws.amazon.com/codebuild/) — AWS CodeBuild 是一项完全托管的[持续集成](https://aws.amazon.com/devops/continuous-integration/)服务，可编译源代码、运行测试并生成可随时部署的软件包。使用 CodeBuild，您无需预置、管理和扩展自己的构建服务器。 CodeBuild 持续扩展并同时处理多个构建，因此您的构建不会排队等待。您可以使用预先打包的构建环境快速开始，也可以创建使用您自己的构建工具的自定义构建环境。
+ [AWS Secrets Manager](https://aws.amazon.com/secrets-manager/) – AWS Secrets Manager 可帮助您保护访问您的应用程序、服务和 IT 资源所需密钥。该项服务让您可以在数据库凭证、API 密钥和其他密钥的整个生命周期内对其进行轮换、管理和检索。用户和应用程序通过调用 Secrets Manager 来检索机密 APIs，而不必以纯文本格式对敏感信息进行硬编码。Secrets Manager 通过与Amazon Relational Database Service (Amazon RDS)、Amazon Redshift 和Amazon DocumentDB 的内置集成，提供密钥轮换。可以扩展该服务以支持其他类型的机密，包括 API 密钥和 OAuth 令牌。此外，Secrets Manager 使您能够使用精细权限控制对密钥的访问，并集中审计 AWS 云、第三方服务和本地环境资源的密钥轮换。
+ [Ama](https://aws.amazon.com/cloudwatch/) zon CloudWatch — Amazon CloudWatch 是一项专为 DevOps 工程师、开发人员、站点可靠性工程师 (SREs) 和 IT 经理构建的监控和观察服务。 CloudWatch 为您提供数据和切实可行的见解，以监控您的应用程序、响应系统范围的性能变化、优化资源利用率并获得统一的运营状况视图。 CloudWatch 以日志、指标和事件的形式收集监控和运营数据，为您提供在 AWS 和本地服务器上运行的 AWS 资源、应用程序和服务的统一视图。您可以使用 CloudWatch 来检测环境中的异常行为、设置警报、并排可视化日志和指标、采取自动操作、解决问题以及发现见解，以保持应用程序平稳运行。
+ [Amazon S3](https://aws.amazon.com/s3/) – Amazon Simple Storage Service (Amazon S3) 是一项对象存储服务，可让您存储和保护任意数量的数据，用于网站、移动应用程序、备份和还原、归档、企业应用程序、IoT 设备和大数据分析。Amazon S3 提供 easy-to-use管理功能，可帮助您整理数据并配置经过微调的访问控制，以满足您的特定业务、组织和合规要求。

## 操作说明
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-epics"></a>

### 在中创建自定义操作 CodePipeline
<a name="create-a-custom-action-in-codepipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 AWS CLI 或 AWS 创建自定义操作 CloudFormation。 | 此步骤涉及创建自定义源操作，该操作可在特定区域 AWS 账户中用于管道的源代码阶段。您必须使用 AWS CLI 或 AWS CloudFormation （不是控制台）来创建自定义源操作。有关本文和其他操作说明中描述的命令和步骤的更多信息，请参阅此模式末尾的 “相关资源”部分。在 AWS CLI 中，使用 create-custom-action-type命令。使用--configuration-properties提供作业工作人员在轮询 CodePipeline 作业时需要处理的所有参数。请务必记下提供给 --provider 和 --action-version 选项的值，这样您就可以在使用此自定义源代码阶段创建管道时使用相同的值。您也可以使用资源类型在 AWS CloudFormation 中创建自定义源操作 AWS::CodePipeline::CustomActionType。 | 常规 AWS | 

### 设置身份验证
<a name="set-up-authentication"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 SSH 密钥对。 | 创建 Secure Shell (SSH) 密钥对。有关说明，请参阅 GitHub 文档。 | 系统/工程师 DevOps  | 
| 在 AWS Secrets Manager 中创建密钥。 | 从 SSH 密钥对中复制私钥的内容，然后在 AWS Secrets Manager 创建密钥。此密钥用于在访问 Git 存储库时进行身份验证。 | 常规 AWS | 
| 将公有密钥添加至 Git 存储库。 | 将 SSH 密钥对中的公钥添加到 Git 存储库账户设置中，以便根据私钥进行身份验证。 | 系统/工程师 DevOps  | 

### 创建管道和网络钩子
<a name="create-a-pipeline-and-webhook"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建包含自定义源操作的管道。 | 在中创建管道 CodePipeline。配置源阶段时，选择之前创建的自定义源操作。您可以在 AWS CodePipeline 控制台或 AWS CLI 中执行此操作。 CodePipeline 提示您输入您在自定义操作上设置的配置属性。该信息是作业工作程序处理自定义操作作业的必要条件。按向导进行操作，为管道创建下一个阶段。 | 常规 AWS | 
| 创建一个 CodePipeline webhook。 | 为您使用自定义源操作构建的管道创建网络钩子。您必须使用 AWS CLI 或 AWS CloudFormation （不是控制台）来创建 Webhook。在 AWS CLI 中，运行 put-webhook 命令并为网络钩子选项提供相应值。记下命令返回的网络钩子 URL。如果您使用 AWS CloudFormation 创建 Webhook，请使用资源类型 AWS::CodePipeline::Webhook。请务必从创建的资源中输出网络钩子网址，并记录。 | 常规 AWS | 
| 创建 Lambda 函数和项目。 CodeBuild  | 在此步骤中，您将使用 Lambda 和 CodeBuild 创建一个任务工作线程，该工作人员将轮询 CodePipeline 自定义操作的任务请求，运行该作业，并将状态结果返回到。 CodePipeline创建一个 Lambda 函数，当管道的自定义源操作阶段转换为 “进行中” 时，该函数由 Amazon CloudWatch Events 规则启动。当 Lambda 函数启动时，它应通过轮询作业来获取自定义操作作业的详细信息。您可以使用 PollForJobs API 返回此信息。获得轮询的作业信息后，Lambda 函数应返回确认，然后使用从自定义操作的配置属性中所获得的数据处理该信息。当工作人员准备好与 Git 仓库对话时，你可以启动一个 CodeBuild 项目，因为使用 SSH 客户端可以方便地处理 Git 任务。 | 常规 AWS，代码开发人员 | 

### 在中创建活动 CloudWatch
<a name="create-an-event-in-cloudwatch"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 CloudWatch 事件规则。 | 创建一个 CloudWatch 事件规则，每当管道的自定义操作阶段转换为 “进行中” 时，该规则就会将 Lambda 函数作为目标启动。 | 常规 AWS | 

## 相关资源
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-resources"></a>

**在中创建自定义操作 CodePipeline**
+ [在中创建和添加自定义操作 CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-create-custom-action.html)
+ [AWS::CodePipeline::CustomActionType 资源](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-customactiontype.html)

**设置身份验证**
+ [通过 AWS Secrets Manager 创建和管理密钥](https://docs.aws.amazon.com/secretsmanager/latest/userguide/managing-secrets.html)

**创建管道和网络钩子**
+ [在中创建管道 CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-create.html)
+ [put-webhook 命令参考](https://docs.aws.amazon.com/cli/latest/reference/codepipeline/put-webhook.html)
+ [AWS::CodePipeline::Webhook 资源](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-codepipeline-webhook.html)
+ [PollForJobs API 参考](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html)
+ [在中创建和添加自定义操作 CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/actions-create-custom-action.html)
+ [在 AWS 中创建构建项目 CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/create-project.html)

**创建事件**
+ [通过 Amazon CloudWatch Events 检测管道状态的变化并做出反应](https://docs.aws.amazon.com/codepipeline/latest/userguide/detect-state-changes-cloudwatch-events.html)

**其他参考资料**
+ [使用中的管道 CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines.html)
+ [AWS Lambda 开发人员指南](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)

# 使用 AWS 创建用于验证 Terraform 配置的 CI/CD 管道 CodePipeline
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline"></a>

*Aromal Raj Jayarajan 和 Vijesh Vijayakumaran Nair，Amazon Web Services*

## Summary
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-summary"></a>

此模式展示了如何使用 AWS 部署的持续集成和持续交付 (CI/CD) 管道来测试 HashiCorp Terraform 配置。 CodePipeline

Terraform 是一款命令行界面应用程序，可帮助您使用代码来配置和管理云基础设施和资源。[此模式中提供的解决方案创建了一个 CI/CD 管道，通过运行五个CodePipeline 阶段来帮助您验证 Terraform 配置的完整性：](https://docs.aws.amazon.com/codepipeline/latest/userguide/concepts.html#concepts-stages)

1. `"checkout"`从 AWS 存储库中提取你正在测试的 Terraform 配置。 CodeCommit 

1. `"validate"`[运行基础设施即代码 (IaC) 验证工具，包括 [tfsec [TFLint](https://github.com/terraform-linters/tflint)、和 chec](https://github.com/aquasecurity/tfsec) kov。](https://www.checkov.io/)该阶段还会运行以下 Terraform IaC 验证命令：`terraform validate` 和 `terraform fmt`。

1. `"plan"` 显示如果应用 Terraform 配置，将对基础架构应用哪些更改。

1. `"apply"` 使用生成的计划在测试环境中配置所需基础架构。

1. `"destroy"` 移除在 `"apply"` 阶段中创建的测试基础架构。

## 先决条件和限制
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ AWS 命令行界面（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)
+ [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)，已在本地计算机上安装并配置
+ [Terraform](https://learn.hashicorp.com/collections/terraform/aws-get-started?utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS)，已在本地计算机上安装并配置

**限制**
+ 这种模式的方法 CodePipeline 将 AWS 部署到一个 AWS 账户中，并且仅限于 AWS 区域。多账户和多区域部署需更改配置。
+ 此模式配置的 AWS Identity and Access Management (IAM) 角色 (**codepiline\$1iam\$1role**) 遵循最低权限的原则。必须根据您的管道需要创建的特定资源，更新此 IAM 角色的权限。 ****

**产品版本**
+ AWS CLI 版本 2.9.15 或更高版本
+ Terraform 版本 1.3.7 或更高版本

## 架构
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-architecture"></a>

**目标技术堆栈**
+ AWS CodePipeline
+ AWS CodeBuild
+ AWS CodeCommit
+ Amazon IAM
+ Amazon Simple Storage Service(Amazon S3)
+ AWS Key Management Service（AWS KMS）
+ Terraform

**目标架构**

下图显示了用于在中测试 Terraform 配置的示例 CI/CD 管道工作流程。 CodePipeline

![\[使用 AWS CI/CD 管道测试 Terraform 配置的架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/4df7b1f8-8eef-4d85-a971-a7f158be9691/images/90b931c8-e745-4b52-92de-a367fb0f1f51.png)


下图显示了如下工作流：

1. 在中 CodePipeline，AWS 用户通过在 AWS CLI 中运行`terraform apply`命令来启动 Terraform 计划中建议的操作。

1. AW CodePipeline S 担任 IAM 服务角色，其中包括访问 CodeCommit CodeBuild、AWS KMS 和 Amazon S3 所需的策略。

1. CodePipeline 运行`"checkout"`管道阶段，从 AWS CodeCommit 存储库中提取 Terraform 配置进行测试。

1. CodePipeline 通过运行 IaC 验证工具并在项目中运行 Terraform iaC 验证命令来运行测试 Terraform 配置的`"validate"`阶段。 CodeBuild 

1. CodePipeline 运行该`"plan"`阶段以基于 Terraform 配置在 CodeBuild 项目中创建计划。在将更改应用至测试环境前，AWS 用户可查看此计划。

1. Code Pi `"apply"` peline 通过使用 CodeBuild 项目在测试环境中配置所需的基础架构，来实施计划。

1. CodePipeline 运行`"destroy"`阶段，该阶段用于 CodeBuild 移除在`"apply"`阶段中创建的测试基础架构。

1. Amazon S3 存储桶存储管道项目，这些项目使用 AWS KMS [客户托管密钥](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#customer-cmk)进行加密和解密。

## 工具
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-tools"></a>

**工具**

*AWS 服务*
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可帮助您快速建模和配置软件发布的不同阶段，并自动执行持续发布软件变更所需的步骤。
+ [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 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) 可帮助您创建和控制加密密钥，以帮助保护您的数据。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

*其他服务*
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款命令行界面应用程序，可帮助您使用代码来配置和管理云基础架构和资源。

**代码**

此模式的代码可在 GitHub [aws-codepipeline-terraform-cicdsamples](https://github.com/aws-samples/aws-codepipeline-terraform-cicd-samples)存储库中找到。存储库包含创建此模式所述目标架构所需 Terraform 配置。

## 操作说明
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-epics"></a>

### 配置解决方案组件
<a name="provision-the-solution-components"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆 GitHub 存储库。 | 在终端窗口中运行以下命令来克隆 GitHub[aws-codepipeline-terraform-cicdsamples](https://github.com/aws-samples/aws-codepipeline-terraform-cicd-samples)存储库：<pre>git clone https://github.com/aws-samples/aws-codepipeline-terraform-cicd-samples.git</pre>有关更多信息，请参阅 GitHub 文档[中的克隆存储库](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository)。 | DevOps 工程师 | 
| 创建 Terraform 变量定义文件。 | 基于您的使用案例要求创建 `terraform.tfvars` 文件。您可以更新克隆存储库中 `examples/terraform.tfvars` 文件中的变量。有关更多信息，请参阅 Terraform 文档中的[为根模块变量赋值](https://developer.hashicorp.com/terraform/language/values/variables#assigning-values-to-root-module-variables)。存储库的 `Readme.md` 文件包含有关所需变量的更多信息。 | DevOps 工程师 | 
| 将 AWS 配置为 Terraform 提供程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)有关更多信息，请参阅 Terraform 文档中的 [AWS 提供者](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)。 | DevOps 工程师 | 
| 更新用于构建 Amazon S3 复制存储桶的 Terraform 提供程序配置。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)复制支持跨 Amazon S3 存储桶自动以异步方式复制对象。 | DevOps 工程师 | 
| 初始化 Terraform 配置。 | 如要初始化包含 Terraform 配置文件的工作目录，在克隆存储库的根文件夹运行以下命令。<pre>terraform init</pre> | DevOps 工程师 | 
| 创建 Terraform 计划。 | 若要创建 Terraform 计划，请在克隆存储库的根文件夹中运行以下命令：<pre>terraform plan --var-file=terraform.tfvars -out=tfplan</pre>Terraform 会评估配置文件，以确定已声明资源的目标状态。然后，其将比较目标状态与当前状态，并创建计划。 | DevOps 工程师 | 
| 验证 Terraform 计划。 | 查看 Terraform 计划，并确认它已在您的目标 Amazon Web Services account 中配置了所需架构。 | DevOps 工程师 | 
| 部署解决方案。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)Terraform 创建、更新或销毁基础设施，以实现配置文件中声明的目标状态。 | DevOps 工程师 | 

### 通过运行管道验证 Terraform 配置
<a name="validate-terraform-configurations-by-running-the-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置源代码存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html) | DevOps 工程师 | 
| 验证管道阶段。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)有关更多信息，请参阅 *AWS CodePipeline 用户指南*中的[查看管道详情和历史记录（控制台）](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipelines-view-console.html)。将更改提交至源存储库的主分支时，测试管道会自动激活。 | DevOps 工程师 | 
| 验证报告输出。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)在此`"validate"`阶段，该`<project_name>-validate` CodeBuild 项目会为您的代码生成漏洞报告。 | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 清理管道和关联资源。 | 要从您的 Amazon Web Services account 中删除测试资源，请在克隆存储库的根文件夹运行以下命令：<pre>terraform destroy --var-file=terraform.tfvars</pre> | DevOps 工程师 | 

## 问题排查
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 在`"apply"`舞台期间您会收到**AccessDenied **错误。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html) | 

## 相关资源
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-resources"></a>
+ [模块数据库](https://developer.hashicorp.com/terraform/language/modules/syntax)（Terraform 文档）
+ [ CI/CD 如何使用 Terraform 部署和配置 AWS 安全服务](https://aws.amazon.com/blogs/security/how-use-ci-cd-deploy-configure-aws-security-services-terraform/)（AWS 博客文章）
+ [使用服务相关角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html)（IAM 文档）
+ [create-pipeline](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codepipeline/create-pipeline.html)（AWS CLI 文档）
+ [为存储在 Amazon S3 中的项目配置服务器端加密 CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/S3-artifact-encryption.html)（AWS CodePipeline 文档）
+ [AWS 配额 CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/limits.html)（AWS CodeBuild 文档）
+ [AWS 中的数据保护 CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/data-protection.html)（AWS CodePipeline 文档）

## 附加信息
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-additional"></a>

**自定义 Terraform 模块**

以下是在此模式中使用的自定义 Terraform 模块列表：
+ `codebuild_terraform`创建构成管道每个阶段的 CodeBuild 项目。
+ `codecommit_infrastructure_source_repo`捕获并创建源 CodeCommit 存储库。
+ `codepipeline_iam_role` 为管道创建所需 IAM 角色。
+ `codepipeline_kms` 为 Amazon S3 对象加密和解密创建所需 AWS KMS 密钥。
+ `codepipeline_terraform`为源 CodeCommit 存储库创建测试管道。
+ `s3_artifacts_bucket` 创建一个 Amazon S3 存储桶以管理管道项目。

**生成规范文件**

以下是此模式用于运行每个管道阶段的构建规范 (buildspec) 文件列表：
+ `buildspec_validate.yml` 运行 `"validate"` 阶段。
+ `buildspec_plan.yml` 运行 `"plan"` 阶段。
+ `buildspec_apply.yml` 运行 `"apply"` 阶段。
+ `buildspec_destroy.yml` 运行 `"destroy"`阶段。

*生成规格文件变量*

每个 buildspec 文件都使用以下变量激活不同的特定构建设置：


| 
| 
| 变量 | 默认 值 | 说明 | 
| --- |--- |--- |
| `CODE_SRC_DIR` | "." | 定义源 CodeCommit 目录 | 
| `TF_VERSION` | "1.3.7" | 为构建环境定义 Terraform 版本 | 

每个 `buildspec_validate.yml` 文件都使用以下变量激活不同的特定构建设置：


| 
| 
| 变量 | 默认 值 | 说明 | 
| --- |--- |--- |
| `SCRIPT_DIR` | "./templates/scripts" | 定义脚本目录 | 
| `ENVIRONMENT` | "dev" | 定义环境名称 | 
| `SKIPVALIDATIONFAILURE` | "Y" | 失败时跳过验证 | 
| `ENABLE_TFVALIDATE` | "Y" | 激活 Terraform 验证  | 
| `ENABLE_TFFORMAT` | "Y" | 激活 Terraform 格式 | 
| `ENABLE_TFCHECKOV` | "Y" | 激活 checkovov 扫描 | 
| `ENABLE_TFSEC` | "Y" | 激活 tfsec 扫描 | 
| `TFSEC_VERSION` | "v1.28.1" | 定义 tfsec 版本 | 

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

**Topics**
+ [使用 AWS PrivateLink 和 Network Load Balancer 在 Amazon EKS 上私密访问容器应用程序](access-container-applications-privately-on-amazon-eks-using-aws-privatelink-and-a-network-load-balancer.md)
+ [将一个 AWS CodeCommit 存储库 AWS 账户 与另一个账户中的 Amazon A SageMaker I Studio Classic 关联起来](associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account.md)
+ [使用着陆区域加速器自动创建账户 AWS](automate-account-creation-lza.md)
+ [通过 AWS Systems Manager 自动添加或更新 Windows 注册表项](automate-adding-or-updating-windows-registry-entries-using-aws-systems-manager.md)
+ [使用 AWS Batch 自动备份 Amazon RDS for PostgreSQL 数据库实例](automate-backups-for-amazon-rds-for-postgresql-db-instances-by-using-aws-batch.md)
+ [使用 AWS SAM 自动部署嵌套应用程序](automate-deployment-of-nested-applications-using-aws-sam.md)
+ [使用 CI/CD 管道在 Amazon EKS 中自动部署节点终止处理程序](automate-deployment-of-node-termination-handler-in-amazon-eks-by-using-a-ci-cd-pipeline.md)
+ [在 Amazon MQ 中自动化 RabbitMQ 配置](automate-rabbitmq-configuration-in-amazon-mq.md)
+ [在跨区域自动复制 Amazon RDS 实例 AWS 账户](automate-the-replication-of-amazon-rds-instances-across-aws-accounts.md)
+ [使用 CI/CD 管道自动构建 Java 应用程序并将其部署到 Amazon EKS](automatically-build-and-deploy-a-java-application-to-amazon-eks-using-a-ci-cd-pipeline.md)
+ [使用 Python 应用程序为 Amazon DynamoDB 自动生成 PynamoDB 模型和 CRUD 函数](automatically-generate-a-pynamodb-model-and-crud-functions-for-amazon-dynamodb-by-using-a-python-application.md)
+ [使用 CodePipeline IAM Access Analyzer 和 AWS CloudFormation 宏自动验证和部署 IAM 策略和角色](automatically-validate-and-deploy-iam-policies-and-roles-in-an-aws-account-by-using-codepipeline-iam-access-analyzer-and-aws-cloudformation-macros.md)
+ [在 Stromasys Charon-SSP 模拟器中备份 Sun SPARC 服务器 AWS 云](back-up-sun-sparc-servers-in-the-stromasys-charon-ssp-emulator-on-the-aws-cloud.md)
+ [使用 AWS DataOps 开发套件构建数据管道以提取、转换和分析 Google Analytics 数据](build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit.md)
+ [使用 Amazon A EC2 uto Scaling 和 Systems Manager 构建 Micro Focus 企业服务器 PAC](build-a-micro-focus-enterprise-server-pac-with-amazon-ec2-auto-scaling-and-systems-manager.md)
+ [使用 Image Builder 和 Terraform 为经过强化的容器 EC2 镜像构建管道](build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform.md)
+ [使用亚马逊 A SageMaker I 和 Azure 构建 MLOps 工作流程 DevOps](build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops.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 理 Terraform (AFT) 资源的 Account Factory](clean-up-aft-resources-safely-after-state-file-loss.md)
+ [使用在 Amazon Logs 中为.NET 应用程序配置 CloudWatch 日志记录 NLog](configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog.md)
+ [将 Amazon ECR 容器镜像复制到各处 AWS 账户 AWS 区域](copy-ecr-container-images-across-accounts-regions.md)
+ [为 AWS Step Functions SageMaker 创建自定义 Docker 容器镜像并将其用于模型训练](create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions.md)
+ [在不支持 AWS 的 AWS 区域创建管道 CodePipeline](create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline.md)
+ [使用 Amazon CloudWatch 异常检测为自定义指标创建警报](create-alarms-for-custom-metrics-using-amazon-cloudwatch-anomaly-detection.md)
+ [使用 AWS CDK 外观和逃生舱口自定义默认角色名称](customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches.md)
+ [部署可同时检测多个代码可交付成果中安全问题的管道](deploy-a-pipeline-that-simultaneously-detects-security-issues-in-multiple-code-deliverables.md)
+ [使用基础设施即代码，在 Amazon Web Services Cloud 上部署和管理无服务器数据湖](deploy-and-manage-a-serverless-data-lake-on-the-aws-cloud-by-using-infrastructure-as-code.md)
+ [在作为 Docker 容器 AWS IoT Greengrass V2 运行时部署容器化应用程序](deploy-containerized-applications-on-aws-iot-greengrass-version-2-running-as-a-docker-container.md)
+ [使用 Amazon EKS 和 Amazon S3 中的 Helm 图表存储库部署 Kubernetes 资源和软件包](deploy-kubernetes-resources-and-packages-using-amazon-eks-and-a-helm-chart-repository-in-amazon-s3.md)
+ [使用 AWS CDK 部署多堆栈应用程序 TypeScript](deploy-multiple-stack-applications-using-aws-cdk-with-typescript.md)
+ [使用带有 Kiro 和其他编码助手的 MCP 服务器部署实时编码安全验证](deploy-real-time-coding-security-validation-by-using-an-mcp-server-with-kiro-and-other-coding-assistants.md)
+ [使用 Terraform 在亚马逊 EC2 和亚马逊 FSx 上部署 SQL Server 故障转移集群实例](deploy-sql-server-failover-cluster-instances-on-amazon-ec2-and-amazon-fsx.md)
+ [使用 Terraform 为 AWS WAF 解决方案部署安全自动化](deploy-the-security-automations-for-aws-waf-solution-by-using-terraform.md)
+ [使用 RAG 和提示开发基于人工智能聊天的高级生成式 AI 助手 ReAct](develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.md)
+ [使用 AWS CloudFormation 模板 GuardDuty 有条件地启用 Amazon](enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates.md)
+ [使用 Amazon EKS 容器组身份和 KEDA 在 Amazon EKS 中设置事件驱动的自动扩缩](event-driven-auto-scaling-with-eks-pod-identity-and-keda.md)
+ [使用 Amazon Personalize 生成个性化和重新排名的推荐](generate-personalized-and-re-ranked-recommendations-using-amazon-personalize.md)
+ [当 AWS KMS 密钥的密钥状态发生变化时获取 Amazon SNS 通知](get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes.md)
+ [使用 Account Factory for Terraform 来管理多个账户的权限集](govern-permission-sets-aft.md)
+ [迁移到 Amazon ECR 存储库时自动识别重复的容器映像](identify-duplicate-container-images-automatically-when-migrating-to-ecr-repository.md)
+ [在 Amazon API Gateway 中使用自定义域实施基于路径的 API 版本控制](implement-path-based-api-versioning-by-using-custom-domains.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)
+ [使用 Kubernetes 在亚马逊 EKS 工作节点上安装 SSM 代理 DaemonSet](install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset.md)
+ [将 Stonebranch Universal Controller 与 AWS Mainframe Modernization 集成](integrate-stonebranch-universal-controller-with-aws-mainframe-modernization.md)
+ [大型机现代化： AWS 使用 Rock DevOps et 软件企业套件开启](mainframe-modernization-devops-on-aws-with-micro-focus.md)
+ [使用以下 AWS IAM Identity Center 命令将权限集作为代码进行管理 AWS CodePipeline](manage-aws-iam-identity-center-permission-sets-as-code-by-using-aws-codepipeline.md)
+ [使用 Terraform 动态管理 AWS 权限集](manage-aws-permission-sets-dynamically-by-using-terraform.md)
+ [通过使用 AWS CDK 设置 Amazon ECS Anywhere 来管理本地容器应用程序](manage-on-premises-container-applications-by-setting-up-amazon-ecs-anywhere-with-the-aws-cdk.md)
+ [使用 AWS CodePipeline 和 Amazon Bedrock 将 AWS Organizations 政策作为代码进行管理](manage-organizations-policies-as-code.md)
+ [将 DNS 记录批量迁移至 Amazon Route 53 私有托管区](migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone.md)
+ [使用 appcmd.exe 将 IIS 托管的应用程序迁移 EC2 到亚马逊](migrate-iis-hosted-applications-to-amazon-ec2-by-using-appcmd.md)
+ [监控多个共享的 Amazon 系统映像的使用情况 AWS 账户](monitor-use-of-a-shared-amazon-machine-image-across-multiple-aws-accounts.md)
+ [使用验证、转换和分区编排 ETL 管道 AWS Step Functions](orchestrate-an-etl-pipeline-with-validation-transformation-and-partitioning-using-aws-step-functions.md)
+ [使用 IaC 原则自动 blue/green 部署 Amazon Aurora 全球数据库](p-automate-blue-green-deployments-aurora-global-databases-iac.md)
+ [在非工作负载子网的多账户 VPC 设计中保留可路由的 IP 空间](preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets.md)
+ [使用代码存储库在中 AWS Service Catalog 配置 Terraform 产品](provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.md)
+ [从 AWS Step Functions 同步运行 AWS Systems Manager Automation 任务](run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions.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)
+ [使用 Terraform 为数据库迁移设置 CI/CD 管道](set-up-ci-cd-pipeline-for-db-migration-with-terraform.md)
+ [使用 Amazon 为 SQL Server Always On FCI 设置多可用区基础架构 FSx](set-up-multi-az-infrastructure-for-a-sql-server-always-on-fci-by-using-amazon-fsx.md)
+ [使用 AWS 在亚马逊 EC2 上自动设置 UiPath RPA 机器人 CloudFormation](set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.md)
+ [使用应用程序负载均衡器简化 Amazon ECS 中双向 TLS 的应用程序身份验证](simplify-application-authentication-with-mutual-tls-in-amazon-ecs.md)
+ [使用 C\$1 和 AWS CDK 在 SaaS 架构中为孤岛模型进行租户登录](tenant-onboarding-in-saas-architecture-for-the-silo-model-using-c-and-aws-cdk.md)
+ [使用 Terraform 自动 GuardDuty 为组织启用亚马逊](use-terraform-to-automatically-enable-amazon-guardduty-for-an-organization.md)
+ [使用 Amazon Bedrock 代理，通过基于文本的提示，在 Amazon EKS 中自动创建访问条目控制](using-amazon-bedrock-agents-to-automate-creation-of-access-entry-controls-in-amazon-eks.md)
+ [在本地验证 Account Factory for Terraform (AFT) 代码](validate-account-factory-for-terraform-aft-code-locally.md)
+ [使用 Flask 和 AWS Elastic Beanstalk 可视化 AI/ML 模型结果 AWS Beanstalk](visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk.md)

# Infrastructure
<a name="infrastructure-pattern-list"></a>

**Topics**
+ [使用会话管理器和 Amazon Instance Connect 访问堡垒主 EC2 机](access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.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)
+ [使用 Amazon CloudWatch 可观测性访问管理器进行集中监控](centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager.md)
+ [在启动时检查 EC2 实例是否有必需的标签](check-ec2-instances-for-mandatory-tags-at-launch.md)
+ [状态文件丢失后，安全地清 AWS 理 Terraform (AFT) 资源的 Account Factory](clean-up-aft-resources-safely-after-state-file-loss.md)
+ [在不支持 AWS 的 AWS 区域创建管道 CodePipeline](create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline.md)
+ [使用 AWS CDK 外观和逃生舱口自定义默认角色名称](customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches.md)
+ [使用私有静态在 Amazon EC2 上部署 Cassandra 集群 IPs 以避免重新平衡](deploy-a-cassandra-cluster-on-amazon-ec2-with-private-static-ips-to-avoid-rebalancing.md)
+ [使用 AWS Transit Gateway Connect 扩展 VRFs 到 AWS](extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.md)
+ [当 AWS KMS 密钥的密钥状态发生变化时获取 Amazon SNS 通知](get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes.md)
+ [在非工作负载子网的多账户 VPC 设计中保留可路由的 IP 空间](preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets.md)
+ [使用代码存储库在中 AWS Service Catalog 配置 Terraform 产品](provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.md)
+ [使用 Amazon AWS 账户 SES 使用一个电子邮件地址注册多个邮箱](register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses.md)
+ [在单账户 AWS 环境中为混合网络设置 DNS 解析](set-up-dns-resolution-for-hybrid-networks-in-a-single-account-aws-environment.md)
+ [使用 AWS 在亚马逊 EC2 上自动设置 UiPath RPA 机器人 CloudFormation](set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.md)
+ [在 AWS 上设置高度可用的 PeopleSoft 架构](set-up-a-highly-available-peoplesoft-architecture-on-aws.md)
+ [使用 AWS 弹性灾难恢复为 Oracle JD Edwar EnterpriseOne ds 设置灾难恢复](set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.md)
+ [在多区域、多账户组织中设置 CloudFormation 偏差检测](set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization.md)
+ [成功导入 S3 存储桶作为 AWS CloudFormation 堆栈](successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack.md)
+ [使用 AWS 在不同 AWS 区域的 Amazon EFS 文件系统之间同步数据 DataSync](synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync.md)
+ [使用 LocalStack 和 Terraform 测试来测试 AWS 基础架构](test-aws-infra-localstack-terraform.md)
+ [将 SAP Pacemaker 集群从升级到 ENSA1 ENSA2](upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2.md)
+ [在不同的 AWS 账户中 VPCs 使用一致的可用区](use-consistent-availability-zones-in-vpcs-across-different-aws-accounts.md)
+ [IDs 在 IAM 策略中使用用户进行访问控制和自动化](use-user-ids-iam-policies-access-control-automation.md)
+ [在本地验证 Account Factory for Terraform (AFT) 代码](validate-account-factory-for-terraform-aft-code-locally.md)
+ [更多模式](infrastructure-more-patterns-pattern-list.md)

# 使用会话管理器和 Amazon Instance Connect 访问堡垒主 EC2 机
<a name="access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect"></a>

*Piotr Chotkowski 和 Witold Kowalik，Amazon Web Services*

## Summary
<a name="access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-summary"></a>

*堡垒主机*（有时也称为*跳转盒*）是一种服务器，提供从外部网络到位于专用网络中的资源的单点访问。暴露在外部公共网络（如互联网）中的服务器会给未经授权的访问带来潜在的安全风险。保护和控制对这些服务器的访问非常重要。

此模式描述了如何使用[会话管理器](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html)和 [Amazon EC2 Instance Connect 安全地连接到](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Connect-using-EC2-Instance-Connect.html)部署在您的 AWS 账户中的亚马逊弹性计算云 (Amazon EC2) 堡垒主机。会话管理器是一项功能 AWS Systems Manager。此模式的优点包括：
+ 部署的堡垒主机没有任何向公共互联网公开的开放入站端口。这就减少了潜在的攻击面。
+ 您无需在中存储和维护长期安全外壳 (SSH) 密钥 AWS 账户。相反，每位用户每次连接到堡垒主机时都会生成一个新的 SSH key pair。 AWS Identity and Access Management 附加到用户 AWS 证书的 (IAM) 策略控制对堡垒主机的访问权限。

**目标受众**

这种模式适用于对亚马逊 EC2、亚马逊虚拟私有云（亚马逊 VPC）和 Hashicorp Terraform 有基本了解的读者。

## 先决条件和限制
<a name="access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ AWS Command Line Interface (AWS CLI) 版本 2，[已安装](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)并[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)
+ 的会话管理器插件 AWS CLI，[已安装](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html)
+ Terraform CLI，[已安装](https://developer.hashicorp.com/terraform/cli)
+ Terraform [状态](https://developer.hashicorp.com/terraform/language/state)的存储，例如充当远程后端来存储 Terraform 状态的 Amazon Simple Storage Service (Amazon S3) 桶和 Amazon DynamoDB 表。有关使用远程后端获得 Terraform 状态的更多信息，请参阅 [Amazon S3 后端](https://www.terraform.io/language/settings/backends/s3)（Terraform 文档）。有关使用 Amazon S3 后端设置远程状态管理的代码示例，请参阅 [remote-state-s3 后端](https://registry.terraform.io/modules/nozaq/remote-state-s3-backend/aws/latest)（Terraform Registry）。请注意以下要求：
  + Amazon S3 存储桶和 DynamoDB 表必须在同一个 AWS 区域中。
  + 创建 DynamoDB 表时，分区键必须为 `LockID`（区分大小写），并且分区键类型必须为 `String`。将所有其他设置保留为默认值。有关更多信息，请参阅 DynamoDB 文档中的[关于主键](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.CoreComponents.html#HowItWorks.CoreComponents.PrimaryKey)和[创建表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html)。
+ SSH 客户端，已安装

**限制**
+ 该模式旨在作为概念证明(PoC)，或作为进一步开发的基础。不得将其当前形式用于生产环境。在部署之前，请调整存储库中的示例代码以满足您的要求和用例。
+ 此模式假定目标堡垒主机使用 Amazon Linux 2 作为其操作系统。虽然可以使用其他 Amazon 系统映像 (AMIs)，但其他操作系统超出了这种模式的范围。
**注意**  
即将终止对 Amazon Linux 2 的支持。欲了解更多信息，请参阅[亚马逊 Linux 2 FAQs](https://aws.amazon.com/amazon-linux-2/faqs/)。
+ 在此模式中，堡垒主机位于没有 NAT 网关和互联网网关的私有子网中。这种设计将 Amazon EC2 实例与公共互联网隔离开来。您可以添加特定的网络配置，使其能够与互联网进行通信。有关更多信息，请参阅 Amazon VPC 文档中的[将虚拟私有云（VPC）连接到其他网络](https://docs.aws.amazon.com/vpc/latest/userguide/extend-intro.html)。同样，遵循[最低权限原则](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)， AWS 账户 除非您明确授予权限，否则堡垒主机无权访问您的任何其他资源。有关更多信息，请参阅 IAM 文档中的[基于资源的策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_resource-based)。

**产品版本**
+ AWS CLI 版本 2
+ Terraform 版本 1.3.9

## 架构
<a name="access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-architecture"></a>

**目标技术堆栈**
+ 具有单个私有子网的 VPC
+ 以下[接口 VPC 端点](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html)：
  + `amazonaws.<region>.ssm`— AWS Systems Manager 服务的终端节点。
  + `amazonaws.<region>.ec2messages` – Systems Manager 使用此端点从 SSM 代理调用到 Systems Manager 服务。
  + `amazonaws.<region>.ssmmessages`— 会话管理器使用此终端节点通过安全数据通道连接到您的 Amazon EC2 实例。
+ 运行`t3.nano`亚马逊 Linux 的亚马逊 EC2 实例 2
+ IAM 角色与实例配置文件
+ 终端节点和亚马逊 EC2 实例的 Amazon VPC 安全组和安全组规则

**目标架构**

![\[使用会话管理器访问堡垒主机的架构图。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/a02aed20-1852-4c91-902f-f553795006e2/images/819c503b-7eec-4a9c-862b-b87107d50dc1.png)


该图显示了以下过程：

1. 用户假定的 IAM 角色拥有执行以下操作的权限：
   + 对 Amazon EC2 实例进行身份验证、授权和连接
   + 使用会话管理器启动会话

1. 用户通过会话管理器启动 SSH 会话。

1. 会话管理器对用户进行身份验证，验证关联的 IAM policy 中的权限，检查配置设置，并向 SSM 代理发送消息以打开双向连接。

1. 用户通过 Amazon EC2 元数据将 SSH 公钥推送到堡垒主机。这必须在每次连接之前完成。SSH 公钥在 60 秒内保持可用。

1. 堡垒主机与 Systems Manager 和 Amazon 的接口 VPC 终端节点通信。 EC2

1. 用户使用 TLS 1.2 加密的双向通信通道通过会话管理器访问堡垒主机。

**自动化和扩缩**

以下选项可用于自动部署或扩缩此架构：
+ 您可以通过持续集成和持续交付（CI/CD）管道部署体系结构。
+ 您可以修改代码以更改堡垒主机的实例类型。
+ 您可以修改代码以部署多个堡垒主机。在 `bastion-host/main.tf` 文件的 `aws_instance` 资源块中，添加 `count` 元参数。有关更多信息，请参阅[ Terraform 文档](https://developer.hashicorp.com/terraform/language/meta-arguments/count)。

## 工具
<a name="access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-tools"></a>

**AWS 服务**
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您 AWS 服务 通过命令行 shell 中的命令进行交互。
+ [亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/ec2/) 在中提供可扩展的计算容量 AWS 云。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 可帮助您管理在 AWS 云端运行的应用程序和基础设施。它简化了应用程序和资源管理，缩短了检测和解决操作问题的时间，并帮助您大规模安全地管理 AWS 资源。此模式使用 [Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html)，这是 Systems Manager 的一项功能。
+ [Amazon Virtual Private Cloud（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。该虚拟网络类似于您在数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。

**其他工具**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款基础设施即代码（IaC）工具，可帮助您使用代码来预调配和管理云基础设施和资源。此模式使用 [Terraform CLI](https://developer.hashicorp.com/terraform/cli)。

**代码存储库**

此模式的代码可在[使用会话管理器 GitHub 访问堡垒主机和 Amazon EC2 Instance Connect](https://github.com/aws-samples/secured-bastion-host-terraform) 存储库中找到。

## 最佳实践
<a name="access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-best-practices"></a>
+ 我们建议使用自动代码扫描工具来提高代码的安全性和质量。使用 IaC 的静态代码分析工具 [Checkov](https://www.checkov.io/) 对该模式进行了扫描。我们至少建议您使用 `terraform validate` 和 `terraform fmt -check -recursive` Terraform 命令执行基本验证和格式检查。
+ 为 IaC 添加自动化测试是一种很好的做法。有关测试 Terraform 代码的不同方法的更多信息，请参阅[测试 Terraform（ HashiCorp Terraform 博客](https://www.hashicorp.com/blog/testing-hashicorp-terraform)文章）。
+ 在部署过程中，每次检测到新版本的亚马逊 [Linux 2 AMI 时，Terraform 都会使用替换的亚马逊 EC2 ](https://aws.amazon.com/marketplace/pp/prodview-zc4x2k7vt6rpu?sr=0-1&ref_=beagle&applicationId=AWSMPContessa)实例。这将部署新版本的操作系统，包括补丁和升级。如果未及时安排部署计划，可能会由于实例没有最新补丁而带来安全风险。经常更新已部署的 Amazon EC2 实例并对其应用安全补丁非常重要。有关更多信息，请参阅 [Amazon 中的更新管理 EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/update-management.html)。
+ 由于此模式是一种概念验证，因此它使用 AWS 托管策略，例如`AmazonSSMManagedInstanceCore`。 AWS 托管策略涵盖常见用例，但不授予最低权限权限。根据您的使用案例需要，我们建议您创建自定义策略，以便为此架构中部署的资源授予最低权限许可。有关更多信息，请参阅[开始使用 AWS 托管策略并转向最低权限权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-use-aws-defined-policies)。
+ 使用密码来保护对 SSH 密钥的访问，并将密钥存储在安全位置。
+ 为堡垒主机设置日志记录和监控。从操作和安全角度来看，日志和监控都是维护系统的重要组成部分。有多种方法可以监控堡垒主机中的连接和活动。有关更多信息，请参阅 Systems Manager 文档中的以下主题：
  + [监控 AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/monitoring.html)
  + [登录和监控 AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/logging-and-monitoring.html)
  + [审核会话活动](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-auditing.html)
  + [记录会话活动](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-logging.html)

## 操作说明
<a name="access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-epics"></a>

### 部署资源
<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/access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.html) | DevOps 工程师、开发人员 | 
| 初始化 Terraform 工作目录。 | 只有首次部署时才需要这一步骤。如果您要重新部署模式，请跳至下一步。在克隆存储库的根目录中，输入以下命令，其中：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.html)<pre>terraform init \<br />    -backend-config="bucket=$S3_STATE_BUCKET" \<br />    -backend-config="key=$PATH_TO_STATE_FILE" \<br />    -backend-config="region=$AWS_REGION</pre>您也可以打开 **config.tf** 文件，在 `terraform` 部分中手动填入这些值。 | DevOps 工程师、开发人员、Terraform | 
| 部署资源 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.html) | DevOps 工程师、开发人员、Terraform | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置 SSH 连接。 | 更新 SSH 配置文件，允许通过会话管理器进行 SSH 连接。有关说明，请参阅[会话管理器允许的 SSH 连接](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started-enable-ssh-connections.html#ssh-connections-enable)。这允许授权用户输入启动会话管理器会话并通过双向连接传输所有数据的代理命令。 | DevOps 工程师 | 
| 生成 SSH 密钥。 | 输入以下命令生成本地私密和公共 SSH 密钥对。您可使用此密钥对连接到堡垒主机。<pre>ssh-keygen -t rsa -f my_key</pre> | DevOps 工程师、开发人员 | 

### 使用会话管理器连接到堡垒主机
<a name="connect-to-the-bastion-host-by-using-sesh"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 获取实例 ID。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.html) | 常规 AWS | 
| 发送 SSH 公有密钥。 | 在本部分中，您需要将公有密钥上传到堡垒主机的[实例元数据](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html)中。上传密钥后，您有 60 秒的时间启动与堡垒主机的连接。60 秒后，公有密钥将被删除。有关更多信息，请参阅本模式的[疑难解答](#access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-troubleshooting)部分。快速完成后续步骤，以防止在连接到堡垒主机之前密钥被删除。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.html) | 常规 AWS | 
| 连接到堡垒主机。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.html)还有其他选项可用于打开与堡垒主机的 SSH 连接。有关更多信息，请参阅此模式的[其他信息](#access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-additional)部分中*与堡垒主机建立 SSH 连接的替代方法*。 | 常规 AWS | 

### (可选)清除
<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/access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.html) | DevOps 工程师、开发人员、Terraform | 

## 问题排查
<a name="access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 尝试连接到堡垒主机时出现 `TargetNotConnected` 错误 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect.html) | 
| 尝试连接到堡垒主机时出现 `Permission denied` 错误 | 将公有密钥上传到堡垒主机后，您只有 60 秒的时间来启动连接。60 秒后，密钥将自动删除，您将无法使用它连接到实例。如果发生这种情况，您可以重复该步骤以将密钥重新发送到实例。 | 

## 相关资源
<a name="access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-resources"></a>

**AWS 文档**
+ [AWS Systems Manager Session Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager.html)（Systems Manager 文档）
+ [安装 AWS CLI的会话管理器插件](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-working-with-install-plugin.html)（Systems Manager 文档）
+ [允许会话管理器的 SSH 连接](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started-enable-ssh-connections.html#ssh-connections-enable)（Systems Manager 文档）
+ [关于使用 Instan EC2 ce Connect](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Connect-using-EC2-Instance-Connect.html)（亚马逊 EC2 文档）
+ [使用 Instanc EC2 e Connect 进行连接](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-connect-methods.html)（亚马逊 EC2 文档）
+ 亚马逊@@ [的身份和访问管理 EC2（亚马逊](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-iam.html) EC2 文档）
+ [使用 IAM 角色向在 Amazon EC2 实例上运行的应用程序授予权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html)（IAM 文档）
+ [IAM 中的安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)（IAM 文档）
+ [使用安全组控制流量](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-security-groups.html)（Amazon VPC 文档）

**其他资源**
+ [Terraform 开发人员网页](https://developer.hashicorp.com/terraform)
+ [命令：验证](https://developer.hashicorp.com/terraform/cli/commands/validate)（Terraform 文档）
+ [命令：fmt](https://developer.hashicorp.com/terraform/cli/commands/fmt)（Terraform 文档）
+ [测试 HashiCorp Terraform](https://www.hashicorp.com/blog/testing-hashicorp-terraform)（HashiCorp 博客文章）
+ [Checkov 网页](https://www.checkov.io/)

## 附加信息
<a name="access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-additional"></a>

**与堡垒主机建立 SSH 连接的替代方法**

*端口转发*

您可以使用 `-D 8888` 选项打开具有动态端口转发的 SSH 连接。有关更多信息，请参阅 explainshell.com 上的[说明](https://explainshell.com/explain?cmd=ssh+-i+%24PRIVATE_KEY_FILE+-D+8888+ec2-user%40%24INSTANCE_ID)。以下是使用端口转发打开 SSH 连接的命令示例。

```
ssh -i $PRIVATE_KEY_FILE -D 8888 ec2-user@$INSTANCE_ID
```

此类连接会打开 SOCKS 代理，该代理可通过堡垒主机转发来自本地浏览器的流量。如果您使用的是 Linux 或 MacOS，要查看所有选项，请输入 `man ssh`。这将显示 SSH 参考手册。

*使用提供的脚本*

您可以使用代码存储库中包含的 **connect.sh** 脚本，无需手动运行[操作说明](#access-a-bastion-host-by-using-session-manager-and-amazon-ec2-instance-connect-epics)部分中*使用会话管理器连接到堡垒主机*中所描述的步骤。此脚本生成 SSH 密钥对，将公钥推送到 Amazon EC2 实例，并启动与堡垒主机的连接。运行脚本时，将标签和键名作为参数传递。以下是运行脚本的命令示例。

```
./connect.sh sandbox-dev-bastion-host my_key
```

# 使用本地微软 Active Direct AWS Managed Microsoft AD ory 集中解析 DNS
<a name="centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory"></a>

*Brian Westmoreland，Amazon Web Services*

## Summary
<a name="centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory-summary"></a>

此模式为同时使用 AWS Directory Service for Microsoft Active Directory (AWS Managed Microsoft AD) 和 Amazon Route 53 在 AWS 多账户环境中集中 DNS 解析提供了指导。在这种模式中， AWS DNS 命名空间是本地 DNS 命名空间的子域。此模式还提供了有关如何将本地 DNS 服务器配置为在本地 DNS 解决方案使用 Microsoft Active Directory AWS 时将查询转发到的指导。 

## 先决条件和限制
<a name="centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory-prereqs"></a>

**先决条件**
+ 使用 AWS Organizations设置的 AWS 多账户环境。
+ 之间已建立网络连接 AWS 账户。
+ 在 AWS 和本地环境之间建立网络连接（通过使用 AWS Direct Connect 或任何类型的 VPN 连接）。
+ AWS Command Line Interface (AWS CLI) 在本地工作站上配置。
+ AWS Resource Access Manager (AWS RAM) 用于在账户之间共享 Route 53 规则。因此，必须在 AWS Organizations 环境中启用共享，如长[篇故事](#centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory-epics)部分所述。

**限制**
+ AWS Managed Microsoft AD 标准版的股票上限为 5 股。
+ AWS Managed Microsoft AD 企业版的股票上限为 125 股。
+ 这种模式下的解决方案仅限于通过 AWS 区域 该支持共享 AWS RAM。

**产品版本**
+ 在 Windows Server 2008、2012、2012 R2 或 2016 上运行的 Microsoft Active Directory。

## 架构
<a name="centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory-architecture"></a>

**目标架构**

![\[AWS 上的集中式 DNS 解析的架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/91430e2a-f7f6-4dbe-9fe7-8abed1f764a7/images/9b5fc51d-590b-468f-80f7-1949f3b3b258.png)


在此设计中 AWS Managed Microsoft AD ，安装在共享服务中 AWS 账户。尽管这不是必需的，但该模式假定了这种配置。如果您以不同的 AWS Managed Microsoft AD 方式进行配置 AWS 账户，则可能需要相应地修改 [Epics](#centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory-epics) 部分中的步骤。

此设计使用 Route 53 解析器，通过使用 Route 53 规则来支持名称解析。如果本地 DNS 解决方案使用 Microsoft DNS，则为 AWS 命名空间 (`aws.company.com`)（公司 DNS 命名空间 (`company.com`) 的子域）创建条件转发规则并不简单。如果您尝试创建传统的条件转发器，将会导致错误。这是因为 Microsoft Active Directory 已经被认为对的任何 `company.com` 子域具有权威性。要解决此错误，必须首先为创建一个 `aws.company.com` 委托，委托该命名空间的权限。然后，您可创建条件转发器。

每个分支账户的虚拟私有云 (VPC) 可以根据根命名空间拥有自己的唯一 DNS AWS 命名空间。在此设计中，每个分支账户将账户名称的缩写附加到基本 AWS 命名空间。在分支账户中创建私有托管区域后，这些区域将与分支账户中的本地 VPC 以及中央 AWS 网络账户中的 VPC 相关联。这样，中央 AWS 网络账户就可以回答与分支账户相关的 DNS 查询。这样，Route 53 和 Route 就可以 AWS Managed Microsoft AD 共同承担管理 AWS 命名空间 (`aws.company.com`) 的责任。

**自动化和扩展**

此设计使用 Route 53 解析器端点在本地环境 AWS 之间扩展 DNS 查询。每个 Route 53 Resolver 端点包含多个弹性网络接口（分布在多个可用区），每个网络接口每秒最多可处理 10,000 个查询。Route 53 解析器支持每个端点最多 6 个 IP 地址，因此该设计总共支持每秒多达 60,000 个 DNS 查询，分布在多个可用区中，以实现高可用性。 

此外，这种模式自动考虑了 AWS未来增长。无需修改本地配置的 DNS 转发规则，即可支持新增的私有托管区域 VPCs 及其关联的私有托管区域 AWS。 

## 工具
<a name="centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory-tools"></a>

**AWS 服务**
+ [AWS Directory Service for Microsoft Active Directory](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/directory_microsoft_ad.html)允许你的目录感知工作负载和 AWS 资源使用中的 Microsoft Active Directory。 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 Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一种可用性高、可扩展性强的 DNS Web 服务。

**工具**
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您 AWS 服务 通过命令行外壳中的命令进行交互。在此模式中， AWS CLI 用于配置 Route 53 授权。

## 操作说明
<a name="centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory-epics"></a>

### 创建和共享 AWS Managed Microsoft AD 目录
<a name="create-and-share-an-managed-ad-directory"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 AWS Managed Microsoft AD。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory.html) | AWS 管理员 | 
| 共享您的目录。 | 建立目录后，与 AWS 组织 AWS 账户 中的其他人共享。有关说明，请参阅 *AWS Directory Service 管理指南*中的[共享目录](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step2_share_directory.html)。 AWS Managed Microsoft AD 标准版的股票上限为 5 股。 企业版的股票上限为 125 股。 | AWS 管理员 | 

### 配置 Route 53
<a name="configure-r53"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Route 53 解析器。 | Route 53 解析器简化了本地数据中心 AWS 之间的 DNS 查询解析。 [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory.html)尽管不需要使用中央 AWS 网络账户 VPC，但其余步骤假设此配置。 | AWS 管理员 | 
| 创建 Route 53 规则。 | 您的特定使用案例可能需要大量 Route 53 规则，但您需要配置以下规则作为基准：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory.html)有关更多信息，请参阅 *Route 53 开发人员指南*中的[托管转发规则](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-rules-managing.html)。 | AWS 管理员 | 
| 配置 Route 53 配置文件。 | Route 53 配置文件用于与分支账户共享规则。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory.html) | AWS 管理员 | 

### 配置本地 Active Directory DNS
<a name="configure-on-premises-active-directory-dns"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建委托。 | 使用 Microsoft DNS 管理单元 (`dnsmgmt.msc`) 在 Active Directory 中为 `company.com` 命名空间创建新的委托。委托域的名称应为 `aws`。这使得 `aws.company.com` 委托的完全限定域名 (FQDN) 成为可能。使用 AWS Managed Microsoft AD 域控制器的 IP 地址作为名称服务器 IP 值，并使用`server.aws.company.com`作为名称。（此委托仅用于冗余，因为将为此命名空间创建一个优先于委托的条件转发器。） | Active Directory | 
| 创建条件转发器。 | 使用 Microsoft DNS 管理单元 (`dnsmgmt.msc`) 为 `aws.company.com` 创建新条件转发器。 使用中央 DNS 中 AWS 入站 Route 53 解析器的 IP 地址 AWS 账户 作为条件转发器的目标。   | Active Directory | 

### 为辐条创建 Route 53 私有托管区域 AWS 账户
<a name="create-r53-private-hosted-zones-for-spoke-aws-accounts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Route 53 私有托管区： | 在每个分支账户中创建 Route 53 私有托管区域。将此私有托管区域与分支账户 VPC 相关联。有关详细步骤，请参阅 *Route 53 开发人员指南*中的[创建私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zone-private-creating.html)。 | AWS 管理员 | 
| 创建授权。 | 使用 AWS CLI 为中央 AWS 网络账户 VPC 创建授权。在每个分支 AWS 账户的上下文运行以下命令：<pre>aws route53 create-vpc-association-authorization --hosted-zone-id <hosted-zone-id> \<br />   --vpc VPCRegion=<region>,VPCId=<vpc-id></pre>其中：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory.html) | AWS 管理员 | 
| 创建关联。 | 使用为中央 AWS 网络账户 VPC 创建 Route 53 私有托管区域关联 AWS CLI。在中央 AWS 网络帐户的上下文中运行以下命令：<pre>aws route53 associate-vpc-with-hosted-zone --hosted-zone-id <hosted-zone-id> \<br />   --vpc VPCRegion=<region>,VPCId=<vpc-id></pre>其中：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory.html) | AWS 管理员 | 

## 相关资源
<a name="centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory-resources"></a>
+ [使用 Route 53 解析器简化多账户环境中的 DNS 管理](https://aws.amazon.com/blogs/security/simplify-dns-management-in-a-multiaccount-environment-with-route-53-resolver/)（AWS 博客文章）
+ [创建你的 AWS Managed Microsoft AD](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_getting_started_create_directory.html)（AWS Directory Service 文档）
+ [共享 AWS Managed Microsoft AD 目录](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/step2_share_directory.html)（AWS Directory Service 文档）
+ [什么是 Amazon Route 53 Resolver？](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver.html) （Amazon Route 53 文档）
+ [创建私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zone-private-creating.html)（Amazon Route 53 文档）
+ [Amazon Route 53 Profiles 是什么？](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/profiles.html) （Amazon Route 53 文档）

# 使用 Amazon CloudWatch 可观测性访问管理器进行集中监控
<a name="centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager"></a>

*Anand Krishna Varanasi、JAGDISH KOMAKULA、Ashish Kumar、Jimmy Morgan、Sarat Chandra Pothula、Vivek Thangamuthu 和 Balaji Vedagiri，Amazon Web Services*

## Summary
<a name="centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager-summary"></a>

可观测性对于监控、理解应用程序和排除应用程序故障至关重要。跨多个账户的应用程序（如 AWS Control Tower 或 landing zone 实现）会生成大量日志和跟踪数据。为了快速解决问题或了解用户分析或业务分析，您需要一个跨所有账户的通用可观测性平台。Amazon CloudWatch Observability 访问管理器允许您从一个中心位置访问和控制多个账户日志。

您可使用可观测性访问管理器来查看和管理源账户生成的可观测性数据日志。源账户是为其资源生成 AWS 账户 可观测性数据的个人。源账户与监控账户共享其可观测性数据。共享的可观察性数据可以包括 Amazon 中的指标 CloudWatch、Amazon 日志中的 CloudWatch 日志以及中的 AWS X-Ray跟踪。有关更多信息，请参阅 [Observability Access Manager 文档](https://docs.aws.amazon.com/OAM/latest/APIReference/Welcome.html)。

这种模式适用于拥有多个应用程序或基础架构 AWS 账户 并需要在公共位置查看日志的用户。它解释了如何使用 Terraform 设置 Observability Access Manager，以监控这些应用程序或基础设施的状态和运行状况。您可以通过多种方式安装此解决方案：
+ 作为您手动设置的独立 Terraform 模块
+ 通过使用持续集成和持续交付（CI/CD）管道
+ 通过与 [AWS Control Tower Account Factory for Terraform（AFT）](https://docs.aws.amazon.com/controltower/latest/userguide/aft-overview.html)等其他解决方案集成

[操作说明](#centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager-epics)部分中的说明涵盖了手动实现。有关 AFT 的安装步骤，请参阅 Obs GitHub [ervability Access Manager 存储库](https://github.com/aws-samples/cloudwatch-obervability-access-manager-terraform)的自述文件。

## 先决条件和限制
<a name="centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager-prereqs"></a>

**先决条件**
+ 在您的系统或自动管道中安装或引用 [Terraform](https://www.terraform.io/)。（我们建议您使用[最新版本](https://releases.hashicorp.com/terraform/)。）
+ 可用作中央监控账户的账户。其他账户创建到中央监控账户的链接以便查看日志。
+ （可选）源代码存储库，例如 GitHub、 AWS CodeCommit、Atlassian Bitbucket 或类似系统。如果您使用的是自动 CI/CD 流水线，则不需要源代码存储库。
+ （可选）在中创建用于代码审查和代码协作的拉取请求 (PRs) 的权限 GitHub。

**限制**

Observability Access Manager 具有以下服务限额，且该限额不可更改。部署此功能之前，请考虑这些配额。有关更多信息，请参阅 CloudWatch 文档中的[CloudWatch 服务配额](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_limits.html)。
+ **源账户关联**：您最多可以将每个源账户关联到五个监控账户。
+ **S** ink AWS 区域 s：您可以为一个账户构建多个接收器，但每个账户只允许生成一个接收器。

此外：
+ 汇和链接必须在同一位置创建 AWS 区域；它们不能是跨区域的。

**跨区域和跨账户监控**

对于跨区域、跨账户监控，您可以选择下列选项之一：
+ 为警报[和指标创建跨账户和跨区域 CloudWatch 仪表板](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Cross-Account-Cross-Region.html)。此选项不支持日志和跟踪。
+ 使用 Amazon OpenSearch 服务实现[集中日志](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Cross-Account-Cross-Region.html)。
+ 从所有租户账户中为每个区域创建一个接收器，将指标推送到集中式监控账户（如本模式中所述），然后使用[CloudWatch 指标流](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Metric-Streams.html)将数据发送到公共外部目标或第三方监控产品，例如 Datadog、Dynatrace、Sumo Logic、Splunk 或 New Relic。

## 架构
<a name="centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager-architecture"></a>

**组件**

CloudWatch Observability Access Manager 由两个主要组件组成，可实现跨账户可观察性：
+ *接收器*使源账户能够将可观测性数据发送到中央监控账户。接收器基本上为源账户提供了一个连接的网关连接。只能有一个接收器网关或连接，并且可以有多个账户连接到它。
+ 每个源账户都有一个到接收器网关连接的*链接*，可观测性数据通过此链接发送。必须先创建接收器，然后才能从每个源账户创建链接。

**架构**

下图说明了 Observability Access Manager 及其组件。

![\[带有接收器和链接的跨账户可观测性架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/00603763-4f99-456e-85e7-a80d803b087d/images/5188caf9-348b-4d91-b560-2b3d6ea81191.png)


## 工具
<a name="centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager-tools"></a>

**AWS 服务**
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可帮助您实时监控您的 AWS 资源和运行的应用程序 AWS 的指标。
+ [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)是一项账户管理服务，可帮助您将多个账户整合 AWS 账户 到一个由您创建和集中管理的组织中。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。

**工具**
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。
+ AWS Control Tower Account F@@ [actory for Terraform (AFT) 设置了 Terraform 管道来帮助你在中配置和自定义账户](https://docs.aws.amazon.com/controltower/latest/userguide/aft-overview.html)。 AWS Control Tower您可以选择使用 AFT 跨多个账户大规模设置 Observability Access Manager。

**代码存储库**

此模式的代码可在 Obs GitHub [ervability 访问管理器](https://github.com/aws-samples/cloudwatch-obervability-access-manager-terraform)存储库中找到。

## 最佳实践
<a name="centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager-best-practices"></a>
+ 在 AWS Control Tower 环境中，将日志帐户标记为中央监控帐户（接收器）。
+ 如果您有多个组织中有多个账户 AWS Organizations，我们建议您在配置策略中加入组织而不是个人账户。如果您的账户数量较少，或者这些账户不属于接收器配置策略中的组织，则您可能会决定包含个人账户。

## 操作说明
<a name="centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager-epics"></a>

### 设置接收器模块
<a name="set-up-the-sink-module"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 克隆 GitHub 可观测性访问管理器存储库：<pre>git clone https://github.com/aws-samples/cloudwatch-obervability-access-manager-terraform</pre> | AWS DevOps、云管理员、AWS 管理员 | 
| 为接收器模块指定属性值。 | 在 `main.tf` 文件中 (在存储库的 `deployments/aft-account-customizations/LOGGING/terraform/` ****文件夹中)，为以下属性指定值：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager.html)有关更多信息，请参阅 CloudFormation 文档[AWS::Oam::Sink](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-oam-sink.html)中的。 | AWS DevOps、云管理员、AWS 管理员 | 
| 安装接收器模块。 | 导出您选择作为监控账户的凭据 AWS 账户 ，然后安装 Observability Access Manager 接收器模块：<pre>Terraform Init<br />Terrafom Plan<br />Terraform Apply</pre> | AWS DevOps、云管理员、AWS 管理员 | 

### 设置链接模块
<a name="set-up-the-link-module"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为链接模块指定属性值。 | 在 `main.tf ` 文件中（在存储库的 `deployments/aft-account-customizations/LOGGING/terraform/` ****文件夹中），为以下属性指定值：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager.html)有关更多信息，请参阅 CloudFormation 文档[AWS::Oam::Link](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-oam-link.html)中的。 | AWS DevOps、云管理员、云架构师 | 
| 为个人账户安装链接模块。 | 导出个人账户凭证，并安装 Observability 访问管理器链接模块：<pre>Terraform Plan<br />Terraform Apply</pre>您可为每个账户单独设置链接模块，也可以使用 [AFT](https://docs.aws.amazon.com/controltower/latest/userguide/aft-overview.html) 在大量账户中自动安装此模块。 | AWS DevOps、云管理员、云架构师 | 

### 批准 sink-to-link连接
<a name="approve-sink-to-link-connections"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 状态消息。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager.html)在右侧，您应该会看到带有绿色勾号的**监控账户已启用**状态消息。这意味着监控账户有一个 Observability Access Manager 接收器，其他账户的链接将连接到该接收器。 |  | 
| 批准 link-to-sink连接。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager.html)有关更多信息，请参阅 CloudWatch 文档中的[将监控账户与源账户关联起来](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account-Setup.html)。 | AWS DevOps、云管理员、云架构师 | 

### 验证跨账户可观测性数据
<a name="verify-cross-account-observability-data"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看跨账户数据。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager.html) | AWS DevOps、云管理员、云架构师 | 

### （可选）允许源账户信任监控账户
<a name="optional-enable-source-accounts-to-trust-monitoring-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看其他账户的指标、控制面板、日志、小部件和警报。 | 作为一项附加功能，****您可以与其他账户共享 CloudWatch 指标、仪表板、日志、小组件和警报。每个账户都使用名为 **CloudWatch-** 的 IAM 角色CrossAccountSharingRole 来访问这些数据。与中央监控账户有信任关系的源账户可以承担该角色并查看监控账户的数据。CloudWatch 提供了用于创建角色的示例 CloudFormation 脚本。选择**管理 IAM 角色**，然后在要查看数据的账户中运行此脚本。<pre>{<br />    "Version": "2012-10-17",		 	 	 <br />    "Statement": [<br />        {<br />            "Effect": "Allow",<br />            "Principal": {<br />                "AWS": [<br />                    "arn:aws:iam::XXXXXXXXX:root",<br />                    "arn:aws:iam::XXXXXXXXX:root",<br />                    "arn:aws:iam::XXXXXXXXX:root",<br />                    "arn:aws:iam::XXXXXXXXX:root"<br />                ]<br />            },<br />            "Action": "sts:AssumeRole"<br />        }<br />    ]<br />}</pre>有关更多信息，请参阅 CloudWatch 文档[ CloudWatch中的启用跨账户功能](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Cross-Account-Cross-Region.html#enable-cross-account-cross-Region)。 | AWS DevOps、云管理员、云架构师 | 

### （可选）从监控账户查看跨账户跨 Region
<a name="optional-view-cross-account-cross-region-from-the-monitoring-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置跨账户、跨区域访问。 | 在中央监控账户中，您可以选择添加账户选择器，以便在账户之间轻松切换并查看其数据，而无需进行身份验证。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager.html)有关更多信息，请参阅文档中的[跨账户跨区域 CloudWatch 控制台](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/Cross-Account-Cross-Region.html)。 CloudWatch  | AWS DevOps、云管理员、云架构师 | 

## 相关资源
<a name="centralize-monitoring-by-using-amazon-cloudwatch-observability-access-manager-resources"></a>
+ [CloudWatch 跨账户可观察性](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch-Unified-Cross-Account.html)（Ama CloudWatch zon 文档）
+ [亚马逊 CloudWatch 可观察性访问管理器 API 参考](https://docs.aws.amazon.com/OAM/latest/APIReference/Welcome.html)（亚马逊 CloudWatch 文档）
+ [资源：aws\$1oam\$1sink](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/oam_sink)（Terraform 文档）
+ [数据来源：aws\$1oam\$1link](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/oam_link)（Terraform 文档）
+ [CloudWatchObservabilityAccessManager](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/oam.html)（AWS Boto3 文档）

# 在启动时检查 EC2 实例是否有必需的标签
<a name="check-ec2-instances-for-mandatory-tags-at-launch"></a>

*Susanne Kangnoh 和 Archit Mathur，Amazon Web Services*

## Summary
<a name="check-ec2-instances-for-mandatory-tags-at-launch-summary"></a>

亚马逊弹性计算云 (Amazon EC2) 在亚马逊网络服务 (AWS) 云中提供可扩展的计算容量。使用 Amazon，您 EC2 无需预先投资硬件，因此您可以更快地开发和部署应用程序。

您可以使用标签以不同的方式对您的 AWS 资源进行分类。 EC2 当您的账户中有许多资源并且想要根据标签快速识别特定资源时，实例标记非常有用。您可以使用标签为 EC2 实例分配自定义元数据。每个标签都由用户定义的键和值组成。我们建议您创建一组一致的标签以满足您的组织要求。 

此模式提供了一个 AWS CloudFormation 模板来帮助您监控 EC2 实例中是否存在特定标签。该模板创建一个 Amazon Events CloudWatch 事件，用于监视 AWS CloudTrail **TagResource**或**UntagResource**事件，以检测新的 EC2 实例标记或标签移除。如果缺少预定义标签，它会调用 AWS Lambda 函数，该函数会使用 Amazon Simple Notiﬁcation Service (Amazon SNS) 向您提供的电子邮件地址发送违规消息。 

## 先决条件和限制
<a name="check-ec2-instances-for-mandatory-tags-at-launch-prerequisites-and-limitations"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account。
+ 用于上传提供的 Lambda 代码的 Amazon Simple Storage Service （Amazon S3）存储桶。
+ 您希望接收违规通知的电子邮件地址。

**限制**
+ 此解决方案支持 CloudTrail **TagResource**或**UntagResource**活动。它不会为任何其他事件创建通知。
+ 此解决方案仅检查标签键。它并不监视键值。

## 架构
<a name="check-ec2-instances-for-mandatory-tags-at-launch-architecture"></a>

**工作流程****架构**

![\[Workflow diagram showing AWS 服务 interaction for EC2 instance monitoring and notification.\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/9cd74141-a87f-419e-94b3-0b28fd04a018/images/b48fd21b-a86b-4ec7-b9f6-4f1a64999437.png)


 

**自动化和扩展**
+ 您可以针对不同的 AWS 区域和账户多次使用 AWS CloudFormation 模板。您只需在每个区域或账户中运行该模板一次。

## 工具
<a name="check-ec2-instances-for-mandatory-tags-at-launch-tools"></a>

**AWS 服务**
+ [亚马逊 EC2](https://aws.amazon.com/ec2/) — Amazon Elastic Compute Cloud (Amazon EC2) 是一项网络服务，可在云中提供安全、可调整大小的计算容量。该服务旨在降低开发人员进行网络规模级云计算的难度。
+ [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) — CloudTrail 是一项 AWS 服务，可帮助您对 AWS 账户进行治理、合规以及运营和风险审计。用户、角色或 AWS 服务采取的操作在中记录为事件 CloudTrail。 
+ [Amazon CloudWatch ](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/WhatIsCloudWatchEvents.html) Events — Amazon CloudWatch Events 提供近乎实时的系统事件流，这些事件描述了 AWS 资源的变化。 CloudWatch 通过发送消息以响应环境、激活功能、进行更改和捕获状态信息，事件会在操作变化发生时意识到这些变化，并在必要时采取纠正措施。 
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) — AWS Lambda 是一项计算服务，使您无需预置或管理服务器即可运行代码。只有在需要时 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 服务，可让应用程序、终端用户和设备即时发送和接收来自云端的通知。

**代码**

此模式包括一个包含两个文件的附件：
+ `index.zip` 是压缩文件，其中包含此模式的 Lambda 代码。
+ `ec2-require-tags.yaml`是部署 Lambda 代码的 CloudFormation 模板。

有关如何使用这些文件的信息，请参阅*操作说明*部分。

## 操作说明
<a name="check-ec2-instances-for-mandatory-tags-at-launch-epics"></a>

### 部署 Lambda 代码
<a name="deploy-the-lambda-code"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将代码上传到 S3 存储桶。 | 创建新的 S3 存储桶或使用现有 S3 存储桶上传附加的 `index.zip` 文件（Lambda 代码）。此存储桶必须与您要监控的资源（EC2 实例）位于同一 AWS 区域。 | 云架构师 | 
| 部署 CloudFormation 模板。 | 在与 S3 存储桶相同的 AWS 区域中打开 Cloudformation 控制台，然后部署附件中提供的 `ec2-require-tags.yaml` 文件。在下一个操作说明中，提供模板参数的值。  | 云架构师 | 

### 填写 CloudFormation 模板中的参数
<a name="complete-the-parameters-in-the-cloudformation-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 提供 S3 存储桶名称。 | 输入您在第一篇操作说明中创建或选择的 S3 存储桶的名称。此 S3 存储桶包含 Lambda 代码的.zip 文件，并且必须与模板和 EC2 要监控 CloudFormation 的实例位于相同的 AWS 区域。 | 云架构师 | 
| 提供 S3 密钥。 | 提供 Lambda 代码 .zip 文件在 S3 存储桶中的位置，不带前导斜杠（例如，`index.zip` 或 `controls/index.zip`）。 | 云架构师 | 
| 提供电子邮箱地址。 | 提供要接收违规通知的活动电子邮件地址。 | 云架构师 | 
| 定义日志记录级别。 | 指定日志记录级别和详细程度。`Info` 指定有关应用程序进度的详细信息消息，应仅用于调试。`Error` 指定仍允许应用程序继续运行的错误事件。`Warning` 表示潜在的有害情况。 | 云架构师 | 
| 输入所需标签密钥。 | 输入要检查的标签键。如果要指定多个密钥，请用逗号分隔，不要使用空格。（例如，`ApplicationId,CreatedBy,Environment,Organization` 搜索四个密钥。） Events CloudWatch 事件搜索这些标签密钥，如果找不到则发送通知。 | 云架构师 | 

### 确认订阅
<a name="confirm-the-subscription"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确认电子邮件订阅。 | 成功部署 CloudFormation 模板后，它会向您提供的电子邮件地址发送一封订阅电子邮件。要接收通知，您必须确认此电子邮件订阅。  | 云架构师 | 

## 相关资源
<a name="check-ec2-instances-for-mandatory-tags-at-launch-related-resources"></a>
+ [创建存储桶](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/create-bucket.html)（Amazon S3 文档）
+ [上传对象](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/upload-objects.html)（Amazon S3 文档）
+ [标记您的亚马逊 EC2 资源](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_Tags.html)（亚马逊 EC2 文档）
+ 使用 [AWS 创建在 AWS API 调用时触发 CloudWatch 的事件规则 CloudTrail](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/Create-CloudWatch-Events-CloudTrail-Rule.html)（亚马逊 CloudWatch 文档）

## 附件
<a name="attachments-9cd74141-a87f-419e-94b3-0b28fd04a018"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/9cd74141-a87f-419e-94b3-0b28fd04a018/attachments/attachment.zip)

# 状态文件丢失后，安全地清 AWS 理 Terraform (AFT) 资源的 Account Factory
<a name="clean-up-aft-resources-safely-after-state-file-loss"></a>

*Gokendra Malviya，Amazon Web Services*

## Summary
<a name="clean-up-aft-resources-safely-after-state-file-loss-summary"></a>

当你使用 Acco AWS unt Factory for Terraform (AFT) 管理 AWS Control Tower 环境时，AFT 会生成一个 Terraform 状态文件来跟踪 Terraform 创建的资源的状态和配置。丢失 Terraform 状态文件可能会给资源管理和清理带来重大挑战。这种模式提供了一种系统的方法，可以在保持环境完整性的同时，安全地识别和移除 AFT 相关资源。 AWS Control Tower 

此过程旨在确保正确移除所有 AFT 组件，即使没有原始状态文件参考亦是如此。此过程为在您的环境中成功重新建立和重新配置 AFT 提供了明确的途径，有助于确保最大限度地减少对运营的干扰。 AWS Control Tower 

有关 AFT 的更多信息，请参阅 [AWS Control Tower 文档](https://docs.aws.amazon.com/controltower/latest/userguide/taf-account-provisioning.html)。

## 先决条件和限制
<a name="clean-up-aft-resources-safely-after-state-file-loss-prereqs"></a>

**先决条件**
+ 深入了解 [AFT 架构](https://docs.aws.amazon.com/controltower/latest/userguide/aft-architecture.html)。
+ 对以下账户的管理员访问权限：
  + AFT 管理账户
  + AWS Control Tower 管理账户
  + 日志存档账户
  + 审计账户
+ 验证没有任何服务控制策略 (SCPs) 包含会阻止删除 AFT 相关资源的限制或限制。

**限制**
+ 此过程可以有效地清理资源，但无法恢复丢失的状态文件，并且某些资源可能需要手动识别。
+ 清理过程的持续时间取决于环境的复杂性，可能需要几个小时。
+ 此模式已在 AFT 版本 1.12.2 中进行了测试，并删除了以下资源。如果您使用的是其他版本的 AFT，则可能需要删除其他资源。    
[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html)

**重要**  
按照此模式中的步骤删除的资源无法恢复。在执行这些步骤之前，请仔细验证资源名称并确认它们是由 AFT 创建的。

## 架构
<a name="clean-up-aft-resources-safely-after-state-file-loss-architecture"></a>

下图显示了 AFT 组件和高级工作流。AFT 设置了一个 Terraform 管道，可帮助您在 AWS Control Tower中预调配和自定义您的账户。AFT 遵循一种 GitOps 模型来实现账户配置过程的自动化 AWS Control Tower。借助 AFT，您可以创建一个账户请求 Terraform 文件，以获取触发 AFT 账户预调配工作流的输入。账户预调配完成后，AFT 可以自动运行其他自定义步骤。

![\[AFT 组件和高级工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/1342c0a6-4b07-46df-a063-ceab2e2f83c8/images/3e0cae87-20ef-4fcc-aacf-bb450844ac56.png)


在此架构中：
+ **AWS Control Tower 管理账户**是专用于 AWS 账户 该 AWS Control Tower 服务的账户。这通常也称为 *AWS 付款人账户*或 *AWS Organizations 管理账户*。
+ **AFT 管理账户**是专门用 AWS 账户 于 AFT 管理操作的账户。这与企业的管理账户不同。
+ **Vended 账户** AWS 账户 包含您选择的所有基准组件和控件。AFT AWS Control Tower 用来出售一个新账户。

有关此架构的更多信息，请参阅 AWS Control Tower 研讨会中的 [AFT 简介](https://catalog.workshops.aws/control-tower/en-US/customization/aft)。

## 工具
<a name="clean-up-aft-resources-safely-after-state-file-loss-tools"></a>

**AWS 服务**
+ [AWS Control Tower](https://docs.aws.amazon.com/controltower/latest/userguide/what-is-control-tower.html)按照规范性最佳实践，帮助您设置和管理 AWS 多账户环境。
+ AWS A@@ [ccount Factory for Terraform (AFT)](https://docs.aws.amazon.com/controltower/latest/userguide/taf-account-provisioning.html) 设置了 Terraform 管道，以帮助你在中配置和自定义账户和资源。 AWS Control Tower
+ [AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_introduction.html)随着 AWS 资源的增长和扩展，可以帮助你集中管理和治理环境。通过使用 Organizations，您可以创建账户并分配资源，对账户进行分组以组织工作流，应用策略以满足治理的需要，并通过对所有账户使用统一的付款方式来简化账单。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。此模式需要 IAM 角色和权限。

**其他工具**
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。

## 最佳实践
<a name="clean-up-aft-resources-safely-after-state-file-loss-best-practices"></a>
+ 有关 AWS Control Tower信息，请参阅 AWS Control Tower 文档中的[AWS Control Tower 管理员最佳实践](https://docs.aws.amazon.com/controltower/latest/userguide/best-practices.html)。
+ 有关 IAM 的信息，请参阅 IAM 文档中的[安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)。

## 操作说明
<a name="clean-up-aft-resources-safely-after-state-file-loss-epics"></a>

### 删除 AFT 管理账户中的 AFT 资源
<a name="delete-aft-resources-in-the-aft-management-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除由 AFT 标签标识的资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | AWS 管理员、AWS DevOps、 DevOps 工程师 | 
| 删除 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | AWS 管理员、AWS DevOps、 DevOps 工程师 | 
| 删除 AWS Backup 备份存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | AWS 管理员、AWS DevOps、 DevOps 工程师 | 
| 删除 Amazon CloudWatch 资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | AWS 管理员、AWS DevOps、 DevOps 工程师 | 
| 删除 AWS KMS 资源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | AWS 管理员、AWS DevOps、 DevOps 工程师 | 

### 删除日志存档账户中的 AFT 资源
<a name="delete-aft-resources-in-the-log-archive-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除 S3 存储桶。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | AWS 管理员、AWS DevOps、 DevOps 工程师 | 
| 删除 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | AWS 管理员、AWS DevOps、 DevOps 工程师 | 

### 删除审计账户中的 AFT 资源
<a name="delete-aft-resources-in-the-audit-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | AWS 管理员、AWS DevOps、 DevOps 工程师 | 

### 删除 AWS Control Tower 管理账户中的 AFT 资源
<a name="delete-aft-resources-in-the-ctower-management-account"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | AWS 管理员、AWS DevOps、 DevOps 工程师 | 
| 删除 EventBridge 规则。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | AWS 管理员、AWS DevOps、 DevOps 工程师 | 

## 问题排查
<a name="clean-up-aft-resources-safely-after-state-file-loss-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 断开互联网网关失败。 | 在删除由 **AFT** 标签标识的资源时，如果在断开或删除互联网网关时遇到此问题，则必须先删除 VPC 端点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | 
| 您找不到指定的 CloudWatch 查询。 | 如果您找不到 AFT 创建的 CloudWatch 查询，请按照以下步骤操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/clean-up-aft-resources-safely-after-state-file-loss.html) | 

## 相关资源
<a name="clean-up-aft-resources-safely-after-state-file-loss-resources"></a>
+ AFT：
  + [GitHub 存储库](https://github.com/aws-ia/terraform-aws-control_tower_account_factory)
  + [工作坊](https://catalog.workshops.aws/control-tower/en-US/customization/aft)
  + [文档](https://docs.aws.amazon.com/controltower/latest/userguide/aft-getting-started.html)
+ [AWS Control Tower 文档](https://docs.aws.amazon.com/controltower/latest/userguide/getting-started-with-control-tower.html)

## 附加信息
<a name="clean-up-aft-resources-safely-after-state-file-loss-additional"></a>

要在 L CloudWatch ogs Insights 控制面板上查看 AFT **查询，请从右上角选择已保存和示例查询**图标，如以下屏幕截图所示：

![\[在 “ CloudWatch 日志见解” 控制面板上访问 AFT 查询。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/1342c0a6-4b07-46df-a063-ceab2e2f83c8/images/255d4032-738b-4600-9084-9684d2e9a328.png)


# 在不支持 AWS 的 AWS 区域创建管道 CodePipeline
<a name="create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline"></a>

*Anand Krishna Varanasi，Amazon Web Services*

## Summary
<a name="create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline-summary"></a>

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

AWS CodePipeline 是一项持续交付 (CD) 编排服务，是亚马逊网络服务 (AWS) 的一组 DevOps 工具的一部分。它与各种来源（例如版本控制系统和存储解决方案）、AWS 和 AWS Partners 提供的持续集成 (CI) 产品和服务以及开源产品集成，为应用程序和基础设施的快速部署提供 end-to-end工作流程服务。

但是， CodePipeline 并非所有 AWS 区域都支持，因此拥有一个连接 AWS CI/CD 服务的隐形协调器会很有用。此模式描述了如何使用 AWS CodeCommit、AWS 和 AWS 等 AWS CI/CD 服务在 CodePipeline 尚未支持的 AWS 区域中实施 end-to-end工作流程管道 CodeDeploy。 CodeBuild

## 先决条件和限制
<a name="create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account。
+ AWS Cloud Development Kit (AWS CDK) CLI 版本 2.28 或更高版本

## 架构
<a name="create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline-architecture"></a>

**目标技术堆栈**

下图显示了在不支持的 CodePipeline区域（例如非洲（开普敦）区域）中创建的管道。开发者将 CodeDeploy 配置文件（也称为*部署生命周期挂钩脚本*）推送到托管的 Git 存储库 CodeCommit。（请参阅此模式提供的[GitHub 存储库](https://github.com/aws-samples/invisible-codepipeline-unsupported-regions)。） Amazon EventBridge 规则会自动启动。 CodeBuild

 CodeDeploy 配置文件 CodeCommit 作为管道源阶段的一部分从中提取并传输到 CodeBuild。 

在下一阶段， CodeBuild 执行以下任务： 

1. 下载应用程序源代码 TAR 文件。您可以使用参数存储（AWS Systems Manager 的一项功能）来配置此文件的名称。

1. 下载 CodeDeploy 配置文件。

1. 创建应用程序源代码和特定于应用程序类型的 CodeDeploy 配置文件的组合存档。

1. 使用组合 CodeDeploy 存档启动部署到亚马逊弹性计算云 (Amazon EC2) 实例。

![\[在不受支持的 AWS 区域 中创建管道\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e27750de-b597-424e-b5bf-4d58dc9b60cc/images/95fc815e-a762-4142-b0fd-2a716823e498.png)


## 工具
<a name="create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline-tools"></a>

**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 CodeDeploy](https://docs.aws.amazon.com/codedeploy/latest/userguide/welcome.html) 可自动部署到亚马逊 EC2 或本地实例、AWS Lambda 函数或亚马逊弹性容器服务 (Amazon ECS) Container Service 服务。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可帮助您快速建模和配置软件发布的不同阶段，并自动执行持续发布软件变更所需的步骤。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一个软件开发框架，可帮助您在代码中定义并预置 Amazon Web Services Cloud 基础设施。

**代码**

此模式的代码可在 “ GitHub [CodePipeline 不支持的区域](https://github.com/aws-samples/invisible-codepipeline-unsupported-regions)” 存储库中找到。

## 操作说明
<a name="create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline-epics"></a>

### 设置开发人员工作站
<a name="set-up-your-developer-workstation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装 AWS CDK CLI。 | 有关说明，请参阅 [AWS CDK 文档](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_prerequisites)。 | AWS DevOps | 
| 安装 Git 客户端。 | 要创建提交，您可以使用安装在本地计算机上的 Git 客户端，然后将提交推送到 CodeCommit 存储库。要使用 Git 客户端 CodeCommit 进行设置，请参阅[CodeCommit 文档](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-create-commit.html)。 | AWS DevOps | 
| 安装 npm。 | 安装 **npm** 包管理器。有关更多信息，请参阅 [npm 文档](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)。 | AWS DevOps | 

### 设置管道
<a name="set-up-the-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆代码存储库。 | 运行以下命令，将 “ GitHub [CodePipeline 不支持的区域](https://github.com/aws-samples/invisible-codepipeline-unsupported-regions)” 存储库克隆到您的本地计算机。<pre>git clone https://github.com/aws-samples/invisible-codepipeline-unsupported-regions</pre> | DevOps 工程师 | 
| 在 cdk.json 中设置参数。 | 打开 `cdk.json`文件并为以下参数赋值：<pre>"pipeline_account":"XXXXXXXXXXXX",<br />"pipeline_region":"us-west-2",<br />"repo_name": "app-dev-repo",<br />"ec2_tag_key": "test-vm",<br />"configName" : "cbdeployconfig",<br />"deploymentGroupName": "cbdeploygroup",<br />"applicationName" : "cbdeployapplication",<br />"projectName" : "CodeBuildProject"</pre>其中：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline.html) | AWS DevOps | 
| 设置 AWS CDK 构造库。 | 在克隆的 GitHub 存储库中，使用以下命令安装 AWS CDK 构造库、构建您的应用程序并进行合成以生成应用程序的 AWS CloudFormation 模板。<pre>npm i aws-cdk-lib<br />npm run build<br />cdk synth</pre> | AWS DevOps | 
| 部署示例 AWS CDK 应用程序 | 在不支持的区域(例如 `af-south-1`)中运行以下命令来部署代码。<pre>cdk deploy</pre> | AWS DevOps | 

### 为以下内容设置 CodeCommit 存储库 CodeDeploy
<a name="set-up-the-codecommit-repository-for-codedeploy"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为应用程序 CI/CD 进行设置。 | 克隆您在`cdk.json`文件中指定的 CodeCommit 存储库（默认为`app-dev-repo`该存储库），为应用程序设置 CI/CD 管道。<pre>git clone https://git-codecommit.us-west-2.amazonaws.com/v1/repos/app-dev-repo</pre>其中，存储库名称和区域取决于您在 `cdk.json` 文件中提供的值。 | AWS DevOps | 

### 测试管道
<a name="test-the-pipeline"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 根据部署说明测试管道。 | “ GitHub [CodePipeline 不支持的区域](https://github.com/aws-samples/invisible-codepipeline-unsupported-regions)” 存储库的`CodeDeploy_Files`文件夹包含指示部署应用程序 CodeDeploy 的示例文件。该`appspec.yml`文件是一个 CodeDeploy 配置文件，其中包含用于控制应用程序部署流程的挂钩。您可以使用示例文件 `index.html`、`start_server.sh`、`stop_server.sh` 和 `install_dependencies.sh` 来更新托管在 Apache 上的网站。这些都是示例，您可以使用 GitHub 存储库中的代码来部署任何类型的应用程序。当文件被推送到 CodeCommit 存储库时，会自动启动不可见的管道。有关部署结果，请在 CodeBuild 和 CodeDeploy 控制台中查看各个阶段的结果。 | AWS DevOps | 

## 相关资源
<a name="create-a-pipeline-in-aws-regions-that-don-t-support-aws-codepipeline-resources"></a>
+ [入门](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_prerequisites)（AWS CDK 文档）
+ [云开发工具包（CDK）简介](https://catalog.us-east-1.prod.workshops.aws/workshops/5962a836-b214-4fbf-9462-fedba7edcc9b/en-US)(AWS 研习会参与平台 Workshop Studio)
+ [AWS CDK 研讨会](https://cdkworkshop.com/)

# 使用 AWS CDK 外观和逃生舱口自定义默认角色名称
<a name="customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches"></a>

*SANDEEP SINGH 和 James Jacob，Amazon Web Services*

## Summary
<a name="customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-summary"></a>

此模式演示如何自定义由 AWS Cloud Development Kit (AWS CDK) 构造创建的角色的默认名称。如果根据命名约定，您的组织具有特定约束，则通常需要自定义角色名称。例如，您的组织可能会设置 AWS Identity and Access Management (IAM) [权限边界](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_boundaries.html)或[服务控制策略 (SCPs)](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html)，要求在角色名称中使用特定的前缀。在这种情况下，由 AWS CDK 构造生成的默认角色名称可能不符合这些约定，因此可能需要更改。此模式通过在 AWS CDK中使用[逃生舱口](https://docs.aws.amazon.com/cdk/v2/guide/cfn-layer.html)和[方面](https://docs.aws.amazon.com/cdk/v2/guide/aspects.html)来满足这些要求。您可以使用逃生舱口来定义自定义角色名称，并使用方面来将自定义名称应用于所有角色，以确保遵守组织的策略和约束。

## 先决条件和限制
<a name="customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ [AWS CDK 文档](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_prerequisites)中指定的先决条件

**限制**
+ Aspects 会根据资源类型来筛选资源，因此所有角色共享相同的前缀。如果您需要为不同的角色添加不同的角色前缀，则需要根据其他属性进行额外筛选。例如，要为与 AWS Lambda 函数关联的角色分配不同的前缀，您可以按特定的角色属性或标签进行筛选，为与 Lambda 相关的角色应用一个前缀，为其他角色应用不同的前缀。
+ IAM 角色名称的最大长度为 64 个字符，因此必须裁剪修改后的角色名称才能满足此限制。
+ 有些 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="customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-architecture"></a>

**目标技术堆栈**
+ AWS CDK
+ AWS CloudFormation

**目标架构**

![\[使用逃生舱口和方面来自定义 AWS CDK 分配的角色名称的架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/c149d8d2-1da6-4680-ab0b-e5051b69688c/images/15e56ca5-f150-4522-b374-8ee2dcc655a9.png)

+ 一个 AWS CDK 应用程序由一个或多个 CloudFormation 堆栈组成，这些堆栈经过合成和部署以管理 AWS 资源。
+ 要修改第 2 层 (L2) 构造未公开的 AWS CDK托管资源的属性，您可以使用逃生舱口来覆盖底层 CloudFormation 属性（在本例中为角色名称），并在 AWS CDK 堆栈合成过程中使用一个方面将该角色应用于 AWS CDK 应用程序中的所有资源。

## 工具
<a name="customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-tools"></a>

**AWS 服务**
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html)是一个软件开发框架，可帮助您在代码中定义和配置 AWS 云 基础架构。
+ [AWS CDK 命令行接口 (AWS CDK CLI)](https://docs.aws.amazon.com/cdk/latest/guide/cli.html)（也称为 AWS CDK Toolkit）是一个命令行云开发套件，可帮助您与 AWS CDK 应用程序进行交互。CLI `cdk` 命令是与您的 AWS CDK 应用程序交互的主要工具。它运行您的应用程序，查询您定义的应用程序模型，并生成和部署由生成的 CloudFormation 模板。 AWS CDK
+ [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在资源的整个生命周期中跨地区对其 AWS 账户 进行管理。

**代码存储库**

此模式的源代码和模板可在 GitHub [CDK Aspects Override](https://github.com/aws-samples/cdk-aspects-override) 存储库中找到。

## 最佳实践
<a name="customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-best-practices"></a>

请参阅**AWS **规范性指南[网站上使用 AWS CDK 中的 TypeScript 创建 IaC 项目的最佳实践](https://docs.aws.amazon.com/prescriptive-guidance/latest/best-practices-cdk-typescript-iac/introduction.html)。

## 操作说明
<a name="customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-epics"></a>

### 安装 AWS CDK CLI
<a name="install-the-cdk-cli"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装 C AWS CDK LI。 | 要全局安装 AWS CDK CLI，请运行以下命令：<pre>npm install -g aws-cdk</pre> | AWS DevOps | 
| 验证 版本。 | 运行如下命令：<pre>cdk --version</pre>确认您使用的是 AWS CDK CLI 的版本 2。 | AWS DevOps | 
| 引导 AWS CDK 环境。 | 在部署 CloudFormation 模板之前，请准备好要 AWS 区域 使用的账户和账户。运行如下命令：<pre>cdk bootstrap <account>/<Region></pre>有关更多信息，请参阅[AWS CDK 文档中的引导](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)。 AWS  | AWS DevOps | 

### 部署 AWS CDK 应用程序以演示各方面的用法
<a name="deploy-the-cdk-app-to-demonstrate-the-use-of-aspects"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置项目。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches.html) | AWS DevOps | 
| 使用由 AWS CDK分配的默认角色名称部署堆栈。 | 部署两个包含 Lambda 函数及其关联角色的 CloudFormation 堆栈（`ExampleStack1`和`ExampleStack2`）：<pre>npm run deploy:ExampleAppWithoutAspects</pre>该代码并未显式传递角色属性，因此角色名称将由 AWS CDK构造而成。有关示例输出，请参阅[其他信息](#customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-additional)部分。 | AWS DevOps | 
| 使用方面部署堆栈。 | 在此步骤中，您可以通过为 AWS CDK 项目中部署的所有 IAM 角色添加前缀来应用强制执行角色名称约定的方面。该方面在 `lib/aspects.ts` 文件中定义。该方面会使用逃生舱口，通过添加前缀来覆盖角色名称。该方面可应用于 `bin/app-with-aspects.ts` 文件中的堆栈。本示例中使用的角色名称前缀为 `dev-unicorn`。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches.html)有关示例输出，请参阅[其他信息](#customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-additional)部分。 | AWS DevOps | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除您的 AWS CloudFormation 堆栈。 | 使用完此模式后，请运行以下命令清理资源，以避免产生额外费用：<pre>cdk destroy --all -f && cdk --app npx ts-node bin/app-with-aspects.ts' destroy --all -f </pre> | AWS DevOps | 

## 问题排查
<a name="customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 您在使用时遇到问题 AWS CDK。 | 请参阅 AWS CDK 文档中的[常见 AWS CDK 问题疑难解答](https://docs.aws.amazon.com/cdk/v2/guide/troubleshooting.html)。 | 

## 相关资源
<a name="customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-resources"></a>
+ [AWS Cloud Development Kit (AWS CDK)](https://aws.amazon.com/cdk/)
+ [AWS CDK 文档](https://docs.aws.amazon.com/cdk/)
+ [AWS CDK on GitHub](https://github.com/aws/aws-cdk)
+ [逃生舱口](https://docs.aws.amazon.com/cdk/v2/guide/cfn-layer.html)
+ [方面和 AWS CDK](https://docs.aws.amazon.com/cdk/v2/guide/aspects.html)

## 附加信息
<a name="customize-default-role-names-by-using-aws-cdk-aspects-and-escape-hatches-additional"></a>

**由 CloudFormation 不带任何方面创建的角色名称**

```
Outputs:
ExampleStack1WithoutAspects.Function1RoleName = example-stack1-without-as-Function1LambdaFunctionSe-y7FYTY6FXJXA
ExampleStack1WithoutAspects.Function2RoleName = example-stack1-without-as-Function2LambdaFunctionSe-dDZV4rkWqWnI
...

Outputs:
ExampleStack2WithoutAspects.Function3RoleName = example-stack2-without-as-Function3LambdaFunctionSe-ygMv49iTyMq0
```

**由 CloudFormation 使用方面创建的角色名称**

```
Outputs:
ExampleStack1WithAspects.Function1RoleName = dev-unicorn-Function1LambdaFunctionServiceRole783660DC
ExampleStack1WithAspects.Function2RoleName = dev-unicorn-Function2LambdaFunctionServiceRole2C391181
...

Outputs:
ExampleStack2WithAspects.Function3RoleName = dev-unicorn-Function3LambdaFunctionServiceRole4CAA721C
```

# 使用私有静态在 Amazon EC2 上部署 Cassandra 集群 IPs 以避免重新平衡
<a name="deploy-a-cassandra-cluster-on-amazon-ec2-with-private-static-ips-to-avoid-rebalancing"></a>

*Dipin Jain，Amazon Web Services*

## Summary
<a name="deploy-a-cassandra-cluster-on-amazon-ec2-with-private-static-ips-to-avoid-rebalancing-summary"></a>

亚马逊弹性计算云 (Amazon EC2) 实例的私有 IP 将在其整个生命周期中保留。然而，私有 IP 可能会在计划内或计划外的系统崩溃期间发生变化，例如在亚马逊机器映像（AMI）升级期间。在某些情况下，保留私有静态 IP 可以提高工作负载的性能并缩短恢复时间。例如为 Apache Cassandra 种子节点使用静态 IP 可以防止集群产生再平衡开销。 

此模式描述了如何将辅助弹性网络接口连接到 EC2 实例，以便在重新托管期间保持 IP 静态。该模式侧重于 Cassandra 集群，但你可以将此实现用于任何受益于私有静态 IPs的架构。

## 先决条件和限制
<a name="deploy-a-cassandra-cluster-on-amazon-ec2-with-private-static-ips-to-avoid-rebalancing-prereqs"></a>

**先决条件**
+ 有效 Amazon Web Service (AWS) 账户

**产品版本**
+ DataStax 版本 5.11.1
+ 操作系统：Ubuntu 16.04.6 LTS

## 架构
<a name="deploy-a-cassandra-cluster-on-amazon-ec2-with-private-static-ips-to-avoid-rebalancing-architecture"></a>

**源架构**

源可以是本地虚拟机 (VM) 上的 Cassandra 集群，也可以是 AWS 云中的 EC2 实例。下图阐明了第二场景。此示例包括 4 个集群节点：3 个种子节点和 1 个管理节点。在源架构中，每个节点都连接有一个网络接口。

![\[四个 Amazon EC2 集群节点，每个节点都连接了一个网络接口。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/47ca4dbc-0922-4e65-b66c-4db5122fc4ac/images/5d80cfc9-4b72-4c72-aefd-b77cc0fb58e3.png)


**目标架构**

目标集群托管在每个节点上都连接了辅助弹性网络 interface 的 EC2 实例上，如下图所示。

![\[四个 Amazon EC2 集群节点，每个节点都连接了一个辅助弹性网络接口。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/47ca4dbc-0922-4e65-b66c-4db5122fc4ac/images/d1e22017-f041-426b-9204-31ac158a407d.png)


**自动化和扩展**

您还可以自动将第二个弹性网络接口连接到 A EC2 uto Scaling 群组，如 A [WS 知识中心视频](https://www.youtube.com/watch?v=RmwGYXchb4E)中所述。

## 操作说明
<a name="deploy-a-cassandra-cluster-on-amazon-ec2-with-private-static-ips-to-avoid-rebalancing-epics"></a>

### 在亚马逊上配置 Cassandra 集群 EC2
<a name="configure-a-cassandra-cluster-on-amazon-ec2"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动 EC2 节点以托管 Cassandra 集群。 | 在[亚马逊 EC2 控制台](https://console.aws.amazon.com/ec2/)上，为你的 AWS 账户中的 Ubuntu 节点启动四个 EC2 实例。三个（种子）节点用于 Cassandra 集群，第四个节点用作集群管理节点，您将在其中安装 DataStax 企业版 (DSE) OpsCenter。有关说明，请参阅 [Amazon EC2 文档](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html#ec2-launch-instance)。 | 云工程师 | 
| 确认节点通信。 | 确保四个节点可通过数据库和集群管理端口相互通信。 | 网络工程师 | 
| 在管理节点 OpsCenter 上安装 DSE。 | 从管理节点上的 Debian 软件包中安装 DSE OpsCenter 6.1。有关说明，请参阅 [DataStax 文档](https://docs.datastax.com/en/opscenter/6.1/opsc/install/opscInstallDeb_t.html)。 | 数据库管理员 | 
| 创建辅助网络接口。 | Cassandra 根据每个节点的 EC2 实例 IP 地址为该节点生成一个通用唯一标识符 (UUID)。此 UUID 用于在环上分发虚拟节点 (vnode)。在 EC2 实例上部署 Cassandra 时，会在创建实例时自动为其分配 IP 地址。 如果发生计划内或计划外停机，则新 EC2 实例的 IP 地址会发生变化，数据分布会发生变化，并且必须重新平衡整个环路。这是不可取的。要保留分配的 IP 地址，请使用具有固定 IP 地址的[辅助弹性网络接口](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#scenarios-enis)。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-cassandra-cluster-on-amazon-ec2-with-private-static-ips-to-avoid-rebalancing.html)有关创建网络接口的更多信息，请参阅 [Amazon EC2 文档](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#create_eni)。 | 云工程师 | 
| 将辅助网络接口连接至集群节点。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-cassandra-cluster-on-amazon-ec2-with-private-static-ips-to-avoid-rebalancing.html)有关连接网络接口的更多信息，请参阅 [Amazon EC2 文档](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#attach_eni)。 | 云工程师 | 
| 在 Amazon 中添加路由 EC2 以解决非对称路由问题。 | 当您连接第二个网络接口时，网络很可能执行非对称路由。为避免这种情况，您可为新的网络接口添加路由。有关非对称路由的深入解释和补救措施，请参阅 [AWS 知识中心视频](https://www.youtube.com/watch?v=RmwGYXchb4E)或[克服多宿主服务器上的非对称路由](http://www.linuxjournal.com/article/7291)（Patrick 在 *Linux 杂志*上发表的文章 McManus，2004 年 4 月 5 日）。 | 网络工程师 | 
| 更新 DNS 条目，以指向辅助网络接口 IP。 | 指定节点的完全限定域名 (FQDN) 指向辅助网络接口的 IP。 | 网络工程师 | 
| 使用 DSE OpsCenter 安装和配置 Cassandra 集群。 | 当集群节点准备好使用辅助网络接口时，您可安装和配置 Cassandra 集群。 | 数据库管理员 | 

### 从节点故障中恢复集群
<a name="recover-cluster-from-node-failure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为集群种子节点创建 AMI。 | 对节点进行备份，以便在节点发生故障时可以使用数据库二进制文件恢复它们。有关说明，请参阅 Amazon EC2 文档中的[创建 AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-ami.html)。 | 备份管理员 | 
| 从节点故障中恢复 | 将故障节点替换为从 AMI 启动的新 EC2 实例，并连接故障节点的辅助网络接口。 | 备份管理员 | 
| 验证 Cassandra 集群是否正常运行。 | 替换节点启动后，在 DSE 中验证集群运行状况 OpsCenter。 | 数据库管理员 | 

## 相关的资源
<a name="deploy-a-cassandra-cluster-on-amazon-ec2-with-private-static-ips-to-avoid-rebalancing-resources"></a>
+ [从 Debian 软件包中安装 DSE OpsCenter 6.1](https://docs.datastax.com/en/opscenter/6.1/opsc/install/opscInstallDeb_t.html)（DataStax 文档）
+ [如何在 Ubuntu EC2 实例中使用辅助网络接口](https://www.youtube.com/watch?v=RmwGYXchb4E)（AWS 知识中心视频）
+ 在@@ [亚马逊上运行 Apache Cassandra 的最佳实践](https://aws.amazon.com/blogs/big-data/best-practices-for-running-apache-cassandra-on-amazon-ec2/)（ EC2AWS 博客文章）

# 使用 AWS Transit Gateway Connect 扩展 VRFs 到 AWS
<a name="extend-vrfs-to-aws-by-using-aws-transit-gateway-connect"></a>

*Adam Till、Yashar Araghi、Vikas Dewangan 和 Amazon Web Services 的 Mohideen HajaMohideen*

## Summary
<a name="extend-vrfs-to-aws-by-using-aws-transit-gateway-connect-summary"></a>

虚拟路由转发（VRF）是传统网络的一个特征。它使用路由表形式的隔离逻辑路由域来分隔同一物理基础设施内的网络流量。当您将本地网络连接到 AWS 时，您可以配置 AWS Transit Gateway 以支持 VRF 隔离。此模式使用示例架构将本地 VRFs 连接到不同的公交网关路由表。

此模式使用 AWS Direct Connect 中的传输虚拟接口 (VIFs) 和传输网关 Connect 附件来扩展 VRFs。[中转 VIF](https://docs.aws.amazon.com/directconnect/latest/UserGuide/WorkingWithVirtualInterfaces.html) 用于访问与 Direct Connect 网关关联的一个或多个 Amazon VPC 中转网关。[中转网关 Connect 连接](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html)将中转网关与在 VPC 中运行的第三方虚拟设备连接起来。中转网关 Connect 连接支持通用路由封装（GRE）隧道协议以实现高性能，支持边界网关协议（BGP）以实现动态路由。

此模式中描述的方法具有以下优点：
+ 使用 Transit Gateway Connect，您可以向 Transit Gateway Connect 对等方通告最多 1,000 条路由，并从中接收最多 5,000 条路由。在不使用 Transit Gateway Connect 的情况下使用 Direct Connect 中转 VIF 功能时，每个中转网关最多可使用 20 个前缀。
+ 无论您的客户使用何种 IP 地址架构，您都可以保持流量隔离并使用 Transit Gateway Connect 在 AWS 上提供托管服务。
+ VRF 流量不需要遍历公共虚拟接口。这使得许多组织更容易遵守合规性和安全要求。
+ 每个 GRE 隧道支持高达 5 Gbps，每个中转网关 Connect 连接最多可以有四个 GRE 隧道。这比许多其他连接类型都要快，例如支持高达 1.25 Gbps 的 AWS Site-to-Site VPN 连接。

## 先决条件和限制
<a name="extend-vrfs-to-aws-by-using-aws-transit-gateway-connect-prereqs"></a>

**先决条件**
+ 所需 Amazon Web Services account 已创建（有关详细信息，请参阅架构）
+ 在每个账户中代入 AWS Identity and Access Management (IAM) 角色。
+ 每个账户的 IAM 角色必须有权预调配 AWS Transit Gateway 和 AWS Direct Connect 资源。有关更多信息，请参阅[中转网关的身份验证和访问控制](https://docs.aws.amazon.com/vpc/latest/tgw/transit-gateway-authentication-access-control.html)和 [Direct Connect 的身份和访问管理](https://docs.aws.amazon.com/directconnect/latest/UserGuide/security-iam.html)。
+ Direct Connect 连接已成功创建。有关更多信息，请参阅[使用连接向导创建连接](https://docs.aws.amazon.com/directconnect/latest/UserGuide/dedicated_connection.html#create-connection)。

**限制**
+ 生产、质量保证和开发账户 VPCs 中的公交网关附件存在限制。有关更多信息，请参阅 [VPC 的中转网关连接](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-vpc-attachments.html)。
+ 创建和使用 Direct Connect 网关是有限制的。有关更多信息，请参阅 [AWS Direct Connect 限额](https://docs.aws.amazon.com/directconnect/latest/UserGuide/limits.html)。

## 架构
<a name="extend-vrfs-to-aws-by-using-aws-transit-gateway-connect-architecture"></a>

**目标架构**

以下示例架构提供了一种可重复使用的解决方案，用于 VIFs 通过公交网关 Connect 附件部署公交。该架构通过使用多个 Direct Connect 位置来提供弹性。有关更多信息，请参阅 Direct Connect 文档中的[最大弹性](https://docs.aws.amazon.com/directconnect/latest/UserGuide/maximum_resiliency.html)。本地网络包含生产、质量保证和开发，这些内容扩展到 AWS VRFs ，并使用专用路由表进行隔离。

![\[使用 AWS Direct Connect 和 AWS Transit Gateway 资源进行扩展的架构图 VRFs\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/db17e177-6c94-4d81-ab39-0923ecab2f1b/images/10be0625-8574-40eb-bc00-bb0a07d0dc26.png)


在 AWS 环境中，有两个账户专门用于扩展 VRFs：一个 *Direct Connect 账户*和一个*网络中心账户*。Direct Connect 账户包含每台路由器的连接和传输 VIFs 。您可以 VIFs 从 Direct Connect 账户创建传输，但将其部署到网络中心帐户，这样您就可以将它们与网络中心账户中的 Direct Connect 网关关关联。网络中心账户包含 Direct Connect 网关和中转网关。AWS 资源连接方式如下：

1. Transit 将直接 VIFs 连接地点的路由器与 Direct Connect 账户中的 AWS Direct Connect 连接起来。

1. 中转 VIF 将 Direct Connect 与网络中心账户中的 Direct Connect 网关连接。

1. [中转网关关联](https://docs.aws.amazon.com/directconnect/latest/UserGuide/direct-connect-transit-gateways.html)将 Direct Connect 网关与网络中心账户中的中转网关连接起来。

1. [Transit gateway Connect 附件](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html)将公交网关与生产账户、QA 账户和开发账户连接起来。 VPCs 

*中转 VIF 架构*

下图显示了公交的配置详细信息 VIFs。此示例架构使用 VLAN 为隧道源，但您也可以使用环回。

![\[路由器与 AWS Direct Connect 间中转 VIF 连接的配置详细信息\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/db17e177-6c94-4d81-ab39-0923ecab2f1b/images/e88d2546-61ef-4531-972b-089cdf44ed67.png)


以下是公交的配置详细信息，例如自治系统编号 (ASNs) VIFs。


| 
| 
| 资源 | Item | Detail | 
| --- |--- |--- |
| 路由器-01 | ASN | 65534 | 
| 路由器-02 | ASN | 65534 | 
| 路由器-03 | ASN | 65534 | 
| 路由器-04 | ASN | 65534 | 
| Direct Connect 网关 | ASN | 64601 | 
| Transit Gateway | ASN | 64600 | 
| CIDR 块 | 10.100.254.0/24 | 

*中转网关 Connect 架构*

下图和表格介绍了如何通过中转网关 Connect 连接配置单个 VRF。此外 VRFs，请在 CIDR 块内分配唯一的隧道 IDs、传输网关 GRE IP 地址和 BGP。对等 GRE IP 地址与中转 VIF 中的路由器对等 IP 地址相匹配。

![\[路由器和中转网关之间 GRE 隧道的配置详细信息\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/db17e177-6c94-4d81-ab39-0923ecab2f1b/images/e58278e1-f3b4-442d-95d9-1dafab4aa5ac.png)


下表包含路由器配置详细信息。


| 
| 
| 路由器 | 隧道 | IP 地址 | 来源 | 目标位置 | 
| --- |--- |--- |--- |--- |
| 路由器-01 | 隧道 1 | 169.254.101.17 | VLAN 60169.254.100.1 | 10.100.254.1 | 
| 路由器-02 | 隧道 11 | 169.254.101.81 | VLAN 61169.254.100.5 | 10.100.254.11 | 
| 路由器-03 | 隧道 21 | 169.254.101.145 | VLAN 62169.254.100.9 | 10.100.254.21 | 
| 路由器-04 | 隧道 31 | 169.254.101.209 | VLAN 63169.254.100.13 | 10.100.254.31 | 

下表包含中转网关配置详细信息。


| 
| 
| 隧道 | 中转网关 GRE IP 地址 | 对等 GRE IP 地址 | CIDR 块内的 BGP | 
| --- |--- |--- |--- |
| 隧道 1 | 10.100.254.1 | VLAN 60169.254.100.1 | 169.254.101.16/29 | 
| 隧道 11 | 10.100.254.11 | VLAN 61169.254.100.5 | 169.254.101.80/29 | 
| 隧道 21 | 10.100.254.21 | VLAN 62169.254.100.9 | 169.254.101.144/29 | 
| 隧道 31 | 10.100.254.31 | VLAN 63169.254.100.13 | 169.254.101.208/29 | 

**部署**

[操作说明](#extend-vrfs-to-aws-by-using-aws-transit-gateway-connect-epics)部分介绍如何在多台客户路由器上部署****单个 VRF 的示例配置。步骤 1–5 完成后，您可使用步骤 6–7 为要扩展到 AWS 的每个新 VRF 创建新的中转网关 Connect 连接：

1. 创建中转网关。

1. 为每个 VRF 创建中转网关路由表。

1. 创建中转虚拟接口。

1. 创建 Direct Connect 网关。

1. 使用允许的前缀创建 Direct Connect 网关虚拟接口和网关关联。

1. 创建中转网关 Connect 连接。

1. 创建中转网关 Connect 对等节点。

1. 将中转网关 Connect 连接与路由表相关联。

1. 向路由器传播路由。

## 工具
<a name="extend-vrfs-to-aws-by-using-aws-transit-gateway-connect-tools"></a>

**Amazon Web Services**
+ [AWS Direct Connect](https://docs.aws.amazon.com/directconnect/latest/UserGuide/Welcome.html) 通过标准的以太网光纤电缆将内部网络链接到 Direct Connect 位置。通过此连接，您可以直接创建连接到公有 Amazon Web Services 的虚拟接口，同时绕过网络路径中的互联网服务提供商。
+ [AWS Transit Gateway](https://docs.aws.amazon.com/vpc/latest/tgw/what-is-transit-gateway.html) 是一个连接虚拟私有云 (VPCs) 和本地网络的中心枢纽。
+ [Amazon Virtual Private Cloud（Amazon VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。此虚拟网络类似于您在自己的数据中心内运行的传统网络，具有使用 AWS 可扩展基础设施的优势。

## 操作说明
<a name="extend-vrfs-to-aws-by-using-aws-transit-gateway-connect-epics"></a>

### 规划架构
<a name="plan-the-architecture"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建自定义架构图。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.html) | 云架构师、网络管理员 | 

### 创建中转网关资源
<a name="create-the-transit-gateway-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建中转网关。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.html) | 网络管理员、云架构师 | 
| 创建中转网关路由表。 | 按照[创建中转网关路由表](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-route-tables.html#create-tgw-route-table)中的说明进行操作。请注意此示例以下几点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.html) | 云架构师、网络管理员 | 

### 创建中转虚拟接口
<a name="create-the-transit-virtual-interfaces"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建中转虚拟接口。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.html) | 云架构师、网络管理员 | 

### 创建 Direct Connect 资源
<a name="create-the-direct-connect-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Direct Connect 网关。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.html) | 云架构师、网络管理员 | 
| 将 Direct Connect 网关连接到公交 VIFs。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.html) | 云架构师、网络管理员 | 
| 使用允许的前缀创建 Direct Connect 网关关联。 | 在网络中心账户中，按照[关联中转网关](https://docs.aws.amazon.com/directconnect/latest/UserGuide/direct-connect-transit-gateways.html#associate-tgw-with-direct-connect-gateway)中的说明进行操作。请注意此示例以下几点：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.html)创建此关联会自动创建具有 Direct Connect 网关资源类型的中转网关连接。此连接不需要与中转网关路由表关联。 | 云架构师、网络管理员 | 
| 创建中转网关 Connect 连接。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.html) | 云架构师、网络管理员 | 
| 创建中转网关 Connect 对等节点。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.html) |  | 

### 将路由传播到路由器
<a name="advertise-routes-to-the-routers"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 传播路由。 | 将新的中转网关 Connect 连接与您之前为此 VRF 创建的路由表相关联。例如，将生产中转网关 Connect 连接与 `Production-VRF`路由表关联。为通告到路由器的前缀创建静态路由。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/extend-vrfs-to-aws-by-using-aws-transit-gateway-connect.html) | 网络管理员、云架构师 | 

## 相关资源
<a name="extend-vrfs-to-aws-by-using-aws-transit-gateway-connect-resources"></a>

**AWS 文档**
+ Direct Connect 文档
  + [使用 Direct Connect 网关](https://docs.aws.amazon.com/directconnect/latest/UserGuide/direct-connect-gateways.html)
  + [中转网关关联](https://docs.aws.amazon.com/directconnect/latest/UserGuide/direct-connect-transit-gateways.html)
  + [AWS Direct Connect 虚拟接口](https://docs.aws.amazon.com/directconnect/latest/UserGuide/WorkingWithVirtualInterfaces.html)
+ Transit Gateway 文档
  + [使用中转网关](https://docs.aws.amazon.com/vpc/latest/tgw/working-with-transit-gateways.html)
  + [将中转网关连接到 Direct Connect 网关](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-dcg-attachments.html)
  + [中转网关 Connect 连接和中转网关 Connect 对等节点](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html)
  + [创建中转网关 Connect 连接](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-connect.html#create-tgw-connect-attachment)

**AWS Blog 文章**
+ [使用 AWS Transit Gateway 连接对混合网络执行分段](https://aws.amazon.com/blogs/networking-and-content-delivery/segmenting-hybrid-networks-with-aws-transit-gateway-connect/)
+ [使用 AWS Transit Gateway 连接来扩展 VRFs 和增加 IP 前缀广告](https://aws.amazon.com/blogs/networking-and-content-delivery/using-aws-transit-gateway-connect-to-extend-vrfs-and-increase-ip-prefix-advertisement/)

## 附件
<a name="attachments-db17e177-6c94-4d81-ab39-0923ecab2f1b"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/db17e177-6c94-4d81-ab39-0923ecab2f1b/attachments/attachment.zip)

# 当 AWS KMS 密钥的密钥状态发生变化时获取 Amazon SNS 通知
<a name="get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes"></a>

*Shubham Harsora、Aromal Raj Jayarajan 和 Navdeep Pareek，Amazon Web Services*

## Summary
<a name="get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes-summary"></a>

删除与 AWS Key Management Service（AWS KMS）密钥关联的数据和元数据后，该密钥将丢失。删除是不可逆的，您无法恢复丢失的数据（包括加密数据）。您可以设置通知系统，提醒您 AWS KMS 密钥的[密钥状态](https://docs.aws.amazon.com/kms/latest/developerguide/key-state.html#key-state-cmk-type)发生更改，从而防止数据丢失。

此模式向您展示如何监控 AWS KMS 密钥的状态变化，方法是使用亚马逊 EventBridge 和亚马逊简单通知服务 (Amazon SNS) Simple Notification Service 在 AWS KMS 密钥的密钥状态更改为或时自动发出通知。`Disabled` `PendingDeletion`例如，如果用户尝试禁用或删除 AWS KMS 密钥，您将收到一封电子邮件通知，其中包含有关尝试更改状态的详细信息。您也可以使用此模式安排删除 AWS KMS 密钥。

## 先决条件和限制
<a name="get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes-prereqs"></a>

**先决条件**
+ 一个拥有 AWS Identity and Access Management (IAM) 用户的有效 Amazon Web Services account
+ 一个 [AWS KMS 密钥](https://docs.aws.amazon.com/kms/latest/developerguide/getting-started.html)

## 架构
<a name="get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes-architecture"></a>

**技术堆栈**
+ Amazon EventBridge
+ AWS Key Management Service（AWS KMS）
+ Amazon Simple Notification Service（Amazon SNS）

**目标架构**

下图显示了一种架构，用于构建自动监控和通知流程，以检测 AWS KMS 密钥状态的任何更改。

![\[用于构建自动监控和通知流程的架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/2534df87-a6fd-4360-9b5d-4a8b1f533de3/images/0cb6a6b0-405b-4d26-ad04-2067176aa086.png)


下图显示了如下工作流：

1. 用户禁用或计划删除 AWS KMS 密钥。

1.  EventBridge 规则评估计划`Disabled`或`PendingDeletion`事件。

1. 该 EventBridge 规则调用了 Amazon SNS 主题。

1. Amazon SNS 会向用户发送一封电子邮件通知消息。

**注意**  
您可以自定义电子邮件消息以满足组织的需求。我们建议包括有关使用 AWS KMS 密钥的实体的信息。这可以帮助用户了解删除 AWS KMS 密钥的影响。您还可以安排在 AWS KMS 密钥删除前一两天发送提醒电子邮件通知。

**自动化和扩展**

AWS CloudFormation 堆栈部署了所有必要的资源和服务，以使这种模式发挥作用。您可以在单个账户中独立实施该模式，也可以将 [AWS 用 CloudFormation StackSets于 AWS Org](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) anizations 中的多个独立账户或[组织单位](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_ous.html)。

## 工具
<a name="get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes-tools"></a>
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可帮助您设置 AWS 资源，快速一致地配置这些资源，并在 AWS 账户和 AWS 区域的整个生命周期中对其进行管理。此模式的 CloudFormation 模板描述了您需要的所有 AWS 资源，并 CloudFormation 为您预置和配置这些资源。
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) 是一项无服务器事件总线服务，可帮助您将应用程序与来自各种来源的实时数据连接起来。 EventBridge 提供来自您自己的应用程序和 AWS 服务的实时数据流，并将这些数据路由到目标，例如 AWS Lambda。 EventBridge 简化了构建事件驱动架构的过程。
+ [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) 可帮助您创建和控制加密密钥，以帮助保护您的数据。
+ [Amazon Simple Notiﬁcation Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可帮助您协调和管理发布者与客户端（包括 Web 服务器和电子邮件地址）之间的消息交换。

**代码**

此模式的代码可在 GitHub [监控 AWS KMS 密钥禁用和计划删除](https://github.com/aws-samples/aws-kms-deletion-notification)存储库中找到。

## 操作说明
<a name="get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes-epics"></a>

### 部署 CloudFormation 模板
<a name="deploy-the-cloudformation-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 运行以下命令，将 Mon GitHub [itor AWS KMS 密钥禁用和计划删除](https://github.com/aws-samples/aws-kms-deletion-notification)存储库克隆到本地计算机：`git clone https://github.com/aws-samples/aws-kms-deletion-notification` | AWS 管理员、云架构师 | 
| 更新模板的参数。 | 在代码编辑器中，打开您从存储库中克隆的`Alerting-KMS-Events.yaml` CloudFormation 模板，然后更新以下参数：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes.html) | AWS 管理员、云架构师 | 
| 部署 CloudFormation 模板。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes.html) | AWS 管理员、云架构师 | 

### 确认订阅
<a name="confirm-the-subscription"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确认订阅电子邮件。 |  CloudFormation 模板成功部署后，Amazon SNS 会向您在模板中 CloudFormation 提供的电子邮件地址发送订阅确认消息。要接收通知，您必须确认此电子邮件订阅。有关更多信息，请参阅 Amazon SNS 开发人员指南中的[确认订阅](https://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.confirm.html)。 | AWS 管理员、云架构师 | 

### 测试订阅通知
<a name="test-the-subscription-notification"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 禁用 AWS KMS 密钥。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes.html) | AWS 管理员 | 
| 验证订阅。 | 确认您收到 Amazon SNS 通知电子邮件。 | AWS 管理员 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除 CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes.html) | AWS 管理员 | 

## 相关资源
<a name="get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes-resources"></a>
+ [AWS CloudFormation](https://aws.amazon.com/cloudformation/)（AWS 文档）
+ 在 [AWS CloudFormation 控制台上创建堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)（AWS CloudFormation 文档）
+ [在 AWS 上构建事件驱动型架构](https://catalog.us-east-1.prod.workshops.aws/workshops/63320e83-6abc-493d-83d8-f822584fb3cb/en-US)（AWS 研习会参与平台 Workshop Studio 文档）
+ [AWS Key Management Service（AWS KMS）最佳实践](https://d1.awsstatic.com/whitepapers/aws-kms-best-practices.pdf)（AWS 白皮书）
+ [AWS Key Management Service（AWS KMS）的安全最佳实践](https://docs.aws.amazon.com/kms/latest/developerguide/best-practices.html)（AWS KMS 开发人员指南）

## 附加信息
<a name="get-amazon-sns-notifications-when-the-key-state-of-an-aws-kms-key-changes-additional"></a>

默认情况下，Amazon SNS 会在传输过程中提供加密。为了与安全最佳实践保持一致，您还可以使用 AWS KMS 客户托管密钥为 Amazon SNS 启用服务器端加密。

# 在非工作负载子网的多账户 VPC 设计中保留可路由的 IP 空间
<a name="preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets"></a>

*Adam Spicer，Amazon Web Services*

## Summary
<a name="preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets-summary"></a>

Amazon Web Services (AWS) 已发布最佳实践，建议在虚拟私有云（VPC）中为[中转网关连接](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-best-design-practices.html)和[网关负载均衡器端点](https://docs.aws.amazon.com/elasticloadbalancing/latest/gateway/getting-started.html)（以支持 [AWS Network Firewall](https://docs.aws.amazon.com/network-firewall/latest/developerguide/firewall-high-level-steps.html) 或第三方设备）使用专用子网。这些子网用于包含这些服务的弹性网络接口。如果您同时使用 AWS Transit Gateway 和网关负载均衡器，则会在 VPC 的每个可用区中创建两个子网。由于设计方式 VPCs ，这些额外的子网[不能小于 /28 掩码，并且会](https://docs.aws.amazon.com/vpc/latest/userguide/configure-subnets.html#subnet-sizing)消耗宝贵的可路由 IP 空间，而这些空间本来可以用于可路由的工作负载。此模式演示了如何为这些专用子网使用辅助的、不可路由的无类别域间路由 (CIDR) 范围，以帮助保留可路由的 IP 空间。

## 先决条件和限制
<a name="preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets-prereqs"></a>

**先决条件**
+ 可路由 IP 空间的[多 VPC 策略](https://docs.aws.amazon.com/whitepapers/latest/building-scalable-secure-multi-vpc-network-infrastructure/welcome.html)
+ 您正在使用的服务（[中转网关连接](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-best-design-practices.html)和[网关负载均衡器](https://aws.amazon.com/blogs/apn/centralized-traffic-inspection-with-gateway-load-balancer-on-aws/)或 [Network Firewall 端点](https://aws.amazon.com/blogs/networking-and-content-delivery/deployment-models-for-aws-network-firewall/)）的不可路由 CIDR 范围

## 架构
<a name="preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets-architecture"></a>

**目标架构**

此模式包括两个参考架构：一种架构具有用于传输网关 (TGW) 连接的子网和一个 Gateway Load Balancer 端点 (GWLBe)，第二个架构具有仅用于 TGW 附件的子网。

**架构 1 - 连接 TGW 的 VPC，具有到设备的入口路由**

下图展示了跨两个可用区的 VPC 的参考架构。在入口处，VPC 使用入[口路由模式](https://aws.amazon.com/blogs/aws/new-vpc-ingress-routing-simplifying-integration-of-third-party-appliances/)将发往公有子网的流量引导到[bump-in-the-wire 设备](https://aws.amazon.com/blogs/networking-and-content-delivery/introducing-aws-gateway-load-balancer-supported-architecture-patterns/)进行防火墙检查。TGW 连接支持从私有子网到单独的 VPC 的出口。

此模式对 TGW 连接子网和子网使用不可路由的 CIDR 范围。 GWLBe 在 TGW 路由表中，使用一组更具体的路由，将此不可路由的 CIDR 配置为黑洞（静态）路由。如果路由要传播到 TGW 路由表，则将应用这些更具体的黑洞路由。

在此示例中，/23 可路由 CIDR 被划分并完全分配给可路由子网。

![\[TGW 连接的 VPC，具有到设备的入口路由。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/0171d91d-ab1e-41ca-a425-1e6e610080e1/images/adad1c83-cdc2-4c5e-aa35-f47fc31af384.png)


**架构 2 — 连接 TGW 的 VPC**

下图展示了另一个跨可用区的 VPC 的参考架构。TGW 连接支持从私有子网到单独的 VPC 的出站。它仅对 TGW 连接子网使用不可路由 CIDR 范围。在 TGW 路由表中，使用一组更具体的路由，将此不可路由的 CIDR 配置为黑洞路由。如果路由要传播到 TGW 路由表，则将应用这些更具体的黑洞路由。

在此示例中，/23 可路由 CIDR 被划分并完全分配给可路由子网。

![\[VPC 横跨 2 个可用区，并通过 TGW 连接，实现从私有子网向独立 VPC 的出口流量传输。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/0171d91d-ab1e-41ca-a425-1e6e610080e1/images/31a2a241-5be6-425e-93e9-5ff7ffeca3a9.png)


## 工具
<a name="preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets-tools"></a>

**Amazon Web Services 和资源**
+ [Amazon Virtual Private Cloud (Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) 可帮助您将 AWS 资源启动到您定义的虚拟网络中。此虚拟网络类似于您在自己的数据中心内运行的传统网络，具有使用 AWS 可扩展基础设施的优势。在这种模式中，VPC 辅助 CIDRs 用于在工作负载 CIDRs中保留可路由 IP 空间。
+ [互联网网关入口路由](https://aws.amazon.com/blogs/aws/new-vpc-ingress-routing-simplifying-integration-of-third-party-appliances/)（边缘关联）可以与网关负载均衡器端点一起使用，用于专用的不可路由子网。
+ [AWS Transit Gateway](https://docs.aws.amazon.com/vpc/latest/tgw/what-is-transit-gateway.html) 是一个连接 VPCs 本地网络的中心枢纽。在这种模式中 VPCs ，集中连接到传输网关，传输网关附件位于不可路由的专用子网中。
+ [网关负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/gateway/introduction.html)可帮助您部署、扩展和管理虚拟设备，例如防火墙、入侵检测和防御系统以及深度数据包检测系统。网关充当所有流量的单一入口和出口点。在这种模式下，网关负载均衡器的端点可以在不可路由的专用子网中使用。
+ [AWS Network Fire](https://docs.aws.amazon.com/network-firewall/latest/developerguide/what-is-aws-network-firewall.html) wall 是一项有状态的托管式网络防火墙以及入侵检测和防御服务，适用于 AWS 云 VPCs 中。在此模式中，防火墙的端点可以在专用的不可路由子网中使用。

**代码存储库**

此模式的运行手册和 AWS CloudFormation 模板可在 GitHub [不可路由的辅助 CIDR 模式存储库中](https://github.com/aws-samples/non-routable-secondary-vpc-cidr-patterns/)找到。您可使用示例文件在您的环境中设置工作实验室。

## 最佳实践
<a name="preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets-best-practices"></a>

**AWS Transit Gateway**
+ 为每个中转网关 VPC 附件使用单独的子网。
+ 从辅助不可路由 CIDR 范围中为中转网关连接子网分配 /28 子网。
+ 在每个中转网关路由表中，为不可路由的 CIDR 范围添加一条更具体的静态路由作为黑洞。

**网关负载均衡器与入口路由**
+ 使用入口路由将流量从互联网引导至网关负载均衡器端点。
+ 为每个网关负载均衡器端点使用单独子网。
+ 从网关负载均衡器端点子网辅助不可路由 CIDR 范围中分配一个 /28 子网。

## 操作说明
<a name="preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets-epics"></a>

### 创建 VPCs
<a name="create-vpcs"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确定不可路由的 CIDR 范围。 | 确定一个不可路由的 CIDR 范围，该范围将用于中转网关连接子网以及（可选）用于任何网关负载均衡器或 Network Firewall 端点子网。此 CIDR 范围用作 VPC 的辅助 CIDR。它**不得从 VPC 的主要 CIDR 范围或更大的网络进行路由**。 | 云架构师 | 
| 确定可路由的 CIDR 范围。 VPCs | 确定一组将用于您的可路由 CIDR 范围。 VPCs此 CIDR 范围将用作您的主 CIDR。 VPCs | 云架构师 | 
| 创建 VPCs。 | 创建您的 VPCs 并将它们连接到传输网关。根据您在前两个步骤中确定的范围，每个 VPC 都应具有可路由的主要 CIDR 范围和不可路由的辅助 CIDR 范围。 | 云架构师 | 

### 配置中转网关黑洞路由
<a name="configure-transit-gateway-blackhole-routes"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建更具体的不可路由的黑洞 CIDRs 。 | 每个中转网关路由表都需要为不可 CIDRs路由的路由创建一组黑洞路由。这些配置可确保来自辅助 VPC CIDR 的任何流量都不可路由，并且不会泄漏到更大的网络中。这些路由应比 VPC 上设置为辅助 CIDR 的不可路由 CIDR 更具体。例如，如果辅助不可路由的 CIDR 为 100.64.0.0/26，则中转网关路由表中的黑洞路由应为 100.64.0.0/27 和 100.64.0.32/27。 | 云架构师 | 

## 相关资源
<a name="preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets-resources"></a>
+ [部署网关负载均衡器的最佳实践](https://aws.amazon.com/blogs/networking-and-content-delivery/best-practices-for-deploying-gateway-load-balancer/)
+ [使用网关负载均衡器的分布式检查架构](https://d1.awsstatic.com/architecture-diagrams/ArchitectureDiagrams/distributed-inspection-architectures-gwlb-ra.pdf?did=wp_card&trk=wp_card)
+ [Networking Immersion Day ](https://catalog.workshops.aws/networking/en-US/gwlb/lab2-internettovpc)‒ [互联网到 VPC 防火墙实验室](https://catalog.workshops.aws/networking/en-US/gwlb/lab2-internettovpc)
+ [中转网关设计最佳实践](https://docs.aws.amazon.com/vpc/latest/tgw/tgw-best-design-practices.html)

## 附加信息
<a name="preserve-routable-ip-space-in-multi-account-vpc-designs-for-non-workload-subnets-additional"></a>

在处理需要大量 IP 地址的大规模容器部署时，不可路由辅助 CIDR 范围也很有用。您可将此模式与私有 NAT 网关配合使用，从而使用不可路由的子网来托管您的容器部署。有关更多信息，请参阅博客帖子[如何使用私有 NAT 解决方案解决私有 IP 耗尽问题](https://aws.amazon.com/blogs/networking-and-content-delivery/how-to-solve-private-ip-exhaustion-with-private-nat-solution/)。

# 使用代码存储库在中 AWS Service Catalog 配置 Terraform 产品
<a name="provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository"></a>

*Rahul Sharad Gaikwad 博士和 Tamilselvan P，Amazon Web Services*

## Summary
<a name="provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository-summary"></a>

AWS Service Catalog 支持自助服务配置，并管理您的 [HashiCorp Terraform](https://developer.hashicorp.com/terraform/tutorials/aws-get-started) 配置。如果您使用 Terraform，则可以使用 Service Catalog 作为单一工具，在其中大规模组织、管理和分发 Terraform 配置。 AWS 您可以访问 Service Catalog 的主要功能，包括对标准化和预先批准的基础架构即代码 (IaC) 模板进行编目、访问控制、使用最低权限访问的云资源配置、版本控制、与数 AWS 账户千人共享以及标记。最终用户（例如工程师、数据库管理员和数据科学家）会看到其有权访问的产品和版本列表，并且只需一个操作即可完成部署。

此模式可帮助您使用 Terraform 代码部署 AWS 资源。 GitHub 存储库中的 Terraform 代码可通过 Service Catalog 进行访问。借助此方法，您可以将产品整合到现有的 Terraform 工作流中。管理员可以使用 Terraform 创建 Service Catalog AWS Launch Wizard 产品组合并向其中添加产品。

这种解决方案的优点如下：
+ 由于 Service Catalog 中具有回滚功能，因此如果在部署过程中出现任何问题，可以将产品恢复到以前的版本。
+ 您可以轻松识别不同产品版本之间的差异。这有助于在部署期间解决问题。
+ 您可以在 Service Catalog 中配置存储库连接，例如到 GitHub 或 GitLab。您可以直接通过存储库更改产品。

有关总体优势的信息 AWS Service Catalog，请参阅[什么是 Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html)。

## 先决条件和限制
<a name="provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+  GitHub BitBucket、或其他包含 ZIP 格式的 Terraform 配置文件的存储库。
+ AWS Serverless Application Model [已安装](https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/install-sam-cli.html)命令行界面 (AWS SAM CLI)。
+ 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://go.dev/doc/install) Go。
+ Python 版本 3.9，[已安装](https://www.python.org/downloads/release/python-3913/)。 AWS SAM CLI 需要这个版本的 Python。
+ 编写和运行 AWS Lambda 函数的权限以及访问和管理 Service Catalog 产品和产品组合的权限。

## 架构
<a name="provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository-architecture"></a>

![\[通过代码存储库在 Service Catalog 中预调配 Terraform 产品的架构图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/7d0d76e8-9485-4b3f-915f-481b6a7cdcd9/images/e83fa44a-4ca6-4438-a0d1-99f09a3541bb.png)


下图显示了如下工作流：

1. 当 Terraform 配置准备就绪后，开发人员会创建一个包含所有 Terraform 代码的 .zip 文件。开发人员将 .zip 文件上传至连接到 Service Catalog 的代码存储库中。

1. 管理员将 Terraform 产品与 Service Catalog 中的产品组合关联。管理员还会创建启动约束，以便最终用户预调配产品。

1. 在 Service Catalog 中，最终用户使用 Terraform 配置启动 AWS 资源。他们可以选择要部署的产品版本。

## 工具
<a name="provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository-tools"></a>

**AWS 服务**
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html)帮助您集中管理已获批准的 IT 服务目录。 AWS最终用户可在遵循组织设定约束的情况下快速部署他们所需已获得批准的 IT 服务。

**其他服务**
+ [Go](https://go.dev/doc/install) 是谷歌支持的开源编程语言。
+ [Python](https://www.python.org/) 是通用的计算机编程语言。

**代码存储库**

如果您需要可通过 Service Catalog 部署的 Terraform 示例配置，则可以使用 [Amazon Mac GitHub ie 组织设置](https://github.com/aws-samples/aws-macie-customization-terraform-samples)使用 Terraform 存储库中的配置。并非必须使用此存储库中的代码示例。

## 最佳实践
<a name="provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository-best-practices"></a>
+ 在通过 Service Catalog 启动产品时配置变量值，而不是在 Terraform 配置文件 (`terraform.tfvars`) 中提供变量的值。
+ 仅向特定用户或管理员授予对产品组合的访问权限。
+ 遵循最低权限原则，并授予执行任务所需的最低权限。有关更多信息，请参阅 AWS Identity and Access Management (IAM) 文档中的[授予最低权限](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#grant-least-priv)和[安全最佳实践](https://docs.aws.amazon.com/IAM/latest/UserGuide/IAMBestPracticesAndUseCases.html)。

## 操作说明
<a name="provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository-epics"></a>

### 设置本地工作站
<a name="set-up-your-local-workstation"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| （可选）安装 Docker。 | 如果要在开发环境中运行这些 AWS Lambda 函数，请安装 Docker。有关说明，请参阅 Docker 文档中的[安装 Docker 引擎](https://docs.docker.com/engine/install/)。 | DevOps 工程师 | 
| 为 Terraform 安装 AWS Service Catalog 引擎。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | DevOps 工程师，AWS 管理员 | 

### Connect GitHub 存储库
<a name="connect-the-github-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建与 GitHub 存储库的连接。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | AWS 管理员 | 

### 在 Service Catalog 中创建 Terraform 产品
<a name="create-a-terraform-product-in-service-catalog"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Service Catalog 产品。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | AWS 管理员 | 
| 创建产品组合。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | AWS 管理员 | 
| 将 Terraform 产品添加到产品组合中。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | AWS 管理员 | 
| 创建访问策略。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | AWS 管理员 | 
| 创建自定义信任策略。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | AWS 管理员 | 
| 向 Service Catalog 产品添加启动约束。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | AWS 管理员 | 
| 授予对产品的访问权限。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | AWS 管理员 | 
| 启动产品。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | DevOps 工程师 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证部署。 | Service Catalog 配置工作流程有两台 AWS Step Functions 状态机：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html)您可以检查 `ManageProvisionedProductStateMachine` 状态机的日志，以确认产品已预调配。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | DevOps 工程师 | 

### 清理基础设施
<a name="clean-up-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除预调配产品。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | DevOps 工程师 | 
| 移除 Terraform 的 AWS Service Catalog 引擎。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository.html) | AWS 管理员 | 

## 相关资源
<a name="provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository-resources"></a>

**AWS 文档**
+ [开始使用 Terraform 产品](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/getstarted-Terraform.html)

**Terraform 文档**
+ [Terraform installation](https://learn.hashicorp.com/tutorials/terraform/install-cli)（Terraform 安装）
+ [Terraform 后端配置](https://developer.hashicorp.com/terraform/language/backend)
+ [Terraform AWS 提供者文档](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)

## 附加信息
<a name="provision-a-terraform-product-in-aws-service-catalog-by-using-a-code-repository-additional"></a>

**访问策略**

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "s3:GetObject",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "s3:ExistingObjectTag/servicecatalog:provisioning": "true"
                }
            }
        },
        {
            "Action": [
                "s3:CreateBucket*",
                "s3:DeleteBucket*",
                "s3:Get*",
                "s3:List*",
                "s3:PutBucketTagging"
            ],
            "Resource": "arn:aws:s3:::*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "resource-groups:CreateGroup",
                "resource-groups:ListGroupResources",
                "resource-groups:DeleteGroup",
                "resource-groups:Tag"
            ],
            "Resource": "*",
            "Effect": "Allow"
        },
        {
            "Action": [
                "tag:GetResources",
                "tag:GetTagKeys",
                "tag:GetTagValues",
                "tag:TagResources",
                "tag:UntagResources"
            ],
            "Resource": "*",
            "Effect": "Allow"
        }
    ]
}
```

**信任策略**

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "GivePermissionsToServiceCatalog",
            "Effect": "Allow",
            "Principal": {
                "Service": "servicecatalog.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        },
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::account_id:root"
            },
            "Action": "sts:AssumeRole",
            "Condition": {
                "StringLike": {
                    "aws:PrincipalArn": [
                        "arn:aws:iam::accounti_id:role/TerraformEngine/TerraformExecutionRole*",
                        "arn:aws:iam::accounti_id:role/TerraformEngine/ServiceCatalogExternalParameterParserRole*",
                        "arn:aws:iam::accounti_id:role/TerraformEngine/ServiceCatalogTerraformOSParameterParserRole*"
                    ]
                }
            }
        }
    ]
}
```

# 使用 Amazon AWS 账户 SES 使用一个电子邮件地址注册多个邮箱
<a name="register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses"></a>

*Joe Wozniak 和 Shubhangi Vishwakarma，Amazon Web Services*

## Summary
<a name="register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses-summary"></a>

此模式描述了如何将真实的电子邮件地址与与之关联的电子邮件地址分开。 AWS 账户 AWS 账户 要求在创建账户时提供唯一的电子邮件地址。在某些组织中，管理团队 AWS 账户 必须承担与其邮件团队一起管理许多唯一电子邮件地址的负担。对于管理许多企业的大型组织来说，这可能很困难 AWS 账户。此外，如果您的电子邮件系统不允许 [Sieve 电子邮件筛选：子地址扩展（RFC 5233）](https://datatracker.ietf.org/doc/html/rfc5233)中定义的*加号寻址*或*子寻址*，则通过在电子邮件地址本地部分的末尾添加加号（\$1）和标识符（例如 `admin+123456789123@example.com`），此模式可以帮助克服此限制。

这种模式提供了一种独特的电子邮件地址自动售货解决方案，使 AWS 账户 所有者能够将一个电子邮件地址与多个电子邮件地址相关联 AWS 账户。然后， AWS 账户 所有者的真实电子邮件地址与表格中生成的这些电子邮件地址相关联。该解决方案处理唯一电子邮件账户的所有传入电子邮件，查找每个账户的拥有者，然后将收到的所有邮件转发给拥有者。 

## 先决条件和限制
<a name="register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses-prereqs"></a>

**先决条件**
+ 对的管理访问权限 AWS 账户。
+ 可以进入开发环境。
+ （可选）熟悉 AWS Cloud Development Kit (AWS CDK) 工作流程和 Python 编程语言将帮助您解决任何问题或进行修改。

**限制**
+ 出售的电子邮件地址的总长度为 64 个字符。有关详细信息，请参阅 *AWS Organizations API 参考[CreateAccount](https://docs.aws.amazon.com/organizations/latest/APIReference/API_CreateAccount.html)*中的。

**产品版本**
+ Node.js 版本 22.x 或更高版本
+ Python 3.13 或更高版本
+ Python 软件包 **pip** 和 **virtualenv**
+ AWS CDK CLI 版本 2.1019.2 或更高版本
+ Docker 20.10.x 或更高版本

## 架构
<a name="register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses-architecture"></a>

**目标技术堆栈**
+ CloudFormation 堆栈
+ AWS Lambda 函数
+ Amazon Simple Email Service（Amazon SES）规则和规则集
+ AWS Identity and Access Management (IAM) 角色和策略
+ Amazon Simple Storage Service (Amazon S3) 存储桶和存储桶策略
+ AWS Key Management Service (AWS KMS) 密钥和密钥策略
+ Amazon Simple Notification Service(Amazon SNS) 主题和主题策略
+ Amazon DynamoDB 表 

**目标架构 **

![\[使用单个电子邮件地址注册多个 Amazon Web Services account 目标架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/1be85b92-69e5-43b2-aeed-27b9509e145e/images/c7ae9d7a-d4e0-412e-97cb-0f3073e012e7.png)


此图显示了两个流程：
+ **电子邮件地址自动售货流程：**在图中，电子邮件地址自动售货流程（下部分）通常从账户自动售货解决方案或外部自动化开始，或者手动调用。在请求中，使用包含所需元数据的负载调用 Lambda 函数。该函数使用此信息生成唯一的账户名和电子邮件地址，将其存储在 DynamoDB 数据库，然后将值返回给调用方。然后，可以使用这些值来创建新值 AWS 账户 （通常通过使用 AWS Organizations）。
+ **电子邮件转发流程：**此流程如上图的上半部分所示。使用电子邮件 AWS 账户 地址自动售货流程生成的账户电子邮件创建时， AWS 会向该电子邮件地址发送各种电子邮件，例如账户注册确认和定期通知。按照此模式中的步骤操作，您可以将 with Amazon SES 配置为接收整个域的电子邮件。 AWS 账户 此解决方案配置了转发规则，允许 Lambda 处理所有传入的电子邮件，检查该 `TO` 地址是否在 DynamoDB 表中，然后将邮件转发到账户拥有者的电子邮件地址。使用此流程，账户拥有者可以将多个账户与一个电子邮件地址相关联。

**自动化和扩展**

此模式使用 AWS CDK 来完全自动化部署。该解决方案使用 AWS 托管服务，这些服务将（或可以配置为）自动扩展以满足您的需求。Lambda 函数可能需要额外配置才能满足您的扩缩需求。有关更多信息，请参阅 Lambda 文档中的[了解 Lambda 函数扩缩](https://docs.aws.amazon.com/lambda/latest/dg/invocation-scaling.html)。

## 工具
<a name="register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses-tools"></a>

**AWS 服务**
+ [CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)帮助您设置 AWS 资源，快速一致地配置资源，并在资源的整个生命周期中跨地区对其 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 数据库服务，可提供快速、可预测、可扩展的性能。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 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) 是一项计算服务，可帮助您运行代码，无需预调配或管理服务器。它只在需要时运行您的代码，并自动进行扩展，因此您只需为使用的计算时间付费。
+ [Amazon Simple Email Service (Amazon SES)](https://docs.aws.amazon.com/ses/latest/dg/Welcome.html) 帮助您通过使用您自己的电子邮件地址和域发送和接收电子邮件。
+ [Amazon Simple Notiﬁcation 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 CLI 和 IAM 访问权限的开发环境 AWS 账户。 有关详细信息，请参阅 “[相关资源](#register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses-resources)” 部分中的链接。 
+ 在您的开发系统上，安装以下项：
  + Git 命令行工具，可通过 [Git 下载网站](https://git-scm.com/downloads)获取。
  + 用于 AWS CLI 为配置访问凭证 AWS CDK。有关详情，请参阅 [AWS CLI 文档](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)。
  + Python 版本 3.13 或更高版本，可通过 [Python 下载网站](https://www.python.org/downloads/)获取。
  + 用于 Python 包管理的 UV。有关安装说明，请参阅 [UV 安装指南](https://docs.astral.sh/uv/getting-started/installation/)。
  + Node.js 版本 22.x 或更高版本。有关安装说明，请参阅 [Node.js 文档](https://nodejs.org/en/learn/getting-started/how-to-install-nodejs)。
  + AWS CDK CLI 版本 2.1019.2 或更高版本。有关安装说明，请参阅 [AWS CDK 文档](https://docs.aws.amazon.com/cdk/v2/guide/getting-started.html#getting-started-install)。
  + Docker 版本 20.10.x 或更高版本。有关安装说明，请参阅 [Docker 文档](https://docs.docker.com/engine/install/)。

**代码**

此模式的代码可在 GitHub [AWS 账户 工厂电子邮件](https://github.com/aws-samples/aws-account-factory-email)存储库中找到。

## 操作说明
<a name="register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses-epics"></a>

### 分配目标部署环境
<a name="allocate-a-target-deployment-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 识别或创建 AWS 账户. | 确定您拥有完全管理权限 AWS 账户 的现有或新的电子邮件解决方案，以部署电子邮件解决方案。 | AWS 管理员、云管理员 | 
| 设置部署环境。 | 按照以下步骤配置易于使用的部署环境并设置依赖项：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses.html) | AWS DevOps，应用程序开发者 | 

### 设置验证的域
<a name="set-up-a-verified-domain"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 识别和分配域。 | 电子邮件转发功能需要专用域。识别并分配您可以使用 Amazon SES 验证的域或子域。此域应可用于在部署电子邮件转发解决方案 AWS 账户 的地方接收传入的电子邮件。域要求：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses.html) | 云管理员、网络管理员、DNS 管理员 | 
| 验证域。 | 验证所识别的域是否可用于接受传入电子邮件。完成 Amazon SES 文档中的[验证您的域以接收 Amazon SES 电子邮件](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-verification.html)中的说明。这需要与负责域的 DNS 记录人员或团队进行协调。 | AWS 应用程序开发人员 DevOps | 
| 设置 MX 记录。 | 使用指向您和地区的 Amazon SES 终端节点的 MX 记录来设置您的 AWS 账户 域名。有关更多信息，请参阅 Amazon SES 文档中的[发布 Amazon SES 电子邮件接收的 MX 记录](https://docs.aws.amazon.com/ses/latest/dg/receiving-email-mx-record.html)。 | 云管理员、网络管理员、DNS 管理员 | 

### 部署电子邮件自动售卖和转发解决方案
<a name="deploy-the-email-vending-and-forwarding-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 修改 `cdk.json` 中的默认值。 | 编辑 `cdk.json` 文件中的一些默认值（位于存储库的根目录），以便解决方案在部署后能够正常运行。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses.html) | AWS 应用程序开发人员 DevOps | 
| 部署电子邮件自动售卖与转发解决方案。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses.html) | AWS 应用程序开发人员 DevOps | 
| 验证解决方案是否已部署。 | 开始测试之前，验证解决方案是否成功部署：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses.html) | AWS 应用程序开发人员 DevOps | 

### 验证电子邮件自动售卖和转发是否按预期运行
<a name="verify-that-email-vending-and-forwarding-operate-as-expected"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证该 API 是否正常运行。 | 在此步骤中，您将测试数据提交到解决方案的 API，并确认解决方案产生预期输出并且后端操作已按预期执行。使用测试输入，手动运行 **Vend Email** Lambda 函数。(有关示例，请参阅 [sample\$1vend\$1request.json 文件](https://github.com/aws-samples/aws-account-factory-email/blob/main/src/events/sample_vend_request.json)。) 对于 `OwnerAddress`，请使用有效的电子邮件地址。API 应返回账户名和账户电子邮件以及预期的值。 | AWS 应用程序开发人员 DevOps | 
| 确认电子邮件已转发。 | 在此步骤中，您通过系统发送测试电子邮件并验证电子邮件是否转发给预期收件人。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses.html) | AWS 应用程序开发人员 DevOps | 

## 问题排查
<a name="register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 系统无法按预期转发电子邮件。 | 验证您的设置是否正确：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses.html)验证域设置后，请按下列步骤操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses.html) | 
| 当你尝试部署 AWS CDK 堆栈时，你会收到类似于以下内容的错误：“模板格式错误：无法识别的资源类型”  | 在大多数情况下，此错误消息意味着您所定位的区域没有所有可用的 Amazon Web Services。如果您使用 Amazon EC2 实例来部署解决方案，则您的目标区域可能与实例运行的区域不同。默认情况下，会 AWS CDK 部署到您在中配置的区域和账户。 AWS CLI可能的解决方案：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses.html) | 
| 部署此解决方案时，您会收到错误消息：“部署失败：错误: AwsMailFwdStack: SSM 参数 /cdk-bootstrap/hnb659fds/version 未找到。是否已引导环境？ 请运行 'cdk bootstrap'” | 如果您从未将任何 AWS CDK 资源部署到目标 AWS 账户 和区域，则必须先按照错误指示运行该`cdk bootstrap`命令。如果在运行引导命令后继续收到此错误，则您可能正在尝试将解决方案部署到与运行开发环境的区域不同的区域。要解决此问题，请在部署解决方案 AWS CLI 之前设置`AWS_DEFAULT_REGION`环境变量或使用设置区域。或者，您可按照 [AWS CDK 环境文档](https://docs.aws.amazon.com/cdk/v2/guide/environments.html)中的说明修改存储库根目录中的 `app.py` 文件，使其包含硬编码的账户 ID 和区域。 | 

## 相关资源
<a name="register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses-resources"></a>
+ 有关安装的帮助 AWS CLI，请参阅[安装或更新到最新版本的 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html)。
+ 有关 AWS CLI 使用 IAM 访问凭证设置的帮助，请参阅[配置设置 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)。
+ 有关方面的帮助 AWS CDK，请参阅《[入门》 AWS CDK](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html#getting_started_install)。

## 附加信息
<a name="register-multiple-aws-accounts-with-a-single-email-address-by-using-amazon-ses-additional"></a>

**成本**

部署此解决方案时， AWS 账户 持有者可能会产生与使用以下服务相关的费用。 对您来说，了解这些服务的计费方式非常重要，这样您就可以了解任何潜在的费用。有关定价信息，请参阅以下页面：
+ [Amazon SES 定价](https://aws.amazon.com/ses/pricing/)
+ [Amazon S3 定价](https://aws.amazon.com/s3/pricing/)
+ [AWS KMS 定价](https://aws.amazon.com/kms/pricing/)
+ [AWS Lambda 定价](https://aws.amazon.com/lambda/pricing/)
+ [Amazon DynamoDB 定价](https://aws.amazon.com/dynamodb/pricing/)

# 在单账户 AWS 环境中为混合网络设置 DNS 解析
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-single-account-aws-environment"></a>

*Abdullahi Olaoye，Amazon Web Services*

## Summary
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-single-account-aws-environment-summary"></a>

此模式描述了如何设置完全混合的域名系统 (DNS) 架构，该架构支持本地资源、AW end-to-end S 资源和互联网 DNS 查询的 DNS 解析，而无需管理开销。该模式描述了如何设置 Amazon Route 53 Resolver 转发规则，以根据域名确定应将源自 AWS 的 DNS 查询发送到何处。对本地资源的 DNS 查询将转发到本地 DNS 解析程序。AWS 资源的 DNS 查询和互联网 DNS 查询由 Route 53 解析程序解析。

此模式涵盖 AWS 单账户环境中的混合 DNS 解析。有关在 AWS 多账户环境中设置出站 DNS 查询的信息，请参阅[在多账户 AWS 环境中为混合网络设置 DNS 解析](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment.html)。

## 先决条件和限制
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-single-account-aws-environment-prereqs"></a>

**先决条件**
+ 一个 Amazon Web Services account 
+ 您的 Amazon Web Services account 中的虚拟私有云（VPC）
+ 通过 AWS 虚拟专用网络 (AWS VPN) 或 AWS Direct Connect 在本地环境和 VPC 之间建立网络连接
+ 您的本地 DNS 解析程序的 IP 地址（可从您的 VPC 访问）
+ 要转发给本地解析程序的域名/子域名（例如 onprem.mydc.com）
+ AWS 私有托管区的域名/子域名（例如 myvpc.cloud.com）

## 架构
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-single-account-aws-environment-architecture"></a>

**目标技术堆栈**
+ Amazon Route 53 私有托管区
+ Amazon Route 53 Resolver
+ Amazon VPC
+ AWS VPN 或 Direct Connect

**目标架构**

![\[使用 Route 53 Resolver 在 AWS 单账户环境中进行混合 DNS 解析的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/120dedc8-cc6c-4aa7-be11-c70a7ee80642/images/7b75f534-1adc-4a39-86d6-5c4596ff7b6a.png)


 

## 工具
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-single-account-aws-environment-tools"></a>
+ [Amazon Route 53 Resolver](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-getting-started.html) 通过在整个混合云实现无缝 DNS 查询解析，让企业客户更轻松地使用混合云。您可以创建 DNS 终端节点和条件转发规则，以解析本地数据中心和您的数据中心之间的 DNS 命名空间。 VPCs
+ [Amazon Route 53 私有托管区域](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html)是一个容器，其中包含有关您希望 Route 53 如何响应您使用 Amazon VPC 服务创建的一个或多个 VPCs 域中的域及其子域的 DNS 查询的信息。

## 操作说明
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-single-account-aws-environment-epics"></a>

### 配置私有托管区
<a name="configure-a-private-hosted-zone"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 AWS 保留域名（例如 myvpc.cloud.com）创建 Route 53 私有托管区。 | 该区域保存应从本地环境解析的 AWS 资源 DNS 记录。有关说明，请参阅 Route 53 文档中的[创建私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zone-private-creating.html)。 | 网络管理员、系统管理员 | 
| 将此私有托管区与分支账户 VPC 相关联。 | 要使 VPC 中的资源能够解析此私有托管区中的 DNS 记录，您必须将您的 VPC 与托管区关联。有关说明，请参阅 Route 53 文档中的[创建私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zone-private-creating.html)。 | 网络管理员、系统管理员 | 

### 设置 Route 53 解析程序 端点
<a name="set-up-route-53-resolver-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 地址。 | 网络管理员、系统管理员 | 
| 创建出站端点。 | Route 53 解析程序使用出站端点向本地 DNS 解析程序发送 DNS 查询。有关说明，请参阅 Route 53 文档中的[将出站 DNS 查询转发到您的网络](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-forwarding-outbound-queries.html)。记下输出端点 ID。 | 网络管理员、系统管理员 | 

### 设置转发规则并将其与您的 VPC 关联
<a name="set-up-a-forwarding-rule-and-associate-it-with-your-vpc"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为本地域创建转发规则 | 此规则将指示 Route 53 解析程序将本地域（例如 onprem.mydc.com）的任何 DNS 查询转发给本地 DNS 解析程序。要创建此规则，您需要本地 DNS 解析程序的 IP 地址和 Route 53 解析程序的出站端点 ID。有关说明，请参阅 Route 53 文档中的[管理转发规则](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-rules-managing.html)。 | 网络管理员、系统管理员 | 
| 将转发规则与 VPC 关联。 | 若要使转发规则生效，您必须将该规则与您的 VPC 关联起来。然后，Route 53 解析程序 在解析域名时会考虑该规则。有关说明，请参阅 Route 53 文档中的[管理转发规则](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-rules-managing.html)。 | 网络管理员、系统管理员 | 

### 配置本地 DNS 解析程序
<a name="configure-on-premises-dns-resolvers"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在内部部署 DNS 解析程序中配置条件转发。 | 要从本地环境向 Route 53 私有托管区发送 DNS 查询，您必须在本地 DNS 解析程序中配置条件转发。这指示 DNS 解析程序将 AWS 域（例如 myvpc.cloud.com）的所有 DNS 查询转发到 Route 53 解析程序的入站端点 IP 地址。 | 网络管理员、系统管理员 | 

### 测试 end-to-end DNS 解析度
<a name="test-end-to-end-dns-resolution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 测试 AWS 到本地环境的 DNS 解析。 | 在 VPC 中的服务器上，对本地域（例如 server1.onprem.mydc.com）执行 DNS 查询。 | 网络管理员、系统管理员 | 
| 测试从本地环境到 AWS 的 DNS 解析。 | 在本地服务器上，对 AWS 域（例如 serv1.myvpc.cloud.com）执行 DNS 解析。 | 网络管理员、系统管理员 | 

## 相关资源
<a name="set-up-dns-resolution-for-hybrid-networks-in-a-single-account-aws-environment-resources"></a>
+ [使用 Amazon Route 53 和 AWS Transit Gateway 对混合云进行集中 DNS 管理](https://aws.amazon.com/blogs/networking-and-content-delivery/centralized-dns-management-of-hybrid-cloud-with-amazon-route-53-and-aws-transit-gateway/)（AWS 网络与内容交付博客）
+ [使用 Route 53 Resolver 简化多账户环境中的 DNS 管理](https://aws.amazon.com/blogs/security/simplify-dns-management-in-a-multiaccount-environment-with-route-53-resolver/)（AWS Security 博客文章）
+ [使用私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html)（Route 53 文档）
+ [Route 53 解析程序 入门](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resolver-getting-started.html)（Route 53 文档）

# 使用 AWS 在亚马逊 EC2 上自动设置 UiPath RPA 机器人 CloudFormation
<a name="set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation"></a>

*Rahul Sharad Gaikwad 博士和 Tamilselvan P，Amazon Web Services*

## Summary
<a name="set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation-summary"></a>

此模式说明了如何在亚马逊弹性计算云 (Amazon) 实例上部署机器人流程自动化 (RPA EC2) 机器人。它使用 I [EC2 mage Builder](https://docs.aws.amazon.com/imagebuilder/latest/userguide/what-is-image-builder.html) 管道来创建自定义的亚马逊系统映像 (AMI)。AMI 是一种预配置的虚拟机 (VM) 映像，其中包含用于部署 EC2 实例的操作系统 (OS) 和预安装的软件。此模式使用 AWS CloudFormation 模板在自定义 AMI 上安装 [UiPath Studio 社区版](https://www.uipath.com/product/studio)。 UiPath 是一款 RPA 工具，可帮助您设置机器人来自动执行任务。

作为该解决方案的一部分，使用基本 AMI 启动 EC2 Windows 实例，并在实例上安装 UiPath Studio 应用程序。该模式使用 Microsoft 系统准备（Sysprep）工具复制自定义的 Windows 安装。之后，它删除主机信息并从实例创建最终 AMI。然后，您可以使用最终的 AMI 以及您自己的命名约定和监控设置来按需启动实例。


| 
| 
| 注意：此模式不提供有关使用 RPA 机器人的任何信息。有关该信息，请参阅[UiPath 文档](https://docs.uipath.com/)。您也可使用此模式根据您的要求自定义安装步骤来设置其他 RPA 机器人应用程序。 | 
| --- |

此模式提供以下自动化和优点：
+ 应用程序部署和共享：您可以构建 Amazon EC2 AMIs 以进行应用程序部署，并通过 I EC2 mage Builder 管道在多个账户之间共享它们，该管道使用 AWS CloudFormation 模板作为基础设施即代码 (IaC) 脚本。
+ Amazon EC2 配置和扩展： CloudFormation IaC 模板提供自定义计算机名称序列和 Active Directory 自动加入功能。
+ 可观察性和监控：该模式设置了亚马逊 CloudWatch 控制面板，以帮助您监控亚马逊 EC2 指标（例如 CPU 和磁盘使用率）。
+ RPA 为您的企业带来的好处：RPA 提高了准确性，因为机器人可以自动、一致地执行分配的任务。RPA 还可以提高速度和生产力，因为它消除了不增加价值的操作并处理重复的活动。

## 先决条件和限制
<a name="set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation-prereqs"></a>

**先决条件**
+ 一个有效的 [Amazon Web Services account](https://aws.amazon.com/free/)
+ 用于部署 CloudFormation 模板@@ [的 AWS Identity and Access Management (IAM) 权限](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html)
+ 用于@@ [使用 Im EC2 age Builder 设置跨账户 AMI 分发的 IAM 策略](https://docs.aws.amazon.com/imagebuilder/latest/userguide/cross-account-dist.html)

## 架构
<a name="set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation-architecture"></a>

![\[用于在亚马逊上设置 RPA 机器人的目标架构 EC2\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/5555a62d-91d4-4e81-9961-ff89faedd6ad/images/1893d2d3-8912-4473-adf1-6633b5badcd9.png)


1. 管理员在`ec2-image-builder.yaml`文件中提供基本 Windows AMI，并在 CloudFormation 控制台中部署堆栈。

1.  CloudFormation 堆栈部署 EC2 Image Builder 管道，其中包括以下资源：
   + `Ec2ImageInfraConfiguration`
   + `Ec2ImageComponent`
   + `Ec2ImageRecipe`
   + `Ec2AMI`

1.  EC2 Image Builder 管道使用基本 AMI 启动临时 Windows EC2 实例并安装所需的组件（在本例中为 UiPath Studio）。

1.  EC2 Image Builder 会删除所有主机信息并从 Windows 服务器中创建 AMI。

1. 您可以使用自定义 AMI 更新`ec2-provisioning yaml`文件并根据您的要求启动多个 EC2 实例。

1. 您可以使用 CloudFormation 模板部署 Count 宏。此宏为 CloudFormation 资源提供了 C **ount** 属性，因此您可以轻松地指定多个相同类型的资源。

1. 更新 CloudFormation `ec2-provisioning.yaml`文件中宏的名称并部署堆栈。

1. 管理员根据要求更新 `ec2-provisioning.yaml` 文件并启动堆栈。

1. 该模板使用 UiPath Studio 应用程序部署 EC2 实例。

## 工具
<a name="set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation-tools"></a>

**AWS 服务**
+ [AWS CloudFormation](https://aws.amazon.com/cloudformation/) 可帮助您以自动且安全的方式对基础设施资源进行建模和管理。
+ [Amazon CloudWatch](https://aws.amazon.com/cloudwatch/) 可帮助您观察和监控 AWS、本地和其他云上的资源和应用程序。
+ [亚马逊弹性计算云 (Amazon EC2](https://aws.amazon.com/ec2/)) 在 AWS 云中提供安全且可调整大小的计算容量。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [EC2 Image Builder](https://aws.amazon.com/image-builder/) 简化了在 AWS 上或本地使用的虚拟机和容器镜像的构建、测试和部署。
+ [Amazon EventBridge](https://aws.amazon.com/eventbridge/) 可帮助您在 AWS、现有系统或软件即服务 (SaaS) 应用程序中大规模构建事件驱动型应用程序。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 可帮助您安全地控制对您 AWS 资源的访问。借助 IAM，您可以集中管理控制用户可访问哪些 AWS 资源的权限。可以使用 IAM 来控制谁通过了身份验证(准许登录)并获得授权(拥有权限)来使用资源。
+ [AWS Lambda](https://aws.amazon.com/lambda/) 是一项无服务器、事件驱动计算服务，让您能够为几乎任何类型的应用程序或后端服务运行代码，而无需预调配或管理服务器。您可以从 200 多种 Amazon Web Services 和 SaaS 应用程序中调用 Lambda 函数，并且只需按实际使用量付费。
+ [Amazon Simple Storage Service (Amazon S3)](https://aws.amazon.com/s3/) 是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。
+ [AWS Systems Manager 代理 (SSM 代理)](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html) 可帮助 Systems Manager 更新、管理和配置 EC2 实例、边缘设备、本地服务器和虚拟机 (VMs)。

**代码存储库**

此模式的代码可在[使用 CloudFormation存储库的 GitHub UiPath RPA 机器人设置](https://github.com/aws-samples/uipath-rpa-setup-ec2-windows-ami-cloudformation)中找到。该模式还使用 A [WS Mac CloudFormation ros 存储库中提供的宏。](https://github.com/aws-cloudformation/aws-cloudformation-macros/tree/master/Count)

## 最佳实践
<a name="set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation-best-practices"></a>
+ AWS 每月 AMIs都会发布新的 [Windows](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/windows-ami-version-history.html)。其中包含最新的操作系统补丁、驱动程序和启动代理。您应该在启动新实例或构建自己的自定义镜像时利用最新的 AMI。
+ 在镜像生成期间应用所有可用的 Windows 或 Linux 安全补丁。

## 操作说明
<a name="set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation-epics"></a>

### 为基础镜像部署镜像管道
<a name="deploy-an-image-pipeline-for-the-base-image"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 EC2 Image Builder 管道。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html) | AWS DevOps | 
| 查看 EC2 Image Builder 设置。 |  EC2 Image Builder 设置包括基础架构配置、分发设置和安全扫描设置。若要查看设置，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html)最佳做法是，应仅通过 CloudFormation 模板对 EC2 Image Builder 进行任何更新。 | AWS DevOps | 
| 查看镜像管道。 | 要查看已部署的镜像管道，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html) | AWS DevOps | 
| 查看 Image Builder 日志。 | EC2 Image Builder 日志按 CloudWatch 日志组进行聚合。要查看日志，请执行 CloudWatch以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html)EC2 Image Builder 日志也存储在 S3 存储桶中。若要查看存储桶中的日志，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html) | AWS DevOps | 
| 将 UiPath 文件上传到 S3 存储桶。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html) | AWS DevOps | 

### 部署并测试 Count 宏
<a name="deploy-and-test-the-count-macro"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署计数宏。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html)如果要使用控制台，请按照上一篇长篇故事或[CloudFormation 文档](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)中的说明进行操作。  | DevOps 工程师 | 
| 测试计数宏。 | 若要测试宏的功能，请尝试启动宏附带的示例模板。 <pre>aws cloudformation deploy \<br />    --stack-name Count-test \<br />    --template-file test.yaml \<br />    --capabilities CAPABILITY_IAM</pre> | DevOps 工程师 | 

### 部署 CloudFormation 堆栈以使用自定义映像配置实例
<a name="deploy-the-cloudformation-stack-to-provision-instances-with-the-custom-image"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 Amazon EC2 配置模板。 | 要部署 EC2 映像管道，请使用 CloudFormation以下方法：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html) | AWS DevOps | 
| 查看 Amazon EC2 设置。 | Amazon EC2 设置包括安全、联网、存储、状态检查、监控和标签配置。若要查看这些配置，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html) | AWS DevOps | 
| 查看 CloudWatch 控制面板。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html)预调配堆栈后，需要一段时间才能在控制面板中填充指标。控制面板提供以下指标：`CPUUtilization`、`DiskUtilization`、`MemoryUtilization`、`NetworkIn`、`NetworkOut`、`StatusCheckFailed`。 | AWS DevOps | 
| 查看关于内存和磁盘使用情况的自定义指标。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html) | AWS DevOps | 
| 查看内存与磁盘使用情况警报。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html) | AWS DevOps | 
| 验证快照生命周期规则。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html) | AWS DevOps | 

### 删除环境（可选）
<a name="delete-the-environment-optional"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除堆栈。 | PoC 或试点项目完成后，我们建议您删除创建的堆栈，以确保您无需为这些资源付费。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.html)堆栈删除操作开始后就无法停止。堆栈进入 `DELETE_IN_PROGRESS`状态。如果删除失败，则堆栈将处于 `DELETE_FAILED` 状态。有关解决方案，请参阅 AWS CloudFormation 疑难解答文档中的[删除堆栈失败](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html#troubleshooting-errors-delete-stack-fails)。有关保护堆栈不被意外删除的信息，请参阅 AWS CloudFormation 文档中的[保护堆栈不被删除](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-protect-stacks.html)。 | AWS DevOps | 

## 问题排查
<a name="set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 当你部署 Amazon EC2 配置模板时，你会收到错误消息：*收到来自转换 123xxxx:: Count 的格式错误的响应*。 | 这是一个已知问题。（参见 [AW CloudFormation S 宏存储库](https://github.com/aws-cloudformation/aws-cloudformation-macros/pull/20)中的自定义解决方案和 PR。）[要修复此问题，请打开 AWS Lambda 控制台并`index.py`使用存储库中的GitHub 内容进行更新。](https://raw.githubusercontent.com/aws-cloudformation/aws-cloudformation-macros/f1629c96477dcd87278814d4063c37877602c0c8/Count/src/index.py)  | 

## 相关资源
<a name="set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation-resources"></a>

**GitHub 存储库**
+ [UiPath 使用 RPA 机器人设置 CloudFormation](https://github.com/aws-samples/uipath-rpa-setup-ec2-windows-ami-cloudformation)
+ [计数 CloudFormation 宏](https://github.com/aws-cloudformation/aws-cloudformation-macros/tree/master/Count)

**AWS 参考**
+ 在 [AWS CloudFormation 控制台上创建堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)（CloudFormation 文档）
+ [故障排除 CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/troubleshooting.html)（CloudFormation 文档）
+ [监控亚马逊 EC2 实例的内存和磁盘指标](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/mon-scripts.html)（亚马逊 EC2 文档）
+ [如何使用 CloudWatch 代理在 Windows 服务器上查看 “性能监视器” 的指标？](https://repost.aws/knowledge-center/cloudwatch-performance-monitor-windows) （AWS re: Post 文章）

**其他参考资料**
+ [UiPath 文档](https://docs.uipath.com/)
+ 在 [ SysPreped AMI 中设置主机名](https://blog.brianbeach.com/2014/07/setting-hostname-in-syspreped-ami.html)（Brian Beach 的博客文章）
+ [当参数发生变化时，如何让 Cloudformation 通过宏重新处理模板？](https://stackoverflow.com/questions/59828989/how-do-i-make-cloudformation-reprocess-a-template-using-a-macro-when-parameters) 堆栈溢出

# 在 AWS 上设置高度可用的 PeopleSoft 架构
<a name="set-up-a-highly-available-peoplesoft-architecture-on-aws"></a>

*Ramanathan Muralidhar，Amazon Web Services*

## Summary
<a name="set-up-a-highly-available-peoplesoft-architecture-on-aws-summary"></a>

当您将 PeopleSoft 工作负载迁移到 AWS 时，弹性是一个重要的目标。它可确保您的 PeopleSoft 应用程序始终保持高可用性，并能够快速从故障中恢复。

此模式为您在 AWS 上的 PeopleSoft 应用程序提供了一个架构，可确保网络、应用程序和数据库层的高可用性 (HA)。它将 [Amazon Relational Database Service (Amazon RDS)](https://aws.amazon.com/rds/) 用于 Oracle，或将 Amazon RDS for SQL Server 数据库用于数据库层。该架构还包括例如以下的 AWS 服务：[Amazon Route 53](https://aws.amazon.com/route53/)、[Amazon Elastic Compute Cloud（Amazon EC2）](https://aws.amazon.com/ec2/) Linux 实例、[Amazon Elastic Block Storage（Amazon EBS）](https://aws.amazon.com/ebs/)、[Amazon Elastic File System（Amazon EFS）](https://aws.amazon.com/efs/)以及[应用程序负载均衡器](https://aws.amazon.com/elasticloadbalancing/application-load-balancer)，并且具有可扩展性。

[Oracle PeopleSoft](https://www.oracle.com/applications/peoplesoft/) 为劳动力管理和其他业务运营提供了一套工具和应用程序。

## 先决条件和限制
<a name="set-up-a-highly-available-peoplesoft-architecture-on-aws-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 具有在 AWS 上进行设置所需的许可证的 PeopleSoft 环境
+ 您的 Amazon Web Services account 中设置的虚拟私有云（VPC）包含以下资源：
  + 至少两个可用区
  + 每个可用区中有 1 个公有子网和 3 个私有子网
  + NAT 网关和互联网网关
  + 每个子网的路由表用于路由流量
  + 根据贵组织的标准定义的网络访问控制列表（网络 ACLs）和安全组，以帮助确保 PeopleSoft 应用程序的安全

**限制**
+ 这种模式提供高可用性 (HA) 解决方案。它不支持灾难恢复 (DR) 方案。在极少数情况下，用于实现 HA 的整个 AWS 区域出现故障，应用程序将不可用。

**产品版本**
+ PeopleSoft 运行 PeopleTools 8.52 及更高版本的应用程序

## 架构
<a name="set-up-a-highly-available-peoplesoft-architecture-on-aws-architecture"></a>

**目标架构**

 PeopleSoft 生产应用程序的停机或中断会影响应用程序的可用性，并对您的业务造成重大中断。

我们建议您在设计 PeopleSoft 生产应用程序时使其始终保持高可用性。您可通过消除单点故障、添加可靠的交叉点或失效转移点以及检测故障来实现这一点。下图说明了 AWS PeopleSoft 上的 HA 架构。

![\[适用于 AWS 的高可用架构 PeopleSoft\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/0db96376-dadb-4545-b130-ebbe64acd4e9/images/5d585a8e-320a-495d-a049-97171633e90f.png)


此架构部署使用适用于 Oracle 的 Amazon RDS 作为 PeopleSoft 数据库，使用在红帽企业 Linux (RHEL) 上运行的 EC2 实例。您还可以使用 Amazon RDS for SQL Server 作为 Peoplesoft 数据库。

该架构包含以下组件： 
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 用作域名服务器 (DNS)，用于将来自互联网的请求路由到 PeopleSoft 应用程序。
+ [AWS WS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html) 帮助您防范可能影响可用性、损害安全性或消耗过多资源的常见 Web 漏洞和机器人。[AWS Shield Advanced](https://docs.aws.amazon.com/waf/latest/developerguide/shield-chapter.html)（未图示）提供更广泛的保护。
+ [应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html)通过针对 Web 服务器的高级请求路由对 HTTP 和 HTTPS 流量进行负载平衡。
+ 支持应用程序的 Web 服务器、应用程序服务器、流程调度器服务器和 Elasticsearch 服务器在多个可用区中运行并使用 [Amazon EC2 A](https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html) uto Scaling。 PeopleSoft 
+  PeopleSoft 应用程序使用的数据库以多可用区配置在 [Amazon RDS](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html) 上运行。
+  PeopleSoft 应用程序使用的文件共享在 [Amazon EFS](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html) 上配置，用于跨实例访问文件。
+ [Amazon EC2 Auto Scaling 使用亚马逊系统映像 (AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html)) 来确保在需要时快速克隆 PeopleSoft 组件。
+ [NAT 网关](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)将私有子网中的实例连接到 VPC 外部的服务，并确保外部服务无法启动与这些实例的连接。
+ [互联网网关](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)是一种横向扩展、冗余且高度可用的 VPC 组件，支持在 VPC 和互联网之间进行通信。
+ 公有子网中的堡垒主机提供从外部网络（例如互联网或本地网络）访问私有子网中的服务器的权限。堡垒主机提供对私有子网中服务器的受控且安全的访问。

**架构详情**

该 PeopleSoft 数据库位于采用多可用区配置的 Amazon RDS for Oracle（或适用于 SQL Server 的 Amazon RDS）数据库中。[Amazon RDS Multi-AZ 功能](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZ.html)可跨两个可用区复制数据库更新，以提高持久性和可用性。Amazon RDS 会自动失效转移到备用数据库，以进行计划内维护和计划外中断。

 PeopleSoft Web 层和中间层安装在 EC2 实例上。这些实例分布在多个可用区中，并由[自动扩缩组](https://docs.aws.amazon.com/autoscaling/ec2/userguide/what-is-amazon-ec2-auto-scaling.html)绑定。这确保了这些组件始终具有高可用性。维护最低数量的所需实例，以确保应用程序始终可用并且可以在需要时进行扩展。

我们建议您对 OEM EC2 实例使用当前一代 EC2 实例类型。当前一代的实例类型，例如在 [AWS Nitro 系统上构建的实](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#ec2-nitro-instances)例，支持硬件虚拟机 (HVMs)。HVM AMIs 需要利用[增强的联网功能](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/enhanced-networking.html)，而且它们还能提供更高的安全性。属于每个自动扩缩组的 EC2 实例在替换或者扩展实例时使用自己的 AMI。我们建议您根据您希望应用程序处理的负载以及 Oracle 为您的 PeopleSoft PeopleSoft 应用程序和 PeopleTools 版本推荐的最低值来选择 EC2 实例类型。有关硬件和软件要求的更多信息，请参见 [Oracle 支持网站](https://support.oracle.com)。

 PeopleSoft Web 层和中间层共享 Amazon EFS 挂载以共享报告、数据文件和（如果需要）`PS_HOME`目录。出于性能和成本考虑，Amazon EFS 在每个可用区配置挂载目标。

Application Load Balancer 的配置是为了支持访问 PeopleSoft 应用程序的流量，并对不同可用区之间的 Web 服务器之间的流量进行负载平衡。应用程序负载均衡器是在至少两个可用区内提供 HA 的网络设备。Web 服务器使用负载平衡配置将流量分发到不同的应用程序服务器。Web 服务器和应用程序服务器间的负载平衡可确保负载在实例间均匀分布，并有助于避免因实例过载而导致瓶颈和服务中断。

Amazon Route 53 提供 DNS 服务，用于将流量从互联网路由到应用程序负载均衡器。Route 53 是一种可用性高、可扩展性强的 DNS Web 服务。

**HA 详情**
+ 数据库：Amazon RDS 的多可用区功能通过同步复制在多个可用区中运行两个数据库。这将创建一个具有自动失效转移功能的高可用性环境。Amazon RDS 具有失效转移事件检测功能，这些事件发生时启动自动失效转移。您也可通过 Amazon RDS API 启动手动失效转移。有关详细说明，请参见博客文章 [Amazon RDS 幕后：多可用区](https://aws.amazon.com/blogs/database/amazon-rds-under-the-hood-multi-az/)。失效转移是无缝的，并且应用程序会在发生故障时自动重新连接到数据库。但是，失效转移期间的任何进程调度程序作业都会生成错误，并且必须重新提交。
+ PeopleSoft 应用程序服务器：应用程序服务器分布在多个可用区中，并为其定义了一个 Auto Scaling 组。如果实例发生故障，自动扩缩组会立即将其替换为从应用程序服务器模板的 AMI 克隆的正常实例。具体而言，*Jolt pooling* 已启用，​当应用程序服务器实例出现故障时，会话会自动失效转移到另一个应用程序服务器，并且自动扩缩组会自动启动另一个实例、启动应用程序服务器并将其注册到 Amazon EFS 挂载中。使用 Web 服务器中的 `PSSTRSETUP.SH` 脚本，将新创建的应用程序服务器自动添加到 Web 服务器中。这可确保应用程序服务器始终处于高可用性并能快速从故障中恢复。
+ 流程调度器：流程调度器服务器分布在多个可用区，并为其定义自动扩缩组。如果实例发生故障，自动扩缩组会立即将其替换为从进程调度程序服务器模板的 AMI 克隆的运行状况良好的实例。具体来说，当进程调度程序实例出现故障时，自动扩缩组会自动启动另一个实例并启动进程调度程序。实例失败时正在运行的任何作业都必须重新提交。这确保了进程调度程序始终具有高可用性并能够快速从故障中恢复。
+ Elasticsearch 服务器：Elasticsearch 服务器具有为其定义的自动扩缩组。如果实例发生故障，自动扩缩组会立即将其替换为从 Elasticsearch 服务器模板的 AMI 克隆的运行状况良好的实例。具体来说，当 Elasticsearch 实例出现故障时，向其提供请求的应用程序负载均衡器会检测到故障并停止向其发送流量。自动扩缩组会自动启动另一个实例且启动 Elasticsearch 实例。当 Elasticsearch 实例备份时，应用程序负载均衡器检测到它运行状况良好并开始再次向其发送请求。这可确保 Elasticsearch 服务器始终保持高可用性并快速从故障中恢复。
+ Web 服务器：Web 服务器具有为其定义的自动扩缩组。如果实例发生故障，自动扩缩组会立即将其替换为从 Web 服务器模板的 AMI 克隆的正常实例。具体来说，当 Web 服务器实例出现故障时，向其提供请求的应用程序负载均衡器会检测到故障并停止向其发送流量。自动扩缩组会自动启动另一个实例并启动 Web 服务器实例。备份 Web 服务器实例时，应用程序负载均衡器检测到其运行状况良好，并再次开始向其发送请求。这可确保 Web 服务器始终保持高可用性并快速从故障中恢复。

## 工具
<a name="set-up-a-highly-available-peoplesoft-architecture-on-aws-tools"></a>

**Amazon Web Services**
+ [应用程序负载均衡器](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/)在多个可用区中的多个目标 (例如 EC2 实例) 间分配应用程序的传入流量。
+ [Amazon Elastic Block Store (Amazon EBS)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html) 提供了块级存储卷，以与 Amazon Elastic Compute Cloud (Amazon EC2) 实例一起使用。
+ [Amazon Elastic Compute Cloud (Amazon EC2)](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/concepts.html) 在 Amazon Web Services Cloud 中提供可扩展的计算能力。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [Amazon Elastic File System (Amazon EFS)](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html) 可帮助您在 Amazon Web Services Cloud 中创建和配置共享文件系统。
+ [Amazon Relational Database Service (Amazon RDS)](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html) 可帮助您在 Amazon Web Services Cloud 中设置、操作和扩展关系数据库。
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一种可用性高、可扩展性强的 DNS Web 服务。

## 最佳实践
<a name="set-up-a-highly-available-peoplesoft-architecture-on-aws-best-practices"></a>

**运营最佳实践**
+  PeopleSoft 在 AWS 上运行时，使用 Route 53 路由来自互联网和本地的流量。如果主数据库实例不可用，则使用[失效转移选项](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-configuring.html) 将流量重新路由到灾难恢复 (DR) 站点。
+ 始终在 PeopleSoft 环境前使用 Application Load Balancer。这样可确保以安全的方式将流量负载均衡到 Web 服务器。
+ 在应用程序负载均衡器目标组设置中，确保使用负载均衡器生成的 Cookie [开启粘性](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html)。
**注意**  
如果您使用外部单点登录（SSO），则可能需要使用基于应用程序的 Cookie。这样可确保 Web 服务器和应用程序服务器之间的连接保持一致。
+ 对于 PeopleSoft 生产应用程序，Application Load Balancer 空闲超时必须与您使用的网络配置文件中设置的值相匹配。这样可防止用户会话在负载均衡器层过期。
+ 对于 PeopleSoft 生产应用程序，请将应用程序服务器的[回收次数](https://docs.oracle.com/cd/F28299_01/pt857pbr3/eng/pt/tsvt/concept_PSAPPSRVOptions-c07f06.html?pli=ul_d96e90_tsvt)设置为可最大限度地减少内存泄漏的值。
+ 如果您将 Amazon RDS 数据库用于 PeopleSoft 生产应用程序（如本模式所述），请以[多可用区格式运行该数据库以实现高可用性](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Concepts.MultiAZ.html)。
+ 如果您的数据库在 PeopleSoft 生产应用程序的 EC2 实例上运行，请确保[备用数据库在另一个可用区上运行](https://docs.aws.amazon.com/prescriptive-guidance/latest/migration-oracle-database/ec2-oracle.html#ec2-oracle-ha)以实现高可用性。
+ 对于灾难恢复，请确保您的 Amazon RDS 数据库或 EC2 实例在与生产数据库不同的 AWS 区域中配置了备用数据库。这样可以确保在该地区发生灾难时，您可将应用程序割接到另一个区域。
+ 对于灾难恢复，请使用 [Amazon Elastic Disaster Recovery](https://aws.amazon.com/disaster-recovery/)在与生产组件不同的区域中设置应用程序级组件。这样可以确保在该地区发生灾难时，您可将应用程序割接到另一个区域。
+ 使用 Amazon EFS（适用于中等 I/O 要求）或 [Amazon FSx](https://aws.amazon.com/fsx/)（适用于高 I/O 要求）来存储您的 PeopleSoft 报告、附件和数据文件。这样可以确保内容存储在一个中心位置，并且可从基础设施中的任何地方进行访问。
+ 使用 [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)（基本和详细）近乎实时地监控您的 PeopleSoft 应用程序正在使用的 AWS 云资源。这样可确保您立即收到问题警报，并在问题影响环境可用性之前快速解决问题。
+ 如果您使用 Amazon RDS 数据库作为 PeopleSoft 数据库，请使用[增强监控](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_Monitoring.OS.overview.html)。此功能提供对 50 多个指标的访问，包括 CPU、内存、文件系统I/O, and disk I/O。
+ 使用 [AWS CloudTrail](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html) 监控您的 PeopleSoft 应用程序正在使用的 AWS 资源上的 API 调用。这可以帮助您执行安全分析、资源更改跟踪和合规性审核。

**安全最佳实践**
+ [要保护您的 PeopleSoft 应用程序免受 SQL 注入或跨站脚本 (XSS) 等常见漏洞攻击，请使用 AWS WAF。](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html)考虑使用 [AWS Shield Advanced](https://docs.aws.amazon.com/waf/latest/developerguide/shield-chapter.html) 提供量身定制的检测和缓解服务。
+ 向 Application Load Balancer 添加一条规则，自动将流量从 HTTP 重定向到 HTTPS，从而帮助保护您的 PeopleSoft 应用程序。
+ 为应用程序负载均衡器设置单独安全组。此安全组应仅允许 HTTPS/HTTP 入站流量，不允许出站流量。这样可确保仅允许预期流量，并有助于保护您的应用程序。
+ 对应用程序服务器、Web 服务器和数据库使用私有子网，对出站 Internet 流量使用 [NAT 网关](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)。这样可确保无法公开访问支持该应用程序的服务器，同时仅向需要该应用程序的服务器提供公共访问权限。
+ 使用不同的 VPCs 方法来运行 PeopleSoft 生产和非生产环境。使用 [AWS Transit Gateway](https://aws.amazon.com/transit-gateway/) ACLs、[VPC 对等互连](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html)、[网络](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html)和[安全组](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html)来控制 [VPC](https://aws.amazon.com/vpc/) 与您的本地数据中心之间的流量（如有必要）。
+ 遵循最低权限原则。仅向绝对需要的用户授予访问 PeopleSoft 应用程序所使用的 AWS 资源的权限。仅授予执行任务所需最低权限。有关更多信息，请参阅 AWS Well-Architected Framework 的[安全支柱](https://docs.aws.amazon.com/wellarchitected/latest/security-pillar/sec_permissions_least_privileges.html)。
+ 尽可能使用 [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 访问 PeopleSoft 应用程序使用的 EC2 实例。

**可靠性最佳实践**
+ 使用应用程序负载均衡器时，请为每个所启用的可用区注册一个目标。这使得负载均衡器最有效。
+ 我们建议您 URLs 为每个 PeopleSoft 生产环境设置三个不同的网址：一个用于访问应用程序的 URL，一个用于提供集成代理的 URL，以及一个用于查看报告的 URL。如果可能，每个 URL 都应有自己的专用 Web 服务器和Application Server。这种设计有助于提高 PeopleSoft 应用程序的安全性，因为每个 URL 都具有不同的功能和受控的访问权限。它还可最大限度地减少底层服务失败时的影响范围。
+ 我们建议您在 PeopleSoft 应用程序的[负载均衡器目标组上配置运行状况检查](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html)。运行状况检查应在 Web 服务器上执行，而不是在运行这些服务器的 EC2 实例上执行。这确保了如果 Web 服务器崩溃或托管 Web 服务器的 EC2 实例出现故障，应用程序负载均衡器能够准确反映该信息。
+ 对于 PeopleSoft 生产应用程序，我们建议您将 Web 服务器分布在至少三个可用区中。这样可以确保即使其中一个可用区出现故障， PeopleSoft 应用程序也始终保持高可用性。
+ 对于 PeopleSoft 生产应用程序，启用 jolt pooling ()。`joltPooling=true`这样可以确保在服务器因修补目的或虚拟机故障而停机时，您的应用程序可以失效转移到另一台应用程序服务器。
+ 对于 PeopleSoft 生产应用程序，`DynamicConfigReload `请设置为 1。8.52 及更高 PeopleTools 版本支持此设置。它可以动态地向 Web 服务器添加新的应用程序服务器，而无需重新启动服务器。
+ 要最大限度地减少应用 PeopleTools 补丁时的停机时间，请使用 blue/green 部署方法为 Web 和应用程序服务器的 Auto Scaling 组启动配置。有关更多信息，请参见 [AWS 部署选项概述](https://docs.aws.amazon.com/whitepapers/latest/overview-deployment-options/bluegreen-deployments.html)白皮书。
+ 使用 [AWS Backup 在 AWS 上备份](https://docs.aws.amazon.com/aws-backup/latest/devguide/whatisbackup.html)您的 PeopleSoft 应用程序。AWS Backup 是一项经济实惠、完全托管、基于策略服务，可大规模简化数据保护。

**性能最佳实践**
+ 在 Application Load Balancer 上终止 SSL 以获得最佳 PeopleSoft 环境性能，除非您的业务需要整个环境中的加密流量。
+ 为[亚马逊简单通知服务 (Amazon SNS) Simple N [CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)otification Service 等 AWS 服务](https://docs.aws.amazon.com/sns/latest/dg/welcome.html)创建[接口 VPC 终端节点](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html)，以便流量始终位于内部。这有成本效益，有助于保护您的应用程序安全。

**成本优化最佳实践标准**
+ 标记您的 PeopleSoft 环境使用的所有资源，并启用[成本分配标签](https://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/cost-alloc-tags.html)。这些标签可帮您查看和管理资源成本。
+ 对于 PeopleSoft 生产应用程序，请为 Web 服务器和应用程序服务器设置 Auto Scaling 组。这样可以维护最少数量的 Web 和应用程序服务器来支持您的应用程序。您可使用自动扩缩组[策略](https://docs.aws.amazon.com/autoscaling/ec2/userguide/as-scaling-simple-step.html)根据需要向上和向下扩展服务器。
+ 使用[账单警报](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/monitor_estimated_charges_with_cloudwatch.html)，在费用超过您指定的预算阈值时收到提醒。

**可持续发展最佳实践标准**
+ 使用[基础设施即代码](https://docs.aws.amazon.com/whitepapers/latest/introduction-devops-aws/infrastructure-as-code.html) (IaC) 来维护您的 PeopleSoft 环境。这可以帮您构建一致的环境并保持变更控制。

## 操作说明
<a name="set-up-a-highly-available-peoplesoft-architecture-on-aws-epics"></a>

### 将您的 PeopleSoft 数据库迁移到 Amazon RDS
<a name="migrate-your-peoplesoft-database-to-amazon-rds"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建数据库子网组。 | 在 [Amazon RDS 控制台](https://console.aws.amazon.com/rds/) 导航窗格，选择**子网组**，然后创建子网位于多个可用区域的 Amazon RDS 数据库子网组。Amazon RDS 数据库需要这样做，才能使 Amazon RDS 数据库在多可用区配置中运行。 | 云管理员 | 
| 创建 Amazon RDS 数据库。 | 在您为 PeopleSoft HA 环境选择的 AWS 区域的可用区中创建 Amazon RDS 数据库。创建 Amazon RDS 数据库时，请务必选择多可用区选项（**创建备用实例**）和您在上一步中创建的数据库子网组。有关更多信息，请参阅 [Amazon RDS 文档](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CreateDBInstance.html)。 | 云管理员、Oracle Database 管理员 | 
| 将您的 PeopleSoft 数据库迁移到 Amazon RDS。 | 使用 AWS PeopleSoft 数据库迁移服务 (AWS DMS) 将您的现有数据库迁移到 Amazon RDS 数据库。有关更多信息，请参阅 [AWS DMS 文档](https://docs.aws.amazon.com/dms/latest/userguide/CHAP_Source.Oracle.html)和 AWS Blog 文章[使用 AWS DMS 以近乎零停机时间迁移 Oracle 数据库](https://aws.amazon.com/blogs/database/migrating-oracle-databases-with-near-zero-downtime-using-aws-dms/)。 | 云管理员、数据库 PeopleSoft 管理员 | 

### 设置您的 Amazon EFS 文件系统
<a name="set-up-your-amazon-efs-file-system"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建文件系统。 | 在 [Amazon EFS 控制台](https://console.aws.amazon.com/efs/)，为每个可用区创建文件系统并挂载目标。有关说明，请参阅 [Amazon EFS 文档](https://docs.aws.amazon.com/efs/latest/ug/creating-using-create-fs.html#creating-using-fs-part1-console)。创建文件系统后，请记下 DNS 名称。您在挂载文件系统时使用此信息。 | 云管理员 | 

### 设置您的 PeopleSoft 应用程序和文件系统
<a name="set-up-your-peoplesoft-application-and-file-system"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动一个 EC2 实例。 | 为您的 PeopleSoft 应用程序启动 EC2 实例。有关说明，请参阅 [Amazon EC2 文档](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-launch-instance-wizard.html#liw-quickly-launch-instance)。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-highly-available-peoplesoft-architecture-on-aws.html) | 云管理员、 PeopleSoft 管理员 | 
| 在实例 PeopleSoft 上安装。 | 在您创建的 EC2 实例 PeopleTools 上安装您的 PeopleSoft 应用程序和。有关说明，请参阅 [Oracle 文档](https://docs.oracle.com)。 | 云管理员、 PeopleSoft 管理员 | 
| 创建应用程序服务器。 | 为 AMI 模板创建 Application Server，并确保其成功连接到 Amazon RDS 数据库。 | 云管理员、 PeopleSoft 管理员 | 
| 挂载 Amazon EFS 文件系统。 | 以根用户身份登录 EC2 实例，然后运行以下命令将 Amazon EFS 文件系统挂载到服务器上名为 `PSFTMNT` 的文件夹中。<pre>sudo su –<br />mkdir /psftmnt<br />cat /etc/fstab</pre>将以下行附加到 `/etc/fstab` 文件中。使用您在创建文件系统时记录的 DNS 名称。<pre>fs-09e064308f1145388.efs.us-east-1.amazonaws.com:/ /psftmnt nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev 0 0<br />mount -a</pre> | 云管理员、 PeopleSoft 管理员 | 
| 检查权限。 | 确保该`PSFTMNT`文件夹具有适当的权限，以便 PeopleSoft 用户可以正确访问该文件夹。 | 云管理员、 PeopleSoft 管理员 | 
| 创建额外实例。 | 重复本操作说明中的前几个步骤，为流程调度器、Web 服务器和 Elasticsearch 服务器创建模板实例。将这些实例命名为 `PRCS_TEMPLATE`、`WEB_TEMPLATE` 和 `SRCH_TEMPLATE`。对于 Web 服务器，设置 `joltPooling=true`** **和 `DynamicConfigReload=1`。 | 云管理员、 PeopleSoft 管理员 | 

### 创建脚本以设置服务器
<a name="create-scripts-to-set-up-servers"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建用于安装应用服务器的脚本。 | 在 Amazon EC2 `APP_TEMPLATE` 实例中，以 PeopleSoft 用户身份创建以下脚本。给它命名为 `appstart.sh`，并将其放在 `PS_HOME` 目录中。您将使用此脚本启动应用程序服务器，并在 Amazon EFS 挂载上记录服务器名称。<pre>#!/bin/ksh<br />. /usr/homes/hcmdemo/.profile.<br />psadmin -c configure -d HCMDEMO<br />psadmin -c parallelboot -d HCMDEMO<br />touch /psftmnt/`echo $HOSTNAME`</pre> | PeopleSoft 管理员 | 
| 创建用于安装流程调度服务器的脚本。 | 在 Amazon EC2 `PRCS_TEMPLATE` 实例中，以 PeopleSoft 用户身份创建以下脚本。给它命名为 `prcsstart.sh`，并将其放在 `PS_HOME` 目录中。您将使用此脚本启动进程调度器服务器。<pre>#!/bin/ksh<br />. /usr/homes/hcmdemo/. profile<br />/* The following line ensures that the process scheduler always has a unique name during replacement or scaling activity. */ <br />sed -i "s/.*PrcsServerName.*/`hostname -I | awk -F. '{print "PrcsServerName=PSUNX"$3$4}'`/" $HOME/appserv/prcs/*/psprcs.cfg<br />psadmin -p configure -d HCMDEMO<br />psadmin -p start -d HCMDEMO</pre> | PeopleSoft 管理员 | 
| 创建用于安装 Elasticsearch 服务器的脚本。 | 在 Amazon EC2 `SRCH_TEMPLATE` 实例，以 Elasticsearch 用户的身份创建以下脚本。给它命名为 `srchstart.sh`，并将其放在 `HOME` 目录中。<pre>#!/bin/ksh<br />/* The following line ensures that the correct IP is indicated in the elasticsearch.yaml file. */<br />sed -i "s/.*network.host.*/`hostname  -I | awk '{print "host:"$0}'`/" $ES_HOME_DIR/config/elasticsearch.yaml<br />nohup $ES_HOME_DIR/bin/elasticsearch &</pre> | PeopleSoft 管理员 | 
| 创建安装 Web 服务器脚本。 | 在 Amazon EC2 `WEB_TEMPLATE` 实例，以 Web 服务器用户的身份在 `HOME` 目录中创建以下脚本。`renip.sh`：此脚本可确保 Web 服务器在从 AMI 克隆时有正确的 IP。<pre>#!/bin/ksh<br />hn=`hostname`<br />/* On the following line, change the IP with the hostname with the hostname of the web template. */<br />for text_file in `find  *  -type f -exec grep -l '<hostname-of-the-web-template>' {} \;`<br />do<br />sed -e 's/<hostname-of-the-web-template>/'$hn'/g' $text_file > temp<br />mv -f temp $text_file<br />done</pre>`psstrsetup.sh`：此脚本可确保 Web 服务器使用当前正在运行 IPs 的正确应用程序服务器。它尝试通过 jolt 端口连接到每台应用程序服务器，并将其添加到配置文件中。<pre>#!/bin/ksh<br />c2=""<br />for ctr in `ls -1 /psftmnt/*.internal`<br />do<br />c1=`echo $ctr | awk -F "/" '{print $3}'`<br />/* In the following lines, 9000 is the jolt port. Change it if necessary. */<br />if nc -z $c1 9000 2> /dev/null; then<br />if [[ $c2 = "" ]]; then<br />c2="psserver="`echo $c1`":9000"<br />else<br />c2=`echo $c2`","`echo $c1`":9000"<br />fi<br />fi<br />done</pre>`webstart.sh`：此脚本运行前两个脚本并、和启动 Web 服务器。<pre>#!/bin/ksh<br />/* Change the path in the following if necessary. */<br />cd  /usr/homes/hcmdemo <br />./renip.sh<br />./psstrsetup.sh<br />webserv/peoplesoft/bin/startPIA.sh</pre> | PeopleSoft 管理员 | 
| 添加 crontab 条目。 | 在 Amazon EC2 `WEB_TEMPLATE`实例中，以网络服务器用户的身份将以下行添加至 **crontab**。更改时间和路径以反映所需值。此条目可确保 Web 服务器 `configuration.properties` 文件中始终包含正确的应用程序服务器条目。<pre>* * * * * /usr/homes/hcmdemo/psstrsetup.sh</pre> | PeopleSoft 管理员 | 

### 创建 AMIs 和 Auto Scaling 组模板
<a name="create-amis-and-auto-scaling-group-templates"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为应用服务器模板创建 AMI。 | 在 Amazon EC2 控制台，创建 Amazon EC2 `APP_TEMPLATE` 实例的 AMI 映像。命名 AMI `PSAPPSRV-SCG-VER1`。有关说明，请参阅 [Amazon EC2 文档](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html)。 | 云管理员、 PeopleSoft 管理员 | 
|  AMIs 为其他服务器创建。 | 重复上一步 AMIs 为流程调度器、Elasticsearch 服务器和 Web 服务器创建。 | 云管理员、 PeopleSoft 管理员 | 
| 为应用程序服务器自动扩缩组创建启动模板。 | 为应用程序服务器自动扩缩组创建启动模板。将模板命名为 `PSAPPSRV_TEMPLATE.` 在模板中，选择您为 `APP_TEMPLATE` 实例创建的 AMI。有关说明，请参阅 [Amazon EC2 文档](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/create-launch-template.html#create-launch-template-from-instance)。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-highly-available-peoplesoft-architecture-on-aws.html) | 云管理员、 PeopleSoft 管理员 | 
| 为流程调度程序服务器自动扩缩组创建启动模板。 | 重复上一步的操作，为流程调度器服务器自动扩缩组创建启动模板。将模板命名为 `PSPRCS_TEMPLATE`。在模板中，选择您为流程调度器所创建的 AMI。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-highly-available-peoplesoft-architecture-on-aws.html) | 云管理员、 PeopleSoft 管理员 | 
| 为 Elasticsearch 服务器自动扩缩组创建启动模板。 | 重复上述步骤，为 Elasticsearch 服务器自动扩缩组创建启动模板。将模板命名为 `SRCH_TEMPLATE`。在模板中，选择您为搜索服务器所创建的 AMI。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-highly-available-peoplesoft-architecture-on-aws.html) | 云管理员、 PeopleSoft 管理员 | 
| 为 Web 服务器自动扩缩组创建启动模板。 | 重复上述步骤，为 Web 服务器自动扩缩组创建启动模板。将模板命名为 `WEB_TEMPLATE`。在模板中，选择您为 Web 服务器所创建的 AMI。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-highly-available-peoplesoft-architecture-on-aws.html) | 云管理员、 PeopleSoft 管理员 | 

### 创建自动扩缩组
<a name="create-auto-scaling-groups"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为应用程序服务器创建自动扩缩组。 | 在 Amazon EC2 控制台，使用 `PSAPPSRV_TEMPLATE` 模板创建一个名 `PSAPPSRV_ASG` 为的应用程序服务器创建自动扩缩组。有关说明，请参阅 [Amazon EC2 文档](https://docs.aws.amazon.com/autoscaling/ec2/userguide/create-asg-launch-template.html)。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-highly-available-peoplesoft-architecture-on-aws.html) | 云管理员、 PeopleSoft 管理员 | 
| 为其他服务器创建自动扩缩组。 | 重复上述步骤，为进程计划程序、Elasticsearch 服务器和 Web 服务器创建自动扩缩组。 | 云管理员、 PeopleSoft 管理员 | 

### 创建和配置目标组
<a name="create-and-configure-target-groups"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 Web 服务器创建目标组。 | 在 Amazon EC2 控制台，为 Web 服务器创建目标组。有关说明，请参阅[弹性负载均衡文档](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-target-group.html)。将端口设置为 Web 服务器侦听端口。 | 云管理员 | 
| 配置运行状况检查。 | 确认运行状况检查值是否正确，以反映您的业务需求。有关更多信息，请参阅[弹性负载均衡文档](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/target-group-health-checks.html)。 | 云管理员 | 
| 为 Elasticsearch 服务器创建目标组。 | 重复前面的步骤，为 Elasticsearch 服务器创建一个名为 `PSFTSRCH` 的目标组，并设置正确的 Elasticsearch 端口。 | 云管理员 | 
| 将目标组添加到自动扩缩组。 | 打开您之前创建的名为 `PSPIA_ASG` 的 Web 服务器自动扩缩组。在**负载平衡**选项卡，选择**编辑**，然后将 `PSFTWEB` 目标组添加至自动扩缩组。对 Elasticsearch 自动扩缩组 `PSSRCH_ASG` 重复此步骤，添加您之前创建的目标组 `PSFTSRCH`。 | 云管理员 | 
| 设置会话粘性。 | 在目标组 `PSFTWEB`，选择**属性**选项卡，选择**编辑**，设置会话粘性。对于粘性类型，选择**负载均衡器生成 cookie**，并将持续时间设置为 1。有关更多信息，请参阅[弹性负载均衡文档](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/sticky-sessions.html)。为目标组 `PSFTSRCH` 重复此步骤。 | 云管理员 | 

### 创建并配置应用程序负载均衡器。
<a name="create-and-configure-application-load-balancers"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为 Web 服务器创建负载均衡器。 | 创建名为 `PSFTLB` 的应用程序负载均衡器，以对流向 Web 服务器的流量进行负载平衡。有关说明，请参阅[弹性负载均衡文档](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-application-load-balancer.html#configure-load-balancer)。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-highly-available-peoplesoft-architecture-on-aws.html) | 云管理员 | 
| 为 Elasticsearch 服务器创建负载均衡器。 | 创建名为 `PSFTSCH` 的应用程序负载均衡器，以对流向 Elasticsearch 服务器的流量进行负载平衡。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-a-highly-available-peoplesoft-architecture-on-aws.html) | 云管理员 | 
| 配置 Route 53。 | 在 [Amazon Route 53 控制台](https://console.aws.amazon.com/route53/)上，在将为 PeopleSoft 应用程序提供服务的托管区域中创建一条记录。有关说明，请参阅 [Amazon Route 53 文档](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html)。这样可以确保所有流量都通过 `PSFTLB` 负载均衡器。 | 云管理员 | 

## 相关资源
<a name="set-up-a-highly-available-peoplesoft-architecture-on-aws-resources"></a>
+ [甲骨文 PeopleSoft 网站](https://www.oracle.com/applications/peoplesoft/)
+ [AWS 文档](https://docs.aws.amazon.com/)

# 使用 AWS 弹性灾难恢复为 Oracle JD Edwar EnterpriseOne ds 设置灾难恢复
<a name="set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery"></a>

*Thanigaivel Thirumalai，Amazon Web Services*

## Summary
<a name="set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery-summary"></a>

由自然灾害、应用程序故障或服务中断引发的灾难会损害收入，导致企业应用程序停机。为了减少此类事件的影响，灾难恢复（DR）计划对于采用JD Edwards EnterpriseOne 企业资源规划（ERP）系统和其他关键任务和业务关键型软件的公司至关重要。 

这种模式解释了企业如何使用 AWS Elastic 灾难恢复作为其 JD Edwards EnterpriseOne 应用程序的灾难恢复选项。 它还概述了使用弹性灾难恢复故障转移和故障恢复为托管在 AWS 云中的亚马逊弹性计算云 (Amazon EC2) 实例上的数据库构建跨区域灾难恢复策略的步骤。

**注意**  
这种模式要求跨区域灾难恢复实施的主要和次要区域托管在 AWS 上。

[Oracle JD Edwards EnterpriseOne](https://www.oracle.com/applications/jd-edwards-enterpriseone/) 是一款集成式 ERP 软件解决方案，适用于各行各业的大中型公司。

AWS Elastic Daser Recovery 使用经济实惠的存储、最少的计算和恢复，通过快速、可靠地 point-in-time恢复本地和基于云的应用程序，最大限度地减少停机时间和数据丢失。

AWS 提供了[四种核心灾难恢复架构模式](https://docs.aws.amazon.com/whitepapers/latest/disaster-recovery-workloads-on-aws/disaster-recovery-options-in-the-cloud.html)。本文档重点介绍如何使用 [pilot light 策略](https://docs.aws.amazon.com/whitepapers/latest/disaster-recovery-workloads-on-aws/disaster-recovery-options-in-the-cloud.html)进行设置、配置和优化。此策略可帮助您创建低成本灾难恢复环境，在该环境中，您可以先配置复制服务器，以从源数据库复制数据，而只有在开始灾难恢复演练和恢复时才配置实际的数据库服务器。此策略省去了灾难恢复区域维护数据库服务器的成本。相反，您需要为用作复制服务器的小型 EC2 实例支付成本。

## 先决条件和限制
<a name="set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 在 Oracle 数据库或 Microsoft SQL Server 上运行的 JD Edwards EnterpriseOne 应用程序，受支持的数据库在托管 EC2 实例上处于运行状态。此应用程序应包括安装在一个 AWS 区域中的所有 JD Edwards EnterpriseOne 基础组件（企业服务器、HTML 服务器和数据库服务器）。
+ 用于设置弹性灾难恢复服务的 AWS Identity and Access Management (IAM) 角色。
+ 根据所需[连接设置](https://docs.aws.amazon.com/drs/latest/userguide/Network-Requirements.html)配置用于运行 Elastic Disaster Recovery 的网络。

**限制**
+ 您可以使用此模式复制所有层，除非数据库托管在 Amazon Relational Database Service (Amazon RDS) 上，在这种情况下，我们建议您使用 Amazon RDS 的[跨区域复制功能](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/USER_CopySnapshot.html)。
+ Elastic 灾难恢复与 CloudEndure 灾难恢复不兼容，但您可以从 CloudEndure 灾难恢复中升级。有关更多信息，请参阅 Elastic Disaster Recovery 文档中的[常见问题](https://docs.aws.amazon.com/drs/latest/userguide/cedr-to-drs.html)。
+ Amazon Elastic Block Store (Amazon EBS) 限制您的快照拍摄速率。使用 Elastic Disaster Recovery，您可在单个 Amazon Web Services account 中最多复制 300 台服务器。若要复制更多服务器，您可以使用多个 Amazon Web Services account 或多个目标 AWS 区域。（您必须为每个账户和地区分别设置 Elastic Disaster Recovery。） 有关更多信息，请参阅 Elastic Disaster Recovery 文档中的[最佳实践](https://docs.aws.amazon.com/drs/latest/userguide/best_practices_drs.html)。
+ 源工作负载（JD Edwards EnterpriseOne 应用程序和数据库）必须托管在 EC2 实例上。这种模式不支持本地或其他云环境的工作负载。
+ 这种模式侧重于 JD Edwards 的 EnterpriseOne 组件。完整的灾难恢复和业务连续性计划 (BCP) 应包含其他核心服务，包括：
  + 网络（虚拟私有云、子网和安全组）
  + Active Directory
  + Amazon WorkSpaces
  + Elastic Load Balancing
  + 托管式数据库服务，比如 Amazon Relational Database Service（Amazon RDS）

有关先决条件、配置和限制的更多信息，请参阅 [Elastic Disaster Recovery 文档](https://docs.aws.amazon.com/drs/latest/userguide/what-is-drs.html)。

**产品版本**
+ Oracle JD Edwards EnterpriseOne （基于甲骨文最低技术要求的 Oracle 和 SQL Server 支持的版本）

## 架构
<a name="set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery-architecture"></a>

**目标技术堆栈**
+ 单个区域和单个虚拟私有云（VPC）用于生产和非生产，第二区域用于灾难恢复
+ 单一可用区可以确保服务器之间的低延迟
+ 应用程序负载均衡器用于分配网络流量，以提高应用程序在多个可用区的可扩展性和可用性
+ Amazon Route 53，用于提供域名系统（DNS）配置
+ Amazon WorkSpaces 将为用户提供云端桌面体验
+ Amazon Simple Storage Service (Amazon S3)，用于存储备份、文件和对象
+ Amazon CloudWatch 用于应用程序日志、监控和警报
+ Amazon Elastic Disaster Recovery，用于灾难恢复

**目标架构**

下图显示了 EnterpriseOne 使用 Elastic 灾难恢复的 JD Edwards 跨区域灾难恢复架构。

![\[AWS 上的 JD Edwards EnterpriseOne 跨区域灾难恢复架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/9b0de5f0-f211-4086-a044-321d081604f9/images/978b7219-e54e-4e31-b3ff-4885784e2971.png)


**过程**

以下是对该进程的高度回顾。有关详细信息，请参阅*操作说明*部分。
+ Elastic Disaster Recovery 复制从初始同步开始。在初始同步期间，AWS Replication Agent 会将所有数据从源磁盘复制至暂存区域子网中的相应资源。
+ 初始同步完成后，连续复制将无限期继续。
+ 安装代理并开始复制后，您可查看启动参数，包括服务特定的配置和 Amazon EC2 启动模板。当源服务器被指示为准备恢复时，即可启动实例。
+ 当 Elastic Disaster Recovery 发出一系列 API 调用，以开始启动操作时，将根据您的启动设置立即在 AWS 上启动恢复实例。该服务会在启动期间自动启动转换服务器。
+ 转换完成和可供使用后，新实例将在 AWS 上启动。启动时的源服务器状态通过与已启动实例关联的卷表示。转换过程包括更改驱动程序、网络和操作系统许可证，确保实例在 AWS 上以原生方式启动。
+ 启动后，新建卷将不再与源服务器保持同步。AWS Replication Agent 会继续定期将对源服务器的更改复制到暂存区域卷，但启动的实例并未反映这些更改。
+ 启动新的演练或恢复实例时，数据始终反映在源服务器复制到暂存区域子网的最新状态中。
+ 当源服务器被标记为准备恢复时，您可启动实例。

**注意**  
该过程是双向的：从主 AWS 区域失效转移到灾难恢复区域，以及在主站点恢复后故障恢复到主站点。您可通过以完全编排的方式，将数据从目标计算机复制回源计算机的方向，反过来为失效自动恢复做好准备。

此模式中描述的此进程的好处包括：
+ 灵活性：复制服务器根据数据集和复制时间进行横向扩展和横向缩减，因此您可在不中断源工作负载或复制的情况下执行灾难恢复测试。
+ 可靠性：复制功能强大、无中断且可持续。
+ 自动化：此解决方案为测试、恢复和失效自动恢复提供了统一、自动化流程。
+ 成本优化：您只能复制所需卷并为其付费，并且只有在灾难恢复站点的计算资源被激活后，才可以为这些资源付费。您可将成本优化的复制实例（我们建议您使用计算优化型实例类型）用于多个数据源，也可以使用具有大 EBS 卷的单个源。

**自动化和扩展**

当您大规模执行灾难恢复时，JD Edwards EnterpriseOne 服务器将依赖环境中的其他服务器。例如：
+ 启动时连接到 JD Edwards EnterpriseOne 支持的数据库的 JD Edwards EnterpriseOne 应用程序服务器依赖该数据库。
+ 需要身份验证且需要在启动时连接到域控制器才能启动服务的 JD Edwards EnterpriseOne 服务器依赖于域控制器。

因此，我们建议自动执行失效转移任务。例如，您可以使用 AWS Lambda 或 AWS Step Functions 自动执行 JD Edwards EnterpriseOne 启动脚本和负载均衡器更改，以自动执行故障转移过程。 end-to-end有关更多信息，请参阅博客文章[使用 AWS Elastic Disaster Recovery 创建可扩展的灾难恢复计划](https://aws.amazon.com/blogs/storage/creating-a-scalable-disaster-recovery-plan-with-aws-elastic-disaster-recovery/)。

## 工具
<a name="set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery-tools"></a>

**Amazon Web Services**
+ [Amazon Elastic Block Store（Amazon EBS）](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AmazonEBS.html)提供了适用于 EC2 实例的块级存储卷。
+ [Amazon Elastic Compute Cloud (Amazon EC2)](https://aws.amazon.com/products/compute/) 在 Amazon Web Services Cloud 中提供可扩展的计算容量。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [AWS Elastic Disaster Re](https://aws.amazon.com/disaster-recovery/) covery 使用经济实惠的存储、最少的计算和恢复，可以快速、可靠地 point-in-time恢复本地和基于云的应用程序，从而最大限度地减少停机时间和数据丢失。
+ [借助 Amazon Virtual Private Cloud(Amazon VPC) ](https://aws.amazon.com/vpc/)，您可完全控制自己的虚拟网络环境，包括资源放置、连接和安全。

## 最佳实践
<a name="set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery-best-practices"></a>

**一般最佳实践**
+ 制定书面计划，说明在发生真正恢复事件时该怎么做。
+ 正确设置 Elastic 灾难恢复后，创建一个 AWS CloudFormation 模板，以便在需要时按需创建配置。确定服务器和应用程序的启动顺序，并将其记录至恢复计划。
+ 定期进行演练（适用标准 Amazon EC2 费率）。
+ 使用 Elastic Disaster Recovery 控制台或以编程方式监控正在进行的复制的运行状况。
+ 保护 point-in-time快照并在终止实例之前进行确认。
+ 为 AWS Replication Agent 安装创建 IAM 角色。
+ 在真实灾难恢复场景中为恢复实例启动终止保护。
+ 对于启动恢复实例的服务器，请勿在 Elastic Disaster Recovery控制台中使用**断开与 AWS 连接**操作，即使是真实的恢复事件也是如此。执行断开连接会终止与这些源服务器相关的所有复制资源，包括您的 point-in-time (PIT) 恢复点。
+ 更改 PIT 策略，以更改快照保留天数。
+ 在 Elastic Disaster Recovery 启动设置中编辑启动模板，为目标服务器设置正确的子网、安全组和实例类型。
+ 使用 Lambda 或 Step Functions 自动更改 JD Edwards EnterpriseOne 启动脚本和负载均衡器，从而自动执行 end-to-end故障转移流程。

**JD Edwards 的 EnterpriseOne 优化和注意事项**
+ 移**PrintQueue**入数据库。
+ 移**MediaObjects**入数据库。
+ 从批处理服务器和逻辑服务器中排除日志和临时文件夹。
+ 从 Oracle WebLogic 中排除临时文件夹。
+ 为失效转移后启动创建脚本。
+ 排除 SQL Server 中的 tempdb。
+ 排除 Oracle 临时文件。

## 操作说明
<a name="set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery-epics"></a>

### 执行初始任务与配置
<a name="perform-initial-tasks-and-configuration"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置复制网络。 | 在主 AWS 区域实施您的 JD Edwards EnterpriseOne 系统并确定用于灾难恢复的 AWS 区域按照 Elastic 灾难恢复文档中[复制网络要求](https://docs.aws.amazon.com/drs/latest/userguide/preparing-environments.html)部分中的步骤来规划和设置您的复制和灾难恢复网络。 | AWS 管理员 | 
| 确定 RPO 和 RTO。 | 确定应用程序服务器与数据库的恢复时间目标（RTO）和恢复点目标（RPO）。 | 云架构师、灾难恢复架构师 | 
| 为 Amazon EFS 启用复制。 | 如果适用，请使用 AWS、rs **y** nc 或其他适当的工具为共享文件系统（例如亚马逊弹性文件系统 (Amazon EFS)）启用从 AWS DataSync 主区域复制到灾难恢复区域。 | 云管理员 | 
| 在灾难恢复情况下管理 DNS | 确定进程，以在灾难回复演练或实际灾难恢复过程中更新域名系统（DNS）。 | 云管理员 | 
| 为设置创建 IAM 角色。 | 按照 Elastic Disaster Recovery 文档的 [Elastic Disaster Recovery 初始化和权限](https://docs.aws.amazon.com/drs/latest/userguide/getting-started-initializing.html)部分中的说明，创建 IAM 角色以初始化和管理 Amazon Web Services。 | 云管理员 | 
| 设置 VPC 对等连接。 | 确保源和目标之间 VPCs 是对等的，并且可以互相访问。有关配置说明，请参阅 [Amazon VPC 文档](https://docs.aws.amazon.com/vpc/latest/peering/what-is-vpc-peering.html)。 | AWS 管理员 | 

### 配置 Elastic Disaster Recovery 复制设置
<a name="configure-elastic-disaster-recovery-replication-settings"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 初始化 Elastic Disaster Recovery。 | 打开 [Elastic Disaster Recovery 控制台](https://console.aws.amazon.com/drs/home)，选择目标 AWS 区域（您将在其中复制数据并启动恢复实例），然后选择**设置默认复制**。 | AWS 管理员 | 
| 设置复制服务器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.html) | AWS 管理员 | 
| 配置卷与安全组。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.html) | AWS 管理员 | 
| 配置其他设置。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.html) | AWS 管理员 | 

### 安装 AWS Replication Agent
<a name="install-the-aws-replication-agent"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 IAM 角色。 | 创建一个包含 `AWSElasticDisasterRecoveryAgentInstallationPolicy` 策略的 IAM 角色。在**选择 AWS 访问类型**部分中，启用程序访问。记下访问密钥 ID 和秘密访问密钥。在安装 AWS Replication Agent 期间，您将需要这些信息。 | AWS 管理员 | 
| 查看要求。 | 查看并完成安装 AWS Replication Agent 的 Elastic Disaster Recovery 文档中的[先决条件](https://docs.aws.amazon.com/drs/latest/userguide/installation-requiremets.html)。 | AWS 管理员 | 
| 安装 AWS Replication Agent。 | 按照操作系统的[安装说明](https://docs.aws.amazon.com/drs/latest/userguide/agent-installation-instructions.html)操作，然后安装 AWS Replication Agent。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.html)对其余服务器重复上述步骤。 | AWS 管理员 | 
| 监控复制。 | 返回 Elastic Disaster Recovery**源服务器**窗格，以监控复制状态。初始同步将花费一定的时间，具体取决于数据传输的大小。源服务器完全同步后，服务器状态将更新为**就绪**。这意味着已在暂存区创建复制服务器，并且 EBS 卷已从源服务器复制到暂存区。 | AWS 管理员 | 

### 配置启动设置
<a name="configure-launch-settings"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 编辑启动设置。 | 若要更新演练和恢复实例的启动设置，请在 [Elastic Disaster Recovery 控制台](https://console.aws.amazon.com/drs/home)，选择源服务器，然后选择**操作**、**编辑启动设置**。或者，您可以从**源服务器**页面中选择要复制的源计算机，然后选择**启动设置**选项卡。此选项卡有两个部分：**常规启动设置**和**EC2 启动模板**。 | AWS 管理员 | 
| 配置常规启动设置。 | 根据您的要求修改常规启动设置。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.html)有关更多信息，请参阅 Elastic Disaster Recovery 文档中的[常规启动设置](https://docs.aws.amazon.com/drs/latest/userguide/launch-general-settings.html)。 | AWS 管理员 | 
| 配置 Amazon EC2 启动模板。 | Elastic Disaster Recovery 使用 Amazon EC2 启动模板为每台源服务器启动演练和恢复实例。在安装 AWS Replication Agent 之后，系统会自动为您添加至 Elastic Disaster Recovery 的每台源服务器创建启动模板。如果您将项 Amazon EC2 启动模型用于 Elastic Disaster Recovery，则必须将其设置为默认模板。有关更多信息，请参阅 Elastic Disaster Recovery 文档中的 [EC2 启动模板](https://docs.aws.amazon.com/drs/latest/userguide/ec2-launch.html)。 | AWS 管理员 | 

### 启动灾难恢复演练与失效转移
<a name="initiate-dr-drill-and-failover"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动演习 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.html)有关更多信息，请参阅 Elastic Disaster Recovery 文档中的[准备失效转移](https://docs.aws.amazon.com/drs/latest/userguide/failback-preparing.html)。 | AWS 管理员 | 
| 验证演练。 | 在上一步中，您在灾难恢复区域启动了新目标实例。目标实例是源服务器副本，具体取决于您启动启动时拍摄的快照。在此过程中，您将连接至 Amazon EC2 目标计算机，以确认它们按预期运行。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.html) |  | 
| 启动失效转移。 | 失效转移是指将流量从主系统重定向至辅助系统。Elastic Disaster Recovery通 过在 AWS 上启动恢复实例帮助您执行失效转移。启动恢复实例后，您可将流量从主系统重定向到这些实例。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.html)有关更多信息，请参阅 Elastic Disaster Recovery 文档中的[执行失效转移](https://docs.aws.amazon.com/drs/latest/userguide/failback-preparing-failover.html)。 | AWS 管理员 | 
| 启动失效自动恢复。 | 启动失效自动恢复的过程与启动失效转移的过程类似。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.html)有关更多信息，请参阅 Elastic Disaster Recovery 文档中的[执行失效自动恢复](https://docs.aws.amazon.com/drs/latest/userguide/failback-performing-main.html)。 | AWS 管理员 | 
| 启动 JD Edwards EnterpriseOne 组件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery.html)你需要在 Route 53 和 Application Load Balancer 中合并更改才能让 JD Edwards EnterpriseOne 链接起作用。您可使用 Lambda、Step Functions 和 Systems Manager（运行命令）自动执行这些步骤。Elastic Disaster Recovery 对托管操作系统和文件系统的源 EC2 实例 EBS 卷执行块级复制。使用 Amazon EFS 创建的共享文件系统不属于此复制的组成部分。您可以使用 AWS 将共享文件系统复制到灾难恢复区域 DataSync，如第一篇故事中所述，然后将这些复制的文件系统挂载到灾难恢复系统中。 | 京东爱德华兹数控系统 EnterpriseOne  | 

## 问题排查
<a name="set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 源服务器数据复制状态为**已停止**，复制延迟。如果您查看详细信息，则数据复制状态将显示**未看到代理**。 | 检查以确认停顿的源服务器是否在运行。如果源服务器出现故障，则复制服务器将自动终止。有关延迟问题的更多信息，请参阅 Elastic Disaster Recovery 文档中的[复制延迟问题](https://docs.aws.amazon.com/drs/latest/userguide/Other-Troubleshooting-Topics.html#Replication-Lag-Issues)。 | 
| 扫描磁盘后，在 RHEL 8.2 中，在源 EC2 实例中安装 AWS Replication Agent失败。`aws_replication_agent_installer.log` 显示缺少内核标头。 | 在 RHEL 8、CentOS 8 或 Oracle Linux 8 上安装 AWS Replication Agent 之前，请运行：<pre>sudo yum install elfutils-libelf-devel</pre>有关更多信息，请参阅 Elastic Disaster Recovery 文档中的 [Linux 安装要求](https://docs.aws.amazon.com/mgn/latest/ug/installation-requirements.html#linux-requirements)。 | 
| 在 Elastic Disaster Recovery 控制台，您会看到源服务器为**就绪**，但存在延迟，数据复制状态为**已停止**。视 AWS Replication Agent 不可用的时间长短而定，状态可能表示延迟时间过长，但问题仍然存在。 | 使用操作系统命令确认 AWS Replication Agent 是否在源 EC2 实例中运行，或者确认该实例正在运行。更正所有问题后，Elastic Disaster Recovery 将重新开始扫描。等到所有数据都已同步并且复制状态为**正常**，再开始灾难恢复演练。 | 
| 初始复制延迟较高。在 Elastic Disaster Recovery 控制台，您可以看到源服务器的初始同步状态非常慢。 | 查看 Elastic Disaster Recovery 文档的[复制延迟问题](https://docs.aws.amazon.com/drs/latest/userguide/Other-Troubleshooting-Topics.html#Replication-Lag-Issues)部分中记录的复制延迟问题。因内部计算操作，复制服务器可能无法处理负载。在这种情况下，请在咨询 [AWS Technical Support 团队](https://support.console.aws.amazon.com/support/)后尝试升级实例类型。 | 

## 相关资源
<a name="set-up-disaster-recovery-for-oracle-jd-edwards-enterpriseone-with-aws-elastic-disaster-recovery-resources"></a>
+ [AWS Elastic Disaster Recovery 用户指南](https://docs.aws.amazon.com/drs/latest/userguide/what-is-drs.html)
+ [使用 AWS Elastic Disaster Recovery 创建可扩展的灾难恢复计划](https://aws.amazon.com/blogs/storage/creating-a-scalable-disaster-recovery-plan-with-aws-elastic-disaster-recovery/)（AWS Blog 文章）
+ [AWS Elastic Disaster Recovery - 技术简介](https://explore.skillbuilder.aws/learn/course/internal/view/elearning/11123/aws-elastic-disaster-recovery-a-technical-introduction)（AWS Skill Builder 课程；需要登录）
+ [AWS Elastic Disaster Recovery 快速入门指南](https://docs.aws.amazon.com/drs/latest/userguide/quick-start-guide-gs.html)

# 在多区域、多账户组织中设置 CloudFormation 偏差检测
<a name="set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization"></a>

*Ram Kandaswamy，Amazon Web Services*

## Summary
<a name="set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization-summary"></a>

Amazon Web Services (AWS) 用户通常会寻找一种有效的方法来检测资源配置不匹配情况，包括 AWS CloudFormation 堆栈中的偏差，并尽快对其进行修复。使用时 AWS Control Tower 尤其如此。

此模式提供了一种规范的解决方案，通过使用整合的资源配置更改并根据这些更改生成结果来有效地解决问题。该解决方案专为在多个 AWS 区域、多个账户或两者组合中创建多个 CloudFormation 堆栈的场景而设计。该解决方案目标包括以下各项：
+ 简化偏差检测过程
+ 设置通知和警报
+ 设置合并报告

## 先决条件和限制
<a name="set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization-prereqs"></a>

**先决条件**
+ AWS Config 在必须监控的所有地区和账户中启用

**限制**
+ 生成的报告仅支持逗号分隔值（CSV）和 JSON 这两种输出格式。

## 架构
<a name="set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization-architecture"></a>

下图显示了使用多个账户的 AWS Organizations 设置。 AWS Config 规则在账户之间进行通信。 

![\[在两个 AWS Organizations 账户中监控堆栈的五步流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/735d0987-b953-47f8-a9bc-b02a88957ee5/images/340cee9a-5a4e-49ea-bd73-d37dcea5e098.png)


 此工作流包含以下步骤：

1. 该 AWS Config 规则可检测偏差。

1. 在其他账户中发现的偏差检测结果将发送至管理账户。

1. Amazon CloudWatch 规则调用一个 AWS Lambda 函数。

1. Lambda 函数查询 AWS Config 规则以获取聚合结果。

1. Lambda 函数通知 Amazon Simple Notification Service（Amazon SNS），由该服务发送偏差的电子邮件通知。

**自动化和扩展**

此处介绍的解决方案可以针对其他区域和账户进行扩展。

## 工具
<a name="set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization-tools"></a>

**AWS 服务**
+ [AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html)提供了中 AWS 资源配置的详细视图 AWS 账户。这些信息包括资源之间的关联方式以及资源以前的配置方式，让您了解资源的配置和关系如何随着的时间的推移而更改。
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可帮助您实时监控您的 AWS 资源和运行的应用程序 AWS 的指标。
+ [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 服务器和电子邮件地址）之间的消息交换。

## 操作说明
<a name="set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization-epics"></a>

### 自动进行漂移检测 CloudFormation
<a name="automate-drift-detection-for-cfn"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建聚合器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization.html) | 云架构师 | 
| 创建 AWS 托管规则。 | 添加`cloudformation-stack-drift-detection-check` AWS****托管规则。该规则需要一个参数值：`cloudformationArn`。输入具有堆栈偏差检测权限的 IAM 角色 Amazon 资源名称（ARN）。该角色必须具有能够代入该角色 AWS Config 的信任策略。 | 云架构师 | 
| 创建聚合器高级查询部分。 | 若要从多个来源获取偏差堆栈，请创建以下查询：<pre>SELECT resourceId, configuration.driftInformation.stackDriftStatus WHERE resourceType = 'AWS::CloudFormation::Stack'  AND configuration.driftInformation.stackDriftStatus IN ('DRIFTED')</pre> | 云架构师、开发人员 | 
| 自动运行查询和发布。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization.html) | 云架构师、开发人员 | 
| 创建 CloudWatch 规则。 | 创建基于计划的 CloudWatch 规则来调用 Lambda 函数，该函数负责发出警报。 | 云架构师 | 

## 相关资源
<a name="set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization-resources"></a>

**资源**
+ [什么是 AWS Config？](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html)
+ [多账户多区域数据聚合](https://docs.aws.amazon.com/config/latest/developerguide/aggregate-data.html)
+ [检测堆栈和资源的非托管配置更改](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html)
+ [IAM：将 IAM 角色传递给特定角色 AWS 服务](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_examples_iam-passrole-service.html)
+ [什么是 Amazon SNS？](https://docs.aws.amazon.com/sns/latest/dg/welcome.html)

## 附加信息
<a name="set-up-aws-cloudformation-drift-detection-in-a-multi-region-multi-account-organization-additional"></a>

**注意事项**

我们建议使用此模式中提供的解决方案，而不是使用涉及按特定时间间隔调用 API 的自定义解决方案，以便在每个 CloudFormation 堆栈或堆栈集上启动漂移检测。按特定时间间隔调用 API 的自定义方案可能会导致大量 API 调用，进而影响性能。由于 API 调用次数较多，可能会发生节流。另一潜在问题是，如果仅根据计划识别资源更改，则检测会出现延迟。

由于堆栈集是由堆栈组成的，因此您可使用此解决方案。堆栈实例详细信息也作为解决方案的一部分提供。

## 附件
<a name="attachments-735d0987-b953-47f8-a9bc-b02a88957ee5"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/735d0987-b953-47f8-a9bc-b02a88957ee5/attachments/attachment.zip)

# 成功导入 S3 存储桶作为 AWS CloudFormation 堆栈
<a name="successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack"></a>

*Ram Kandaswamy，Amazon Web Services*

## Summary
<a name="successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack-summary"></a>

如果您使用亚马逊网络服务 (AWS) 资源，例如亚马逊简单存储服务 (Amazon S3) Simple Service 存储桶，并且想要使用基础设施即代码 (IaC) 方法，则可以将资源导入 AW CloudFormation S 并将其作为堆栈进行管理。

此模式提供了成功将 S3 存储桶导入 AWS CloudFormation 堆栈的步骤。通过使用此模式的方法，您可以避免在单个操作中导入 S3 存储桶时可能出现的错误。

## 先决条件和限制
<a name="successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户。
+ 现有的 S3 存储桶与 S3 存储桶策略。有关这方面的更多信息，请参阅 AWS 知识中心中的 “[我应该使用哪个 S3 存储桶策略来遵守 AWS Config 规则 s3-bucket-ssl-requests-only](https://aws.amazon.com/premiumsupport/knowledge-center/s3-bucket-policy-for-config-rule/)”。
+ 现有 AWS Key Management Service (AWS KMS) 密钥及其别名。有关这方面的更多信息，请参阅 AWS KMS 文档中的[使用别名](https://docs.aws.amazon.com/kms/latest/developerguide/programming-aliases.html)。
+ `CloudFormation-template-S3-bucket`AWS CloudFormation 模板示例（附后），已下载到您的本地计算机。

## 架构
<a name="successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack-architecture"></a>

![\[使用 CloudFormation 模板创建 CloudFormation 堆栈以导入 S3 存储桶的工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/aea7f6fe-8e67-46c4-8b90-1ab06b879111/images/ee143374-a0a4-42d9-b7ca-16593a597a84.png)


 

下图显示了如下工作流：

1. 用户创建一个 JSON 或 YAML 格式的 AWS CloudFormation 模板。

1. 该模板创建一个 AWS CloudFormation 堆栈来导入 S3 存储桶。

1. AWS CloudFormation 堆栈管理您在模板中指定的 S3 存储桶。

**技术堆栈**
+ AWS CloudFormation
+ AWS Identity and Access Management (IAM)
+ AWS KMS
+ Amazon S3

 

**工具**
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) — AWS CloudFormation 可帮助您以可预测的方式重复创建和配置 AWS 基础设施部署。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) – IAM 是一项 Web 服务，用于安全地控制对 AWS 资源的访问。
+ [AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/overview.html) – AWS Key Management Service (AWS KMS) 是一项扩展到云的加密和密钥管理服务。
+ [Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) – Amazon Simple Storage Service (Amazon S3) 是一项面向互联网的存储服务。

## 操作说明
<a name="successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack-epics"></a>

### 将使用 AWS KMS key基于加密的 S3 存储桶作为 AWS CloudFormation 堆栈导入
<a name="import-an-s3-bucket-with-kms-key-long--based-encryption-as-an-aws-cloudformation-stack"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建一个模板，以便导入 S3 存储桶和 KMS 密钥。 | 在本地计算机上，使用如下示例模板创建一个模板，以便导入 S3 存储桶和 KMS 密钥：<pre>AWSTemplateFormatVersion: 2010-09-09<br /><br />Parameters:<br /><br />  bucketName:<br /><br />    Type: String<br /><br />Resources:<br /><br />  S3Bucket:<br /><br />    Type: 'AWS::S3::Bucket'<br /><br />    DeletionPolicy: Retain<br /><br />    Properties:<br /><br />      BucketName: !Ref bucketName<br /><br />      BucketEncryption:<br /><br />        ServerSideEncryptionConfiguration:<br /><br />          - ServerSideEncryptionByDefault:<br /><br />              SSEAlgorithm: 'aws:kms'<br /><br />              KMSMasterKeyID: !GetAtt <br /><br />                - KMSS3Encryption<br /><br />                - Arn<br /><br />  KMSS3Encryption:<br /><br />    Type: 'AWS::KMS::Key'<br /><br />    DeletionPolicy: Retain<br /><br />    Properties:<br /><br />      Enabled: true<br /><br />      KeyPolicy: !Sub |-<br /><br />        {<br /><br />            "Id": "key-consolepolicy-3",<br /><br />            "Version": "2012-10-17",		 	 	 <br /><br />            "Statement": [<br /><br />                {<br /><br />                    "Sid": "Enable IAM User Permissions",<br /><br />                    "Effect": "Allow",<br /><br />                    "Principal": {<br /><br />                        "AWS": ["arn:aws:iam::${AWS::AccountId}:root"]<br /><br />                    },<br /><br />                    "Action": "kms:*",<br /><br />                    "Resource": "*"<br /><br />                }<br /><br />                }<br /><br />            ]<br /><br />        }<br /><br />      EnableKeyRotation: true</pre> | AWS DevOps | 
| 创建堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack.html) | AWS DevOps | 
| 创建 KMS 密钥别名。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack.html)<pre>KMSS3EncryptionAlias:<br /><br />    Type: 'AWS::KMS::Alias'<br /><br />    DeletionPolicy: Retain<br /><br />    Properties: <br /><br />    AliasName: alias/S3BucketKey<br /><br />    TargetKeyId: !Ref KMSS3Encryption</pre>有关这方面的更多信息，请参阅 [AWS CloudFormation 文档中的 AWS CloudFormation 堆栈更新](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks.html)。  | AWS DevOps | 
| 更新堆栈以包含 S3 存储桶策略。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack.html)<pre>S3BucketPolicy:<br /><br />  Type: 'AWS::S3::BucketPolicy'<br /><br />  Properties:<br /><br />    Bucket: !Ref S3Bucket<br /><br />    PolicyDocument: !Sub |-<br /><br />      {<br /><br />                  "Version": "2008-10-17",		 	 	 <br /><br />                  "Id": "restricthttp",<br /><br />                  "Statement": [<br /><br />                      {<br /><br />                          "Sid": "denyhttp",<br /><br />                          "Effect": "Deny",<br /><br />                          "Principal": {<br /><br />                              "AWS": "*"<br /><br />                          },<br /><br />                          "Action": "s3:*",<br /><br />                          "Resource": ["arn:aws:s3:::${S3Bucket}","arn:aws:s3:::${S3Bucket}/*"],<br /><br />                          "Condition": {<br /><br />                              "Bool": {<br /><br />                                  "aws:SecureTransport": "false"<br /><br />                              }<br /><br />                          }<br /><br />                      }<br /><br />                  ]<br /><br />              }</pre>此 S3 存储桶策略具有一个拒绝语句，用于限制不安全的 API 调用。  | AWS DevOps | 
| 更新密钥策略。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack.html)有关详情，请参阅 AWS KMS 文档中的 [AWS KMS中的密钥策略](https://docs.aws.amazon.com/kms/latest/developerguide/key-policies.html)。 | AWS 管理员 | 
| 添加资源级标签。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack.html)<pre>Tags:<br /><br />  - Key: createdBy<br /><br />    Value: Cloudformation</pre> | AWS DevOps | 

## 相关资源
<a name="successfully-import-an-s3-bucket-as-an-aws-cloudformation-stack-resources"></a>
+ [将现有资源引入 AWS CloudFormation 管理](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import.html)
+ [AWS re: Invent 2017：深入了解 AWS CloudFormation](https://www.youtube.com/watch?v=01hy48R9Kr8)（视频）

## 附件
<a name="attachments-aea7f6fe-8e67-46c4-8b90-1ab06b879111"></a>

要访问与此文档相关联的其他内容，请解压以下文件：[attachment.zip](samples/p-attach/aea7f6fe-8e67-46c4-8b90-1ab06b879111/attachments/attachment.zip)

# 使用 AWS 在不同 AWS 区域的 Amazon EFS 文件系统之间同步数据 DataSync
<a name="synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync"></a>

*Sarat Chandra Pothula 和 Aditya Ambati，Amazon Web Services*

## Summary
<a name="synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync-summary"></a>

该解决方案提供了一个强大的框架，用于在不同 AWS 区域中的 Amazon Elastic File System（Amazon EFS）实例之间高效、安全地同步数据。这种方法具有可扩展性，并能够以受控的方式跨区域复制数据。该解决方案可以增强您的灾难恢复和数据冗余策略。

通过使用 AWS Cloud Development Kit（AWS CDK），可以将此模式用作一种基础设施即代码（IaC）方法来部署解决方案资源。AWS CDK 应用程序部署了 AWS、 DataSync亚马逊 EFS、亚马逊虚拟私有云（亚马逊 VPC）和亚马逊弹性计算云（亚马逊 VPC EC2）的基本资源。此 IaC 提供了一个可重复、受版本控制并且完全符合 AWS 最佳实践的部署过程。

## 先决条件和限制
<a name="synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户
+ [已安装](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)且[已配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) AWS 命令行界面（AWS CLI）版本 2.9.11 或更高版本。
+ [已安装](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_install)且[已引导](https://docs.aws.amazon.com/cdk/v2/guide/getting_started.html#getting_started_bootstrap) AWS CDK 2.114.1 或更高版本。
+ NodeJS 20.8.0 或更高版本，[已安装](https://nodejs.org/en/download)。

**限制**
+ 该解决方案继承了 Amazon EFS DataSync 和 Amazon EFS 的限制，例如数据传输速率、大小限制和区域可用性。有关更多信息，请参阅 [AWS DataSync 配额](https://docs.aws.amazon.com/datasync/latest/userguide/datasync-limits.html)和 A [mazon EFS 配额](https://docs.aws.amazon.com/efs/latest/ug/limits.html)。
+ 此解决方案仅支持 Amazon EFS。 DataSync 支持[其他 AWS 服务](https://docs.aws.amazon.com/datasync/latest/userguide/working-with-locations.html)，例如亚马逊简单存储服务 (Amazon S3) Service 和 Amazon for Lust FSx re。然而，该解决方案需要修改，才能与其他的这些服务同步数据。

## 架构
<a name="synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync-architecture"></a>

![\[用于将数据复制到不同区域中的 EFS 文件系统的架构图\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e28ba6c2-ab8b-4812-932e-f038106d5496/images/18b35ae9-a22e-43e7-b7a3-30e40321c44e.png)


该解决方案将部署以下 AWS CDK 堆栈：
+ **Amazon VPC 堆栈** –­ 此堆栈将在主要和次要 AWS 区域中设置虚拟私有云（VPC）资源，包括子网、互联网网关和 NAT 网关。
+ **Amazon EFS 堆栈** — 此堆栈将 Amazon EFS 文件系统部署到主区域和次要区域，并将它们连接到各自 VPCs的区域。
+ **Amazon EC2 堆**栈 — 此堆栈在主要和次要区域启动 EC2 实例。这些实例被配置为挂载 Amazon EFS 文件系统，这样就使它们能够访问共享存储。
+ **DataSync 位置堆栈** — 此堆栈使用名`DataSyncLocationConstruct`为的自定义构造在主要和次要区域中创建 DataSync 位置资源。这些资源将定义用于同步数据的端点。
+ **DataSync 任务堆栈** — 此堆栈使用名`DataSyncTaskConstruct`为的自定义结构在主区域中创建 DataSync 任务。此任务配置为使用 DataSync 源位置和目标位置在主区域与次要区域之间同步数据。

## 工具
<a name="synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync-tools"></a>

**Amazon Web Services**
+ [AWS Cloud Development Kit（AWS CDK）](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一个软件开发框架，可帮助您在代码中定义并预调配 AWS 云基础设施。
+ [AWS DataSync](https://docs.aws.amazon.com/datasync/latest/userguide/what-is-datasync.html) 是一项在线数据传输和发现服务，可帮助您在 AWS 存储服务之间移动文件或对象数据。
+ [亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/ec2/) 在 AWS 云中提供可扩展的计算容量。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [Amazon Elastic File System（Amazon EFS）](https://docs.aws.amazon.com/efs/latest/ug/whatisefs.html)可帮助您在 AWS 云端创建和配置共享文件系统。
+ [Amazon Virtual Private Cloud（Amazon VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。此虚拟网络类似于您在自己的数据中心内运行的传统网络，具有使用 AWS 可扩展基础设施的优势。

**代码存储库**

此模式的代码可在 GitHub [Amazon EFS 跨区域 DataSync 项目](https://github.com/aws-samples/aws-efs-crossregion-datasync/tree/main)存储库中找到。

## 最佳实践
<a name="synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync-best-practices"></a>

遵循中[使用 AWS CDK 创建 IaC 项目的最佳实践中描述 TypeScript 的最佳](https://docs.aws.amazon.com/prescriptive-guidance/latest/best-practices-cdk-typescript-iac/introduction.html)实践。

## 操作说明
<a name="synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync-epics"></a>

### 部署 AWS CDK 应用程序
<a name="deploy-the-aws-cdk-app"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆项目存储库。 | 输入以下命令以克隆 [Amazon EFS 跨区域 DataSync 项目](https://github.com/aws-samples/aws-efs-crossregion-datasync/tree/main)存储库。<pre>git clone https://github.com/aws-samples/aws-efs-crossregion-datasync.git</pre> | AWS DevOps | 
| 安装 npm 依赖项。 | 输入如下命令。<pre>npm ci</pre> | AWS DevOps | 
| 选择主要区域和次要区域。 | 在克隆的存储库中，导航到 `src/infa` 目录。在 `SECONDARY_AWS_REGION` 文件中，更新 `Launcher.ts` 和 `PRIMARY_AWS_REGION` 值。使用相应的[区域代码](https://docs.aws.amazon.com/general/latest/gr/datasync.html#datasync-region)。<pre>const primaryRegion = { account: account, region: '<PRIMARY_AWS_REGION>' };<br />const secondaryRegion = { account: account, region: '<SECONDARY_AWS_REGION>' };</pre> | AWS DevOps | 
| 引导 环境。 | 输入如下命令，以便引导您要使用的 AWS 账户和 AWS 区域。<pre>cdk bootstrap <aws_account>/<aws_region></pre>有关详情，请参阅 AWS CDK 文档中的[引导](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)。 | AWS DevOps | 
| 列出 AWS CDK 堆栈。 | 输入如下命令，以便查看应用程序中的 AWS CDK 堆栈的列表。<pre>cdk ls</pre> | AWS DevOps | 
| 合成 AWS CDK 堆栈。 | 输入以下命令，为 AWS CDK 应用程序中定义的每个堆栈生成一个 AWS CloudFormation 模板。<pre>cdk synth</pre> | AWS DevOps | 
| 部署 AWS CDK 应用程序。 | 输入如下命令，以便将所有堆栈都部署到您的 AWS 账户中，无需手动批准即可进行任何更改。<pre>cdk deploy --all --require-approval never</pre> | AWS DevOps | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 登录主区域中的 EC2 实例。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync.html) | AWS DevOps | 
| 创建一个临时文件。 | 输入如下命令，以便在 Amazon EFS 挂载路径中创建一个临时文件。<pre>sudo dd if=/dev/zero \<br />of=tmptst.dat \<br />bs=1G \<br />seek=5 \<br />count=0<br /><br />ls -lrt tmptst.dat</pre> | AWS DevOps | 
| 启动 DataSync 任务。 | 输入以下命令将临时文件从主区域复制到辅助区域，其中`<ARN-task>`是您的 DataSync 任务的 Amazon 资源名称 (ARN)。<pre>aws datasync start-task-execution \<br />    --task-arn <ARN-task></pre>此命令将以如下格式返回任务执行操作的 ARN。`arn:aws:datasync:<region>:<account-ID>:task/task-execution/<exec-ID>` | AWS DevOps | 
| 检查数据传输状态。 | 输入以下命令来描述 DataSync 执行任务，其中`<ARN-task-execution>`是任务执行的 ARN。<pre>aws datasync describe-task-execution \<br />    --task-execution-arn <ARN-task-execution></pre>当、和`VerifyStatus`都具有值时 `PrepareStatus``TransferStatus`， DataSync 任务就完成了`SUCCESS`。 | AWS DevOps | 
| 登录辅助区域中的 EC2 实例。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync.html) | AWS DevOps | 
| 验证复制操作。 | 输入如下命令，以便确认 Amazon EFS 文件系统中存在此临时文件。<pre>ls -lrt<br />tmptst.dat</pre> | AWS DevOps | 

## 相关资源
<a name="synchronize-data-between-amazon-efs-file-systems-in-different-aws-regions-by-using-aws-datasync-resources"></a>

**AWS 文档**
+ [AWS CDK API 参考](https://docs.aws.amazon.com/cdk/api/v2/python/modules.html)
+ [使用 Amazon EFS 配置 AWS DataSync 转账](https://docs.aws.amazon.com/datasync/latest/userguide/create-efs-location.html)
+ [排除 AWS DataSync 转账问题](https://docs.aws.amazon.com/datasync/latest/userguide/troubleshooting-datasync-locations-tasks.html)

**其他 AWS 资源**
+ [AWS DataSync FAQs](https://aws.amazon.com/datasync/faqs/)

# 使用 LocalStack 和 Terraform 测试来测试 AWS 基础架构
<a name="test-aws-infra-localstack-terraform"></a>

*Ivan Girardi 和 Ioannis Kalyvas，Amazon Web Services*

## Summary
<a name="test-aws-infra-localstack-terraform-summary"></a>

此模式可帮助您在本地测试 Terraform AWS 中的基础设施即代码 (IaC)，而无需在环境中配置基础架构。 AWS 它将 [Terraform Tests 框架](https://developer.hashicorp.com/terraform/language/tests)与。[LocalStack](https://github.com/localstack/localstack)D LocalStack ocker 容器提供了一个模拟各种本地开发环境。 AWS 服务这样可帮助您测试和迭代基础设施部署，而不会在 AWS 云中产生成本。

该解决方案具有以下优势：
+ **成本优化** — 运行测试 LocalStack 无需使用 AWS 服务。这样可以防止您产生与创建、操作和修改这些 AWS 资源相关的成本。
+ **速度和效率** — 本地测试通常也比部署 AWS 资源更快。这一快速反馈循环加快了开发和调试速度。由于在本地 LocalStack 运行，因此无需互联网连接即可开发和测试 Terraform 配置文件。您可以在本地调试 Terraform 配置文件并立即获得反馈，这样就简化了开发过程。
+ **一致性和可重复性** — LocalStack 为测试提供一致的环境。这种一致性有助于确保无论外部 AWS 变化或网络问题如何，测试都会产生相同的结果。
+ **隔离** — 使用测试 LocalStack 可防止意外影响实时 AWS 资源或生产环境。这一隔离使试验和测试各种配置变得安全。
+ **自动化** – 通过与持续集成和持续交付（CI/CD）管道集成，可帮助您自动测试 Terraform [配置文件](https://developer.hashicorp.com/terraform/language/files)。在部署之前，管道会对 IaC 进行全面测试。
+ **灵活性**-您可以模拟不同的和服务配置 AWS 区域 AWS 账户，以更紧密地匹配您的生产环境。

## 先决条件和限制
<a name="test-aws-infra-localstack-terraform-prereqs"></a>

**先决条件**
+ [安装](https://docs.docker.com/get-started/get-docker/) Docker
+ [允许访问](https://docs.docker.com/reference/cli/dockerd/#daemon-socket-option)默认的 Docker 套接字（`/var/run/docker.sock`）。有关详情，请参阅 [LocalStack 文档](https://docs.localstack.cloud/user-guide/aws/lambda/#migrating-to-lambda-v2)。
+ [安装](https://docs.docker.com/compose/install/) Docker Compose
+ [安装](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) Terraform 版本 1.6.0 或更高版本
+ [安装](https://developer.hashicorp.com/terraform/cli) Terraform CLI
+ [配置](https://hashicorp.github.io/terraform-provider-aws/) Terraform AWS 提供者
+ （可选）[安装](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)并[配置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html) AWS Command Line Interface (AWS CLI)。有关如何 AWS CLI 与一起使用的示例 LocalStack，请参阅使用 GitHub [测试 AWS 基础架构 LocalStack 和 Terraform Te](https://github.com/aws-samples/localstack-terraform-test) sts 存储库。

**限制**
+ 此模式为测试亚马逊简单存储服务 (Amazon S3) Simple Service AWS Lambda、 AWS Step Functions、和亚马逊 DynamoDB 资源提供了明确的示例。但是，您可以扩展此解决方案以包括其他 AWS 资源。
+ 此模式提供了在本地运行 Terraform Tests 的说明，但是您可以将测试集成到任何 CI/CD 管道中吗。
+ 此模式提供了使用 LocalStack 社区图片的说明。如果您使用的是 LocalStack Pro 镜像，请参阅 [LocalStack Pro 文档](https://hub.docker.com/r/localstack/localstack-pro)。
+ LocalStack 为不同 AWS APIs提供仿真服务。要获得完整列表，请参阅 [AWS 服务功能覆盖范围](https://docs.localstack.cloud/user-guide/aws/feature-coverage/)。某些高级功能可能需要订阅 LocalStack Pro。

## 架构
<a name="test-aws-infra-localstack-terraform-architecture"></a>

下图显示了该解决方案的架构。主要组件是源代码存储库、 CI/CD 管道和 LocalStack Docker 容器。 LocalStack Docker 容器在 AWS 服务 本地托管以下内容：
+ 一个用于存储文件的 Amazon S3 存储桶
+ Amazon CloudWatch 用于监控和记录
+ 用于运行无服务器代码的 AWS Lambda 函数
+ 用于协调多步骤工作流程的 AWS Step Functions 状态机
+ 一个用于存储 NoSQL 数据的 Amazon DynamoDB 表

![\[CI/CD 管道用于构建和测试 LocalStack Docker 容器和 AWS 资源。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/34bfbdbf-14e7-42a0-9022-c85a9c30cdcd/images/dc61fac9-b92c-4841-9132-ff8bb865eed9.png)


下图显示了如下工作流：

1. 您可以添加一个 Terraform 配置文件，并将它提交到源代码存储库中。

1.  CI/CD 管道检测更改并启动生成过程以进行静态 Terraform 代码分析。管道构建并运行 LocalStack Docker 容器。随后，此管道将启动测试过程。

1. 管道将对象上传到 LocalStack Docker 容器中托管的 Amazon S3 存储桶。

1. 上传对象会调用一个函数。 AWS Lambda 

1. Lambda 函数将亚马逊 S3 事件通知存储在日志中。 CloudWatch 

1. Lambda 函数启动 AWS Step Functions 状态机。

1. 此状态机会将 Amazon S3 对象的名称写入到一个 DynamoDB 表中。

1.  CI/CD 管道中的测试过程会验证上传对象的名称是否与 DynamoDB 表中的条目相匹配。它还会验证 S3 存储桶是否已使用指定名称部署，并且该 AWS Lambda 函数已成功部署。

## 工具
<a name="test-aws-infra-localstack-terraform-tools"></a>

**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 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 服务 来构建关键业务应用程序。

**其他工具**
+ [Docker](https://www.docker.com/) 是一组平台即服务（PaaS）产品，它们利用操作系统级的虚拟化技术在容器中提供软件。
+ [Docker Compose](https://docs.docker.com/compose/) 是一款工具，用于定义和运行多容器应用程序。
+ [LocalStack](https://localstack.cloud)是在单个容器中运行的云服务模拟器。通过使用 LocalStack，您可以在使用的本地计算机上运行工作负载 AWS 服务，而无需连接到 AWS 云。
+ [Terraform](https://www.terraform.io/) 是一款 IaC 工具 HashiCorp ，可帮助您创建和管理云和本地资源。
+ [Terraform Tests](https://developer.hashicorp.com/terraform/language/tests) 可帮助您通过类似于集成或单元测试的测试，来验证 Terraform 模块配置更新。

**代码存储库**

此模式的代码可在[使用 LocalStack 和 Terraform Tests 存储库的 GitHub 测试 AWS 基础架构](https://github.com/aws-samples/localstack-terraform-test)中找到。

## 最佳实践
<a name="test-aws-infra-localstack-terraform-best-practices"></a>
+ 此解决方案测试在 Terraform 配置文件中指定的 AWS 基础架构，并且不会在中部署这些资源。 AWS 云如果您希望部署这些资源，请遵循[最低权限原则](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)（IAM 文档），并正确[配置 Terraform 后端](https://developer.hashicorp.com/terraform/language/backend)（Terraform 文档）。
+ 集成到 CI/CD 管道 LocalStack 中时，我们建议您不要在权限模式下运行 LocalStack Docker 容器。有关更多信息，请参阅[运行时权限和 Linux 功能](https://docs.docker.com/engine/containers/run/#runtime-privilege-and-linux-capabilities)（Docker 文档）和[自管理运行器的安全性](https://docs.gitlab.com/runner/security/)（GitLab 文档）。

## 操作说明
<a name="test-aws-infra-localstack-terraform-epics"></a>

### 部署解决方案
<a name="deploy-the-solution"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 在一个 bash Shell 中，输入如下命令。这将[使用以下内容克隆测试 AWS 基础架构 LocalStack 和 Terraform Te](https://github.com/aws-samples/localstack-terraform-test) sts 存储库： GitHub<pre>git clone https://github.com/aws-samples/localstack-terraform-test.git</pre> | DevOps 工程师 | 
| 运行 LocalStack 容器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/test-aws-infra-localstack-terraform.html) | DevOps 工程师 | 
| 初始化 Terraform。 | 输入以下命令初始化 Terraform：<pre>terraform init</pre> | DevOps 工程师 | 
| 运行 Terraform Tests。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/test-aws-infra-localstack-terraform.html) | DevOps 工程师 | 
| 清理资源。 | 输入以下命令销毁 LocalStack 容器：<pre>docker-compose down</pre> | DevOps 工程师 | 

## 问题排查
<a name="test-aws-infra-localstack-terraform-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 运行 `terraform test` 命令时的 `Error: reading DynamoDB Table Item (Files\|README.md): empty` 结果。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/test-aws-infra-localstack-terraform.html) | 

## 相关资源
<a name="test-aws-infra-localstack-terraform-resources"></a>
+ [Terraform 入门： AWS CloudFormation 专家指南（AWS 规范性指导](https://docs.aws.amazon.com/prescriptive-guidance/latest/getting-started-terraform/introduction.html)） AWS CDK 
+ [使用 Terraform AWS 提供程序的最佳实践](https://docs.aws.amazon.com/prescriptive-guidance/latest/terraform-aws-provider-best-practices/introduction.html)（AWS 规范性指南）
+ [Terraform CI/CD 并 AWS 使用新的 Terraform 测试框架进行测试](https://aws.amazon.com/blogs/devops/terraform-ci-cd-and-testing-on-aws-with-the-new-terraform-test-framework/)（博客文章）AWS 
+ [使用来自的 LocalStack 云仿真器加速软件交付 AWS Marketplace](https://aws.amazon.com/blogs/awsmarketplace/accelerating-software-delivery-localstack-cloud-emulator-aws-marketplace/)（AWS 博客文章）

## 附加信息
<a name="test-aws-infra-localstack-terraform-additional"></a>

**与 GitHub 操作集成**

您可以使用操作在 CI/CD 管道中集成 LocalStack 和 Terraform 测试。 GitHub 有关更多信息，请参阅[GitHub 操作文档](https://docs.github.com/en/actions)。以下是 GitHub 操作配置文件示例：

```
name: LocalStack Terraform Test

on:
  push:
    branches:
      - '**'

  workflow_dispatch: {}

jobs:
  localstack-terraform-test:
    runs-on: ubuntu-latest

    steps:
    - uses: actions/checkout@v4

    - name: Build and Start LocalStack Container
      run: |
        docker compose up -d

    - name: Setup Terraform
      uses: hashicorp/setup-terraform@v3
      with:
        terraform_version: latest

    - name: Run Terraform Init and Validation
      run: |
        terraform init
        terraform validate
        terraform fmt --recursive --check
        terraform plan
        terraform show

    - name: Run Terraform Test
      run: |
        terraform test

    - name: Stop and Delete LocalStack Container
      if: always()
      run: docker compose down
```

# 将 SAP Pacemaker 集群从升级到 ENSA1 ENSA2
<a name="upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2"></a>

*Gergely Cserdi 和 Balazs Sandor Skublics，Amazon Web Services*

## Summary
<a name="upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2-summary"></a>

此模式说明了将基于独立入队服务器 () ENSA1 的 SAP Pacemaker 群集升级到的步骤和注意事项。 ENSA2此模式中的信息适用于 SUSE Linux Enterprise Server (SLES) 和 Red Hat Enterprise Linux (RHEL) 操作系统。

SAP NetWeaver 7.52 或 S/4HANA 1709 及更早版本上的 Pacemaker 集群在 ENSA1 架构上运行，并且经过专门配置。 ENSA1如果你在 Amazon Web Services (AWS) 上运行 SAP 工作负载 ENSA2，并且有兴趣迁移到，你可能会发现 SAP、SUSE 和 RHEL 文档没有提供全面的信息。此模式描述了重新配置 SAP 参数和 Pacemaker 集群以从升级到所需的技术步骤。 ENSA1 ENSA2它提供了 SUSE 系统的示例，但对于 RHEL 集群，概念是相同的。

**注意**  
ENSA1 并且 ENSA2 是仅适用于 SAP 应用程序的概念，因此这种模式中的信息不适用于 SAP HANA 或其他类型的集群。

**注意**  
严格来说， ENSA2 可以搭配或不使用 Enqueue Replicator 2 一起使用。但是，高可用性（HA）和失效转移自动化（通过集群解决方案）需要 Enqueue Replicator 2。此模式使用*ENSA2 集群*一词来指具有独立入队服务器 2 和 Enqueue Replicator 2 的集群。

## 先决条件和限制
<a name="upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2-prereqs"></a>

**先决条件**
+ 一个 ENSA1基于工作的集群，在 SLES 或 RHEL 上使用 Pacemaker 和 Corosync。
+ 至少有两个亚马逊弹性计算云 (Amazon EC2) 实例在其中运行 (ABAP) SAP 中央服务 (ASCS/SCS) 和 Enqueue 复制服务器 (ERS) 实例。
+ 了解管理 SAP 应用程序和集群的知识。
+ 以根用户身份访问 Linux 环境。

**限制**
+ ENSA1基于群集仅支持双节点架构。
+ ENSA2基于集群不能部署到 7.52 之前 NetWeaver 的 SAP 版本。
+ EC2 集群中的实例应位于不同的 AWS 可用区中。

**产品版本**
+ SAP NetWeaver 版本 7.52 或更高版本
+ 从 S/4HANA 2020 开始，仅支持 ENSA2 集群
+ 内核 7.53 或更高版本，它支持 ENSA2 和 Enqueue Replicator 2
+ 适用于 SAP 应用程序的 SLES 版本 12 或更高版本
+ 适用于 SAP 的高可用性 (HA) RHEL 版本 7.9 或更高版本

## 架构
<a name="upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2-architecture"></a>

**源技术堆栈**
+ 带有 SAP 内核 NetWeaver 7.53 或更高版本的 SAP 7.52
+ SLES 或 RHEL 操作系统

**目标技术堆栈**
+ 搭载 SAP 内核 NetWeaver 7.53 或更高版本的 SAP 7.52，包括搭载 ABAP 平台的 S/4HANA 2020
+ SLES 或 RHEL 操作系统

**目标架构**

下图显示了基于 ENSA2 集群的 ASCS/SCS ERS 实例的 HA 配置。

![\[ENSA2 集群上的 HA 架构 ASCS/SCS 和 ERS 实例\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/c32560de-901f-4796-a6b3-c08c109b22c8/images/19501713-0ddf-4242-9ea3-90478200a19e.png)


** ENSA1 和 ENSA2 集群的比较**

SAP ENSA2 作为继任者推出 ENSA1。 ENSA1基于集群的集群支持双节点架构，在这种架构中，当发生错误时， ASCS/SCS 实例会故障转移到 ERS。此限制源于 ASCS/SCS 实例在故障转移后如何从 ERS 节点的共享内存中恢复锁表信息。 ENSA2基于 Enqueue Replicator 2 的集群消除了这一限制，因为该 ASCS/SCS 实例可以通过网络从 ERS 实例收集锁定信息。 ENSA2基于集群可以有两个以上的节点，因为不再需要 ASCS/SCS 实例故障转移到 ERS 节点。（但是，在双节点 ENSA2 群集环境中， ASCS/SCS 实例仍将故障转移到 ERS 节点，因为集群中没有其他节点可供故障切换。） ENSA2 从 SAP 内核 7.50 开始受支持，但有一些限制。对于支持 Enqueue Replicator 2 的 HA 设置，最低要求为 NetWeaver 7.52（参见 [SAP OSS Note](https://launchpad.support.sap.com/#/notes/2630416) 2630416）。默认情况下，S/4HANA 1809 自带推荐的 ENSA2 架构，而 S/4HANA 仅 ENSA2 支持 2020 版开始。

**自动化和扩缩**

目标架构中的 HA 集群可使 ASCS 自动失效转移到其他节点。

**迁移到 ENSA2基于基础的集群的场景**

升级到 ENSA2基于基础的集群有两种主要方案： 
+ 场景 1：假设你的 SAP 版本和内核版本支持，则选择在不进行 SAP 升级或 S/4HANA 转换 ENSA2 的情况下升级到。 ENSA2
+ 场景 2：在升级或转换（例如，升级到 S/4HANA 1809 或更高版本）的过程中，您使用 SUM 迁移到。 ENSA2 

[操作说明](#upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2-epics)部分涵盖了这两种场景的步骤。第一种情况要求您在更改集群配置之前手动设置与 SAP 相关的参数。 ENSA2在第二种场景中，二进制文件和 SAP 相关参数由 SUM 部署，您唯一剩下的任务是更新 HA 的集群配置。我们仍然建议您在使用 SUM 后验证 SAP 参数。在大多数情况下，S/4HANA 转换是集群升级的主要原因。

## 工具
<a name="upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2-tools"></a>
+ 对于操作系统包管理器，我们建议使用 Zypper（适用于 SLES）或 YUM（适用于 RHEL）工具。
+ 对于集群管理，我们建议使用 **crm** (适用于 SLES) 或 **pcs** (适用于 RHEL) shell。
+ SAP 实例管理工具，例如 SAPControl。
+ （可选）用于 S/4HANA 转换升级的 SUM 工具。

## 最佳实践
<a name="upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2-best-practices"></a>
+ 有关在 AWS 上使用 SAP 工作负载的最佳实践，请参阅 AWS Well-Architected Framework 的 [SAP Lens](https://docs.aws.amazon.com/wellarchitected/latest/sap-lens/sap-lens.html)。
+ 考虑一下您的 ENSA2 多节点架构中的群集节点数量（奇数或偶数）。
+ 按照 SAP S/4-HA-CLU 1.0 认证标准为 SLES 15 设置 ENSA2 集群。
+ 在升级到之前，请务必保存或备份现有的集群和应用程序状态 ENSA2。

## 操作说明
<a name="upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2-epics"></a>

### 手动配置 SAP 参数 ENSA2 （仅限方案 1）
<a name="configure-sap-parameters-manually-for-ensa2-scenario-1-only"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置默认配置文件中的参数。 | 如果要在 ENSA2 保持相同 SAP 版本的情况下升级到，或者目标版本默认为 ENSA1，请将默认配置文件（DEFAULT.PFL 文件）中的参数设置为以下值。<pre>enq/enable=TRUE<br />enq/serverhost=sapascsvirt<br />enq/serverinst=10        (instance number of ASCS/SCS instance)<br />enque/process_location=REMOTESA<br />enq/replicatorhost=sapersvirt<br />enq/replicatorinst=11    (instance number of ERS instance)<br />  </pre>其中 `sapascsvirt` 是 ASCS 实例的虚拟主机名，`sapersvirt` 是 ERS 实例的虚拟主机名。您可以更改这些设置以适合您的目标环境。要使用此升级选项，您的 SAP 版本和内核版本必须支持 ENSA2 和 Enqueue Replicator 2。 | SAP | 
| 配置 ASCS/SCS 实例配置文件。 | 如果您想在 ENSA2 保持相同 SAP 版本的情况下升级到，或者您的目标版本默认为 ENSA1，请在 ASCS/SCS 实例配置文件中设置以下参数。 配置文件中定义 ENSA1 的部分如下所示。<pre>#--------------------------------------------------------------<br />Start SAP enqueue server<br />#-------------------------------------------------------------- <br />_EN = en.sap$(SAPSYSTEMNAME)$(INSTANCE_NAME) <br />Execute_04 = local rm -f $(_EN) <br />Execute_05 = local ln -s -f $(DIR_EXECUTABLE)/enserver$(FT_EXE) $(_EN) <br />Start_Program_01 = local $(_EN) pf=$(_PF)<br />  </pre>要重新配置此部分，请执行以下操作： ENSA2[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2.html)更改后，此配置文件部分将如下所示。<pre>#--------------------------------------------------------------<br />Start SAP enqueue server<br />#-------------------------------------------------------------- <br />_ENQ = enq.sap$(SAPSYSTEMNAME)$(INSTANCE_NAME) <br />Execute_04 = local rm -f $(_ENQ) <br />Execute_05 = local ln -s -f $(DIR_EXECUTABLE)/enq_server$(FT_EXE) $(_ENQ) <br />Start_Program_01 = local $(_ENQ) pf=$(_PF) <br />... <br />enq/server/replication/enable = TRUE <br />Autostart = 0</pre>严禁为 `_ENQ` 启用重新启动选项。如果为 `_ENQ` 设置了 `RestartProgram_01`，请将其更改为 `StartProgram_01`。这可以防止 SAP 重新启动服务或干扰集群管理的资源。 | SAP | 
| 配置 ERS 配置文件。 | 如果您想在 ENSA2 保持相同 SAP 版本的情况下升级到，或者您的目标版本默认为 ENSA1，请在 ERS 实例配置文件中设置以下参数。查找定义排队复制器的部分。它类似于以下内容。<pre>#------------------------------------------------------<br />Start enqueue replication server<br />#------------------------------------------------------ <br />_ER = er.sap$(SAPSYSTEMNAME)$(INSTANCE_NAME) <br />Execute_03 = local rm -f $(_ER) <br />Execute_04 = local ln -s -f $(DIR_EXECUTABLE)/enrepserver$(FT_EXE) $(_ER) <br />Start_Program_00 = local $(_ER) pf=$(_PF) NR=$(SCSID)<br />  </pre>要为 Enqueue Replicator 2 重新配置此部分，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2.html)更改后，此配置文件部分应如下所示。<pre>#------------------------------------------------------<br />Start enqueue replication server<br />#------------------------------------------------------ <br />_ENQR = enqr.sap$(SAPSYSTEMNAME)$(INSTANCE_NAME) <br />Execute_01 = local rm -f $(_ENQR) <br />Execute_02 = local ln -s -f $(DIR_EXECUTABLE)/enq_replicator$(FT_EXE) $(_ENQR) <br />Start_Program_00 = local $(_ENQR) pf=$(_PF) NR=$(SCSID) <br />… <br />Autostart = 0</pre>严禁为 `_ENQR` 启用重新启动选项。如果为 `_ENQR` 设置了 `RestartProgram_01`，请将其更改为 `StartProgram_01`。这可以防止 SAP 重新启动服务或干扰集群管理的服务。 | SAP | 
| 重新启动 SAP 启动服务。 | 更改此长篇故事中前面描述的配置文件后，请重新启动两者 ASCS/SCS 和 ERS 的 SAP Start Services。`sapcontrol -nr 10 -function RestartService SCT``sapcontrol -nr 11 -function RestartService SCT`其中，`SCT`指的是 SAP 系统 ID，并假设 10 和 11 分别是 ASCS/SCS 和 ERS 实例的实例号。 | SAP | 

### 重新配置群集 ENSA2 （两种场景都需要）
<a name="reconfigure-the-cluster-for-ensa2-required-for-both-scenarios"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证 SAP 资源代理中的版本号。 | 当您使用 SUM 将 SAP 升级到 S/4HANA 1809 或更高版本时，SUM 会处理 SAP 配置文件中的参数更改。只有集群需要手动调整。不过，我们建议您在对集群进行任何更改之前先验证参数设置。此操作说明中的示例假设您在使用 SUSE 操作系统。如果您在使用 RHEL，则需要使用 YUM 和 **pcs** shell 之类的工具，而不是 Zypper 和 **crm**。检查架构中的两个节点，确认 `resource-agents` 包与 SAP 推荐的最低版本匹配。对于 SLES，请查看 SAP OSS Note 2641019。对于 RHEL，请查看 SAP OSS Note 2641322。(SAP Notes 需要 [SAP ONE Support Launchpad 用户账户](https://support.sap.com/en/my-support/knowledge-base.html)。）<pre>sapers:sctadm 23> zypper search -s -i resource-agents<br />Loading repository data...<br />Reading installed packages...<br />S | Name | Type | Version | Arch | Repository<br />--+-----------------+---------+------------------------------------+--------+-----------------------------<br />i | resource-agents | package | 4.8.0+git30.d0077df0-150300.8.28.1 | x86_64 | SLE-Product-HA15-SP3-Updates</pre>如有必要，请更新 `resource-agents` 版本。 | AWS 系统管理员 | 
| 备份集群配置。 | 按如下方式备份 CRM 集群配置。`crm configure show > /tmp/cluster_config_backup.txt` | AWS 系统管理员 | 
| 设置维护模式。 | 将集群设置为维护模式。`crm configure property maintenance-mode="true"` | AWS 系统管理员 | 
| 检查集群配置。 | 检查当前集群配置。`crm configure show`以下是完整输出的摘录：<pre>node 1: sapascs<br />node 2: sapers<br />...<br />primitive rsc_sap_SCT_ASCS10 SAPInstance \<br />operations $id=rsc_sap_SCT_ASCS10-operations \<br />op monitor interval=120 timeout=60 on-fail=restart \<br />params InstanceName=SCT_ASCS10_sapascsvirt START_PROFILE="/sapmnt/SCT/profile/SCT_ASCS10_sapascsvirt" \ <br />   AUTOMATIC_RECOVER=false \<br />meta resource-stickiness=5000 failure-timeout=60 migration-threshold=1 priority=10<br />primitive rsc_sap_SCT_ERS11 SAPInstance \<br />operations $id=rsc_sap_SCT_ERS11-operations \<br />op monitor interval=120 timeout=60 on-fail=restart \<br />params InstanceName=SCT_ERS11_sapersvirt START_PROFILE="/sapmnt/SCT/profile/SCT_ERS11_sapersvirt" \<br />   AUTOMATIC_RECOVER=false IS_ERS=true \<br />meta priority=1000<br />...<br />colocation col_sap_SCT_no_both -5000: grp_SCT_ERS11 grp_SCT_ASCS10<br />location loc_sap_SCT_failover_to_ers rsc_sap_SCT_ASCS10 \<br />rule 2000: runs_ers_SCT eq 1<br />order ord_sap_SCT_first_start_ascs Optional: rsc_sap_SCT_ASCS10:start rsc_sap_SCT_ERS11:stop symmetrical=false<br />...</pre>其中 `sapascsvirt` 是指 ASCS 实例的虚拟主机名，`sapersvirt` 是指 ERS 实例的虚拟主机名，`SCT` 是指 SAP 系统 ID。 | AWS 系统管理员 | 
| 移除失效转移主机托管限制。 | 在前面的示例中，位置约束`loc_sap_SCT_failover_to_ers`指定 ASCS 的 ENSA1 功能在故障转移时应始终跟随 ERS 实例。使用 ENSA2，ASCS 应该能够自由地故障转移到任何参与的节点，因此您可以移除此限制。`crm configure delete loc_sap_SCT_failover_to_ers` | AWS 系统管理员 | 
| 调整原语。 | 您还需要对 ASCS 和 ERS SAPInstance 原语进行细微的更改。以下是为配置的 ASCS SAPInstance 原语的示例。 ENSA1<pre>primitive rsc_sap_SCT_ASCS10 SAPInstance \<br />operations $id=rsc_sap_SCT_ASCS10-operations \<br />op monitor interval=120 timeout=60 on-fail=restart \<br />params InstanceName=SCT_ASCS10_sapascsvirt START_PROFILE="/sapmnt/SCT/profile/SCT_ASCS10_sapascsvirt" \<br />   AUTOMATIC_RECOVER=false \<br />meta resource-stickiness=5000 failure-timeout=60 migration-threshold=1 priority=10</pre>要升级到 ENSA2，请将此配置更改为以下内容。<pre>primitive rsc_sap_SCT_ASCS10 SAPInstance \<br />operations $id=rsc_sap_SCT_ASCS10-operations \<br />op monitor interval=120 timeout=60 on-fail=restart \<br />params InstanceName=SCT_ASCS10_sapascsvirt START_PROFILE="/sapmnt/SCT/profile/SCT_ASCS10_sapascsvirt" \<br />   AUTOMATIC_RECOVER=false \<br />meta resource-stickiness=3000 </pre>这是为配置的 ERS SAPInstance 基元的示例。 ENSA1<pre>primitive rsc_sap_SCT_ERS11 SAPInstance \<br />operations $id=rsc_sap_SCT_ERS11-operations \<br />op monitor interval=120 timeout=60 on-fail=restart \<br />params InstanceName=SCT_ERS11_sapersvirt START_PROFILE="/sapmnt/SCT/profile/SCT_ERS11_sapersvirt" \<br />   AUTOMATIC_RECOVER=false IS_ERS=true \<br />meta priority=1000</pre>要升级到 ENSA2，请将此配置更改为以下内容。<pre>primitive rsc_sap_SCT_ERS11 SAPInstance \<br />operations $id=rsc_sap_SCT_ERS11-operations \<br />op monitor interval=120 timeout=60 on-fail=restart \<br />params InstanceName=SCT_ERS11_sapersvirt START_PROFILE="/sapmnt/SCT/profile/SCT_ERS11_sapersvirt" \<br />   AUTOMATIC_RECOVER=false IS_ERS=true</pre>您可以通过多种方式更改原语。例如，您可以在 vi 等编辑器中对其进行修改，如下例所示。`crm configure edit rsc_sap_SCT_ERS11` | AWS 系统管理员 | 
| 禁用维护模式。 | 在集群上禁用维护模式。`crm configure property maintenance-mode="false"`当集群退出维护模式时，它会尝试使用新 ENSA2 设置使 ASCS 和 ERS 实例联机。 | AWS 系统管理员 | 

### （可选）添加集群节点
<a name="optional-add-cluster-nodes"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看最佳实践。 | 在添加更多节点之前，请务必了解最佳实践，例如使用奇数还是偶数节点。 | AWS 系统管理员 | 
| 添加节点。 | 添加更多节点涉及一系列任务，例如更新操作系统、安装与现有节点匹配的软件包以及使附加可用。您可以使用 SAP Software Provisioning Manager (SWPM) 中的**准备其他主机**选项来创建主机的 SAP 特定基准。有关更多信息，请参阅下一部分中列出的 SAP 指南。 | AWS 系统管理员 | 

## 相关资源
<a name="upgrade-sap-pacemaker-clusters-from-ensa1-to-ensa2-resources"></a>

**SAP 和 SUSE 参考资料**

要访问 SAP Notes，您必须拥有 SAP ONE Support Launchpad 用户账户。有关详情，请参阅 [SAP 支持网站](https://support.sap.com/en/my-support/knowledge-base.html)。
+ [SAP Note 2501860 — 适用于 ABAP 7.52 的 SAP NetWeaver 应用程序服务器文档](https://launchpad.support.sap.com/#/notes/2501860)
+ [SAP Note 2641019 − 在 SUSE HA 环境 ENSA2 中安装 ENSA2 并从更新 ENSA1 到](https://launchpad.support.sap.com/#/notes/2641019)
+ [SAP Note 2641322 — 使用适用于 SAP 的红帽 HA 解决方案 ENSA2 时的安装 ENSA2 和更新从 ENSA1 到](https://launchpad.support.sap.com/#/notes/2641322)
+ [SAP Note 2711036 — 在 HA 环境中使用独立排队服务器 2](https://launchpad.support.sap.com/#/notes/2711036)
+ [独立排队服务器 2](https://help.sap.com/docs/ABAP_PLATFORM/cff8531bc1d9416d91bb6781e628d4e0/902412f09e134f5bb875adb6db585c92.html)（SAP 文档）
+ [SAP S/4 HANA — Enqueue Replication 2 高可用性集群 — 设置指南](https://documentation.suse.com/sbp/all/html/SAP_S4HA10_SetupGuide-SLE12/index.html)（SUSE 文档）

**AWS 参考**
+ [SAP HANA on AWS：适用于 SLES 和 RHEL 的高可用性配置指南](https://docs.aws.amazon.com/sap/latest/sap-hana/sap-hana-on-aws-ha-configuration.html)
+ [SAP Lens – AWS Well-Architected Framework](https://docs.aws.amazon.com/wellarchitected/latest/sap-lens/sap-lens.html)

# 在不同的 AWS 账户中 VPCs 使用一致的可用区
<a name="use-consistent-availability-zones-in-vpcs-across-different-aws-accounts"></a>

*Adam Spicer，Amazon Web Services*

## Summary
<a name="use-consistent-availability-zones-in-vpcs-across-different-aws-accounts-summary"></a>

在 Amazon Web Services（AWS）云上，可用区的名称可能因您的 AWS 账户和标识其位置的[可用区 ID（AZ ID）](https://docs.aws.amazon.com/ram/latest/userguide/working-with-az-ids.html)而异。如果您使用 AWS CloudFormation 创建虚拟私有云 (VPCs)，则在创建子网时必须指定可用区的名称或 ID。如果您 VPCs 在多个账户中创建，则可用区名称是随机分配的，这意味着子网在每个账户中使用不同的可用区。 

要在您的账户中使用相同的可用区，您必须将每个账户中的可用区名称映射至相同的可用区 ID。例如，下图表明，`use1-az6` 可用区 ID 在 AWS 账户 A 中名为 `us-east-1a`，在 AWS 账户 Z 中名为 `us-east-1c`。

![\[use1-az6 可用区 ID 在 AWS 账户 A 中名为 us-east-1a，在 AWS 账户 Z 中名为 us-east-1c。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/9954e7f9-d6ce-44bd-af99-0c6bb7cd3cb0/images/23c8a37b-2408-4534-a1e0-bccfa4d7fbe3.png)


 

此模式提供了一个跨账户、可扩展的解决方案，用于在子网中使用同一个可用区，从而帮助确保区域一致性。区域一致性可确保您的跨账户网络流量避免跨可用区网络路径，这有助于降低数据传输成本并降低工作负载之间的网络延迟。

这种模式是 AWS CloudFormation [AvailabilityZoneId 属](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html#cfn-ec2-subnet-availabilityzoneid)性的另一种方法。

## 先决条件和限制
<a name="use-consistent-availability-zones-in-vpcs-across-different-aws-accounts-prereqs"></a>

**先决条件**
+ 位于相同 AWS 区域 中的两个有效 AWS 账户。
+ 评估需要多少个可用区来支持您在该区域中的 VPC 要求。
+ 识别并记录您需要支持的每个可用区的可用区 ID。有关这方面的更多信息，请参阅 [AWS Resource Access Manager 文档中的您的 AWS 资源的可用区 IDs ](https://docs.aws.amazon.com/ram/latest/userguide/working-with-az-ids.html)。 
+ 以逗号分隔的按顺序排列的可用区列表。 IDs例如，列表中的第一个可用区映射为 `az1`，第二个可用区映射为 `az2`，此映射结构将一直持续到以逗号分隔的列表完全映射为止。可以映射的可用区 IDs 数量没有上限。 
+  GitHub [多账户可用区映射](https://github.com/aws-samples/multi-account-az-mapping/)存储库中的`az-mapping.yaml`文件已复制到您的本地计算机

## 架构
<a name="use-consistent-availability-zones-in-vpcs-across-different-aws-accounts-architecture"></a>

下图显示了在账户中部署和创建 AWS Systems Manager Parameter Store 值的架构。当您在账户中创建 VPC 时，将消耗这些 Parameter Store 值。

![\[用于为每个可用区 ID 创建 Systems Manager Parameter Store 值并存储可用区名称的工作流。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/9954e7f9-d6ce-44bd-af99-0c6bb7cd3cb0/images/f1168464-55f8-4efc-9b28-6a0cda668b9e.png)


下图显示了如下工作流：

1. 此模式的解决方案部署到需要 VPC 区域一致性的所有账户。 

1. 该解决方案为每个可用区 ID 创建 Parameter Store 值并存储新的可用区名称。 

1. AWS CloudFormation 模板使用存储在每个 Parameter Store 值中的可用区名称，这样可以确保区域一致性。

下图显示了使用此模式的解决方案创建 VPC 的工作流。

 

![\[工作流提交 CloudFormation 模板以创建具有正确可用区的 VPC IDs。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/9954e7f9-d6ce-44bd-af99-0c6bb7cd3cb0/images/cd859430-ac25-479f-b56a-21da24cddf21.png)


 

下图显示了如下工作流：

1. 向 AWS 提交用于创建 VPC 的模板 CloudFormation。

1. AWS CloudFormation 解析每个可用区的参数存储值，并返回每个可用区 ID 的可用区名称。

1. 使用区域一致性 IDs 所需的正确可用区创建 VPC。

部署此模式的解决方案后，您可创建引用参数存储值的子网。如果您使用 AWS CloudFormation，则可以引用以下 YAML 格式的示例代码中的可用区映射参数值：

```
Resources:
    PrivateSubnet1AZ1: 
        Type: AWS::EC2::Subnet 
        Properties: 
            VpcId: !Ref VPC
            CidrBlock: !Ref PrivateSubnetAZ1CIDR
            AvailabilityZone: 
                !Join 
                    - ''
                    - - '{{resolve:ssm:/az-mapping/az1:1}}'
```

此示例代码包含在 GitHub [多账户可用区映射](https://github.com/aws-samples/multi-account-az-mapping/)存储库`vpc-example.yaml `的文件中。它向您展示如何创建与 Parameter Store 值一致的 VPC 和子网以实现区域一致性。

**技术堆栈**
+ AWS CloudFormation
+ AWS Lambda
+ AWS Systems Manager Parameter Store

**自动化和扩展**

您可以使用 AWS CloudFormation StackSets 或 AWS Control Tower 定制解决方案将此模式部署到您的所有 AWS 账户。有关更多信息，请参阅 [AWS](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) Cloudformation 文档 CloudFormation StackSets中的 “使用 AWS” 和 AWS 解决方案库中的 [AWS Control Tower 自定义设置](https://aws.amazon.com/solutions/implementations/customizations-for-aws-control-tower/)。 

部署 AWS CloudFormation 模板后，您可以将其更新为使用 Parameter Store 值，并在管道 VPCs 中或根据您的要求进行部署。 

## 工具
<a name="use-consistent-availability-zones-in-vpcs-across-different-aws-accounts-tools"></a>

**AWS 服务**
+ [AWS 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) 是一项计算服务，支持无需预置或管理服务器即可运行代码。只有在需要时 Lambda 才运行您的代码，并且能自动扩缩，从每天几个请求扩展到每秒数千个请求。您只需为消耗的计算时间付费 - 代码未运行时不产生费用。
+ [AWS Systems Manager Parameter Store](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html) 是 AWS Systems Manager 的其中一项功能。它可提供安全的分层存储，用于配置数据管理和密钥管理。

**代码**

此模式的代码在 GitHub [多账户可用区映射](https://github.com/aws-samples/multi-account-az-mapping/)存储库中提供。

## 操作说明
<a name="use-consistent-availability-zones-in-vpcs-across-different-aws-accounts-epics"></a>

### 部署 az-mapping.yaml 文件
<a name="deploy-the-az-mapping-yaml-file"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 确定该区域所需可用区。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/use-consistent-availability-zones-in-vpcs-across-different-aws-accounts.html) | 云架构师 | 
| 部署 az-mapping.yaml 文件。 | 使用该`az-mapping.yaml`文件在所有必需的 AWS 账户中创建 AWS CloudFormation 堆栈。在 `AZIds` 参数中，使用您之前创建的以逗号分隔的列表。 我们建议您使用 [AWS CloudFormation StackSets 或 AWS](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html) Cont [rol Tower 定制解决方案](https://aws.amazon.com/solutions/implementations/customizations-for-aws-control-tower/)。 | 云架构师 | 

### VPCs 在您的账户中部署
<a name="deploy-the-vpcs-in-your-accounts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 自定义 AWS CloudFormation 模板。 | 使用 AWS 创建子网时 CloudFormation，请自定义模板以使用您之前创建的参数存储值。有关示例模板，请参阅 GitHub [多账户可用区映射](https://github.com/aws-samples/multi-account-az-mapping/)存储库中的`vpc-example.yaml`文件。 | 云架构师 | 
| 部署 VPCs。 | 将自定义 AWS CloudFormation 模板部署到您的账户。然后，该区域中的每个 VPC 在用于子网可用区中都具有区域一致性 | 云架构师 | 

## 相关资源
<a name="use-consistent-availability-zones-in-vpcs-across-different-aws-accounts-resources"></a>
+ [您 IDs 的 AWS 资源的可用区（AWS R](https://docs.aws.amazon.com/ram/latest/userguide/working-with-az-ids.html) esource Access Manager 文档）
+ [AWS::EC2::Subnet](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-subnet.html)（AWS CloudFormation 文档）

# IDs 在 IAM 策略中使用用户进行访问控制和自动化
<a name="use-user-ids-iam-policies-access-control-automation"></a>

*Srinivas Ananda Babu 和 Ram Kandaswamy，Amazon Web Services*

## Summary
<a name="use-user-ids-iam-policies-access-control-automation-summary"></a>

这种模式解释了在 AWS Identity and Access Management (IAM) 中使用基于用户名的策略的潜在缺陷、使用用户的 IDs好处以及如何将这种方法与 AWS CloudFormation 集成以实现自动化。

在中 AWS 云，IAM 服务可帮助您精确地管理用户身份和访问控制。然而，由于在创建 IAM 策略时依赖用户名，因此可能导致不可预见的安全风险和访问控制问题。例如，考虑这样一个场景：新员工 John Doe 加入了您的团队，您使用用户名 `j.doe` 创建了一个 IAM 用户账户，此账户通过引用用户名的 IAM 策略向他们授予权限。当 John 离开公司时，删除了此账户。当新员工 Jane Doe 加入您的团队，并因此重新创建了 `j.doe` 用户名时，麻烦开始了。现有的策略现在为 Jane Doe 授予与 John Doe 相同的权限。这样会产生安全隐患和合规隐患。

当手动更新每条策略以便反映新的用户详细信息时，这一过程既耗时又容易出错，尤其是在贵组织的成长过程中。该解决方案将使用一个唯一且不可变的用户 ID。创建 IAM 用户账户时，会为 IAM 用户 AWS 分配一个唯一的用户 ID（或委托人 ID）。您可以在 IAM 策略 IDs 中使用这些用户来确保一致可靠的访问控制，且不会受到用户名更改或重复使用的影响。

例如，使用用户 ID 的 IAM 策略可能如下所示：

```
{ 
    "Version": "2012-10-17",		 	 	  
    "Statement": [ 
        { 
            "Effect": "Allow", 
            "Action": "s3:ListBucket", 
            "Resource": "arn:aws:s3:::example-bucket", 
            "Principal": { "AWS": "arn:aws:iam::123456789012:user/abcdef01234567890" } 
        } 
      ] 
}
```

在 IAM 策略 IDs 中使用用户的好处包括：
+ **独特性。**用户 IDs 在所有方面都是独一无二的 AWS 账户，因此他们提供正确且一致的权限申请。
+ **不可变性。**用户 IDs 无法更改，因此它们为在策略中引用用户提供了稳定的标识符。
+ **审计与合规。** AWS 服务 通常 IDs 在日志和审计跟踪中包含用户，这样可以轻松地将操作追溯到特定用户。
+ **自动化和集成。** IDs 在 AWS APIs SDKs、或自动化脚本中使用用户可以确保流程不受用户名更改的影响。
+ **适应未来需求。**从一开始就 IDs 在策略中使用用户可以防止潜在的访问控制问题或大量的策略更新。

**自动化**

当您使用诸如之类的基础设施即代码 (IaC) 工具时 AWS CloudFormation，基于用户名的 IAM 策略的陷阱仍可能导致问题。当您调用 `Ref` 内置函数时，IAM 用户资源将返回用户名。随着贵组织的基础设施不断发展，如果您重复使用用户名，创建并删除资源（包括 IAM 用户账户）这一循环可能会导致意外的访问控制问题。

要解决此问题，我们建议您将用户加入您的 CloudFormation 模板 IDs 中。但是，为此目的 IDs 获取用户可能具有挑战性。在这一方面，自定义资源可以大显身手。您可以使用 CloudFormation 自定义资源通过与 AWS APIs 外部服务集成来扩展服务的功能。通过创建用于获取给定 IAM 用户的用户 ID 的自定义资源，您可以在 CloudFormation 模板中提供该用户 ID。这种方法简化了引用用户的流程， IDs 并确保您的自动化工作流程保持稳健且面向未来。

## 先决条件和限制
<a name="use-user-ids-iam-policies-access-control-automation-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ 云管理员用于运行 CloudFormation 模板的 IAM 角色

**限制**
+ 有些 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="use-user-ids-iam-policies-access-control-automation-architecture"></a>

**目标架构**

下图显示了如何 CloudFormation 使用由支持的自定义资源 AWS Lambda 来检索 IAM 用户 ID。

![\[使用 CloudFormation 自定义资源获取 IAM 用户 ID。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/71698647-274e-4911-92f0-549e444b53f6/images/7e507df4-f597-499e-bd5b-6d7a55e64146.png)


**自动化和扩展**

您可以为不同的 AWS 区域 账户多次使用该 CloudFormation 模板。您只需在每个区域或账户中运行一次此模板。

## 工具
<a name="use-user-ids-iam-policies-access-control-automation-tools"></a>

**AWS 服务**
+ [IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) — AWS Identity and Access Management (IAM) 是一项网络服务，可帮助您安全地控制对 AWS 资源的访问。可以使用 IAM 来控制谁通过了身份验证（准许登录）并获得授权（具有相应权限）来使用资源。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)— AWS CloudFormation 帮助您对 AWS 资源进行建模和设置，这样您就可以花更少的时间管理这些资源，而将更多的时间集中在运行的应用程序上 AWS。您可以创建一个描述 AWS 所需资源的模板，并 CloudFormation 负责为您配置和配置这些资源。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)— AWS Lambda 是一项计算服务，无需预置或管理服务器即可支持运行代码。Lambda 只在需要时运行您的代码，并自动进行扩展，从每天几个请求扩展到每秒数千个请求。 

## 最佳实践
<a name="use-user-ids-iam-policies-access-control-automation-best-practices"></a>

如果您是从头开始或者正在计划进行全新部署，强烈建议您使用 [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) 来实现集中式用户管理。IAM Identity Center 可与您现有的身份提供商（例如 Active Directory 或 Okta）集成 AWS，从而无需直接创建和管理 IAM 用户。这种方法不仅可以确保一致的访问控制，还可以简化用户生命周期管理，并有助于增强整个 AWS 环境的安全性和合规性。

## 操作说明
<a name="use-user-ids-iam-policies-access-control-automation-epics"></a>

### 验证权限
<a name="validate-permissions"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 验证您的 AWS 账户 和 IAM 角色。 | 确认您拥有的 IAM 角色有权在您的中部署 CloudFormation 模板 AWS 账户。如果您计划在本过程的最后一步中使用 AWS CLI 而不是 CloudFormation 控制台来部署模板，则还应设置临时证书以运行 AWS CLI 命令。有关说明，请参阅 [IAM 文档](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html#using-temp-creds-sdk-cli)。 | 云架构师 | 

### 生成一个 CloudFormation 模板
<a name="build-a-cfnshort-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 CloudFormation 模板。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/use-user-ids-iam-policies-access-control-automation.html) | AWS DevOps，云架构师 | 
| 为用户名添加一个输入参数。 | 将以下代码添加到 CloudFormation 模板的`Parameters`部分：<pre>Parameters:<br />  NewIamUserName:<br />    Type: String<br />    Description: Unique username for the new IAM user<br /></pre>此参数将提示用户输入用户名。 | AWS DevOps，云架构师 | 
| 添加一个自定义资源，以便创建一个 IAM 用户。 | 将以下代码添加到 CloudFormation 模板的`Resources`部分：<pre>Resources:<br />  rNewIamUser:<br />    Type: 'AWS::IAM::User'<br />    Properties:<br />      UserName: !Ref NewIamUserName<br /></pre>此代码添加了一个 CloudFormation 资源，该资源使用`NewIamUserName`参数提供的名称创建 IAM 用户。 | AWS DevOps，云架构师 | 
| 为 Lambda 函数添加一个执行角色。 | 在此步骤中，您将创建一个 IAM 角色，该角色向 AWS Lambda 函数授予获取 IAM 的权限`UserId`。指定以下最低必要权限，以使 Lambda 能够运行：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/use-user-ids-iam-policies-access-control-automation.html)有关如何创建执行角色的说明，请参阅 [Lambda 文档](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html)。您将在下一步中创建 Lambda 函数时引用此角色。 | AWS 管理员、云架构师 | 
| 添加一个 Lambda 函数，以便获取唯一的 IAM `UserId`。 | 在此步骤中，您将使用一个 Python 运行时来定义一个 Lambda 函数，以便获取唯一的 IAM `UserId`。为此，请将以下代码添加到 CloudFormation 模板的`Resources`部分。将 `<<ROLENAME>>` 替换为您在最后一步中创建的执行角色的名称。<pre>  GetUserLambdaFunction:<br />    Type: 'AWS::Lambda::Function'<br />    Properties:<br />      Handler: index.handler<br />      Role: <<ROLENAME>><br />      Timeout: 30<br />      Runtime: python3.11<br />      Code:<br />        ZipFile: |<br />          import cfnresponse, boto3<br />          def handler(event, context):<br />            try:<br />              print(event)<br />              user = boto3.client('iam').get_user(UserName=event['ResourceProperties']['NewIamUserName'])['User']<br />              cfnresponse.send(event, context, cfnresponse.SUCCESS, {'NewIamUserId': user['UserId'], 'NewIamUserPath': user['Path'], 'NewIamUserArn': user['Arn']})<br />            except Exception as e:<br />              cfnresponse.send(event, context, cfnresponse.FAILED, {'NewIamUser': str(e)})<br /></pre> | AWS DevOps，云架构师 | 
| 添加一个自定义资源。 | 将以下代码添加到 CloudFormation 模板的`Resources`部分：<pre>  rCustomGetUniqueUserId:<br />    Type: 'Custom::rCustomGetUniqueUserIdWithLambda'<br />    Properties:<br />      ServiceToken: !GetAtt GetUserLambdaFunction.Arn<br />      NewIamUserName: !Ref NewIamUserName<br /></pre>此自定义资源将调用 Lambda 函数，以便获取 IAM `UserID`。 | AWS DevOps，云架构师 | 
| 定义 CloudFormation 输出。 | 将以下代码添加到 CloudFormation 模板的`Outputs`部分：<pre>Outputs:<br />  NewIamUserId:<br />    Value: !GetAtt rCustomGetUniqueUserId.NewIamUserId<br /></pre>这将显示新 IAM 用户的 IAM `UserID`。 | AWS DevOps，云架构师 | 
| 保存此模板。 | 保存对 CloudFormation 模板所做的更改。 | AWS DevOps，云架构师 | 

### 部署 CloudFormation 模板
<a name="deploy-the-cfnshort-template"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 CloudFormation 模板。 | 要使用 CloudFormation 控制台部署`get_unique_user_id.yaml`模板，请按照[CloudFormation 文档](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)中的说明进行操作。或者，您可以运行以下 AWS CLI 命令来部署模板：<pre>aws cloudformation create-stack \<br />--stack-name DemoNewUser \<br />--template-body file://get_unique_user_id.yaml \<br />--parameters ParameterKey=NewIamUserName,ParameterValue=demouser \<br />--capabilities CAPABILITY_NAMED_IAM</pre> | AWS DevOps，云架构师 | 

## 相关资源
<a name="use-user-ids-iam-policies-access-control-automation-resources"></a>
+ [从 CloudFormation 控制台创建堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html)（CloudFormation 文档）
+ [Lambda 支持的自定义资源（文档](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources-lambda.html)）CloudFormation 
+ [唯一标识符](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids)（IAM 文档）
+ [将临时证书与 AWS 资源配合使用](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html)（IAM 文档）

# 在本地验证 Account Factory for Terraform (AFT) 代码
<a name="validate-account-factory-for-terraform-aft-code-locally"></a>

*Alexandru Pop 和 Michal Gorniak，Amazon Web Services*

## Summary
<a name="validate-account-factory-for-terraform-aft-code-locally-summary"></a>

此模式显示了如何在本地测试由 Acco AWS Control Tower unt Fact HashiCorp ory for Terraform（AFT）管理的 Terraform 代码。Terraform 是一款基础设施即代码（IaC）工具，可帮助您使用代码来预调配和管理云基础设施和资源。AFT 设置了一个 Terraform 管道，可以帮助你在其中配置和自定义多个 AWS 账户 管道。 AWS Control Tower

在代码开发过程中，在 AFT 管道之外，在本地测试 Terraform 基础设施即代码（IaC）可能非常有用。此模式说明了如何执行以下操作：
+ 检索存储在您的 AFT 管理账户存储 AWS CodeCommit 库中的 Terraform 代码的本地副本。
+ 使用检索到的代码，在本地模拟 AFT 管道。

此过程还可以用于运行不属于普通 AFT 管道的 Terraform 命令。例如，您可使用此方法来运行 `terraform validate`、`terraform plan`、`terraform destroy` 和 `terraform import` 等命令。

## 先决条件和限制
<a name="validate-account-factory-for-terraform-aft-code-locally-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 多账户环境，使用 [AWS Control Tower](https://aws.amazon.com/controltower)
+ 已全面部署 [AFT 环境](https://docs.aws.amazon.com/controltower/latest/userguide/taf-account-provisioning.html)
+ 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)
+ AWS CLI 已安装并@@ [配置的 AWS CodeCommit凭证助手](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-https-unixes.html)
+ Python 3.x
+ 已在本地计算机上安装并配置 [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
+ [已安装并配置 `git-remote-commit` 实用程序](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-git-remote-codecommit.html#setting-up-git-remote-codecommit-install)
+ 已安装并配置 [Terraform](https://learn.hashicorp.com/collections/terraform/aws-get-started?utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS)（本地 Terraform 软件包版本必须与 AFT 部署中使用的版本相匹配）

**限制**
+ 此模式不包括 AFT 或任何特定 Terraform 模块所需的 AWS Control Tower部署步骤。
+ 在此过程中在本地生成的输出不会保存到 AFT 管道运行时日志中。

## 架构
<a name="validate-account-factory-for-terraform-aft-code-locally-architecture"></a>

**目标技术堆栈**
+ 部署在部署中部署的 AFT 基础架构 AWS Control Tower 
+ Terraform
+ Git
+ AWS CLI 第 2 版

**自动化和扩展**

此模式显示了如何在单个 AFT 管理的单个 AFT 管理中本地调用 Terraform 代码以进行 AFT 全局账户自定义。 AWS 账户验证您的 Terraform 代码之后，您可以将其应用到多账户环境中的其余账户。有关更多信息，请参阅文档中的 “[重新调用自定义](https://docs.aws.amazon.com/controltower/latest/userguide/aft-account-customization-options.html#aft-re-invoke-customizations)” AWS Control Tower 。

您还可以使用类似的过程，在本地终端中进行 AFT 账户自定义。要从 AFT 账户自定义项中本地调用 Terraform 代码，请在 AFT 管理账户中克隆**aft-account-customizations**存储库，而不是从 AFT **aft-global-account-customizations**管理账户 CodeCommit 中克隆存储库。

## 工具
<a name="validate-account-factory-for-terraform-aft-code-locally-tools"></a>

**AWS 服务**
+ [AWS Control Tower](https://docs.aws.amazon.com/controltower/latest/userguide/what-is-control-tower.html)按照规范性最佳实践，帮助您设置和管理 AWS 多账户环境。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您 AWS 服务 通过命令行外壳中的命令进行交互。

**其他服务**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款基础设施即代码（IaC）工具，可帮助您使用代码来预调配和管理云基础设施和资源。
+ [Git](https://git-scm.com/docs) 是开源分布式版本控制系统。

**代码**

以下是 bash 脚本示例，可在本地运行由 AFT 管理的 Terraform 代码。若要使用此脚本，请按照此模式[操作说明](#validate-account-factory-for-terraform-aft-code-locally-epics)部分中的说明操作。

```
#! /bin/bash
# Version: 1.1 2022-06-24 Unsetting AWS_PROFILE since, when set, it interferes with script operation
#          1.0 2022-02-02 Initial Version
#
# Purpose: For use with AFT: This script runs the local copy of TF code as if it were running within AFT pipeline.
#        * Facilitates testing of what the AFT pipline will do 
#           * Provides the ability to run terraform with custom arguments (like 'plan' or 'move') which are currently not supported within the pipeline.
#
# © 2021 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.
# This AWS Content is provided subject to the terms of the AWS Customer Agreement
# available at http://aws.amazon.com/agreement or other written agreement between
# Customer and either Amazon Web Services, Inc. or Amazon Web Services EMEA SARL or both.
#
# Note: Arguments to this script are passed directly to 'terraform' without parsing nor validation by this script.
#
# Prerequisites:
#    1. local copy of ct GIT repositories
#    2. local backend.tf and aft-providers.tf filled with data for the target account on which terraform is to be run
#       Hint: The contents of above files can be obtain from the logs of a previous execution of the AFT pipeline for the target account.
#    3. 'terraform' binary is available in local PATH
#    4. Recommended: .gitignore file containing 'backend.tf', 'aft_providers.tf' so the local copy of these files are not pushed back to git

readonly credentials=$(aws sts assume-role \
    --role-arn arn:aws:iam::$(aws sts get-caller-identity --query "Account" --output text ):role/AWSAFTAdmin \
    --role-session-name AWSAFT-Session \
    --query Credentials )

unset AWS_PROFILE
export AWS_ACCESS_KEY_ID=$(echo $credentials | jq -r '.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo $credentials | jq -r '.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo $credentials | jq -r '.SessionToken')
terraform "$@"
```

## 操作说明
<a name="validate-account-factory-for-terraform-aft-code-locally-epics"></a>

### 将示例代码保存为本地文件
<a name="save-the-example-code-as-a-local-file"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将示例代码保存为本地文件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html) | AWS 管理员 | 
| 让示例代码可以运行。 | 打开终端窗口，通过执行以下任一操作 AWS 在您的 AFT 管理账户中进行身份验证：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html)您的组织可能还有一个自定义工具，可以为您的 AWS 环境提供身份验证凭证。 | AWS 管理员 | 
| 在正确的 AWS 区域中，验证对 AFT 管理账户的访问权限。 | 请确保使用您通过身份验证登录到您的 AFT 管理账户时使用的那个终端会话。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html) | AWS 管理员 | 
| 创建新的本地目录来存储 AFT 存储库代码。 | 从相同的终端会话中，运行以下两个命令：<pre>mkdir my_aft <br />cd my_aft</pre> | AWS 管理员 | 
| 克隆远程 AFT 存储库代码。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html) | AWS 管理员 | 

### 创建 AFT 管道本地运行所需 Terraform 配置文件
<a name="create-the-terraform-configuration-files-required-for-the-aft-pipeline-to-run-locally"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 打开之前运行的 AFT 管道，并将 Terraform 配置文件复制到一个本地文件夹。 | 为使 AFT 管道在本地运行，需要使用在此操作说明中创建的 `backend.tf` 和 `aft-providers.tf` 配置文件。这些文件是在基于云的 AFT 管道内自动创建的，但必须手动创建这些文件，管道才能在本地运行。要在本地运行 AFT 管道，需要一组文件，这些文件表示在单个 AWS 账户内运行管道。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html)**自动生成的 backend.tf 语句示例**<pre>## Autogenerated backend.tf ##<br />## Updated on: 2022-05-31 16:27:45 ##<br />terraform {<br />  required_version = ">= 0.15.0"<br />  backend "s3" {<br />    region         = "us-east-2"<br />    bucket         = "aft-backend-############-primary-region"<br />    key            = "############-aft-global-customizations/terraform.tfstate"<br />    dynamodb_table = "aft-backend-############"<br />    encrypt        = "true"<br />    kms_key_id     = "########-####-####-####-############"<br />    role_arn       = "arn:aws:iam::#############:role/AWSAFTExecution"<br />  }<br />}</pre>**`backend.tf`**和`aft-providers.tf`文件与特定 AWS 账户的 AFT 部署和文件夹相关联。这些文件也有所不同，具体取决于它们是否位于同一 AFT 部署中的**aft-global-customizations**和**aft-account-customizations**存储库中。确保从同一个运行时列表中生成两个文件。 | AWS 管理员 | 

### 使用示例 bash 脚本，在本地运行 AFT 管道
<a name="run-the-aft-pipeline-locally-by-using-the-example-bash-script"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 实施要验证的 Terraform 配置更改。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html) | AWS 管理员 | 
| 运行 `ct_terraform.sh` 脚本并查看输出。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html)** **[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html) | AWS 管理员 | 

### 将本地代码更改推送回 AFT 存储库
<a name="push-your-local-code-changes-back-to-the-aft-repository"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将对 `backend.tf` 和 `aft-providers.tf` 文件的引用添加到一个 `.gitignore` 文件中。 | 运行以下命令，以便将您创建的 `backend.tf`**** 和 `aft-providers.tf` 文件添加到一个 `.gitignore` 文件中：<pre>echo backend.tf >> .gitignore<br />echo aft-providers.tf >>.gitignore</pre>通过将这些文件移到 `.gitignore`**** 文件中，可确保不会将它们提交并推送回远程 AFT 存储库。 | AWS 管理员 | 
| 提交您的代码更改并将其推送至远程 AFT 存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html)在此之前，您通过执行此过程引入的代码更改 AWS 账户 仅适用于一个代码更改。 | AWS 管理员 | 

### 将更改发布到多个账户
<a name="roll-out-the-changes-to-multiple-accounts"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将更改发布到由 AFT 管理的所有账户。 | 要将更改推广到由 AFT 管理 AWS 账户 的多个项目，请按照文档中 “[重新调用自定义](https://docs.aws.amazon.com/controltower/latest/userguide/aft-account-customization-options.html#aft-re-invoke-customizations)” 中的 AWS Control Tower 说明进行操作。 | AWS 管理员 | 

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

**Topics**
+ [使用只读副本 PeopleSoft 在 Amazon RDS Custom 上将 HA 添加到 Oracle](add-ha-to-oracle-peoplesoft-on-amazon-rds-custom-by-using-a-read-replica.md)
+ [自动审核允许从公有 IP 地址进行访问 AWS 的安全组](audit-security-groups-access-public-ip.md)
+ [使用着陆区域加速器自动创建账户 AWS](automate-account-creation-lza.md)
+ [通过 AWS Systems Manager 自动添加或更新 Windows 注册表项](automate-adding-or-updating-windows-registry-entries-using-aws-systems-manager.md)
+ [自动执行 AWS 资源评测](automate-aws-resource-assessment.md)
+ [使用 AWS CDK 自动部署 AWS Service Catalog 产品组合与产品](automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk.md)
+ [使用 DR Orchestrator Framework 自动执行跨区域故障转移和故障恢复](automate-cross-region-failover-and-failback-by-using-dr-orchestrator-framework.md)
+ [自动删除 AWS CloudFormation 堆栈和相关资源](automate-deletion-cloudformation-stacks-associated-resources.md)
+ [使用 Terraform 在 Amazon Managed Grafana 上自动摄取和可视化 Amazon MWAA 自定义指标](automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.md)
+ [在 Amazon MQ 中自动化 RabbitMQ 配置](automate-rabbitmq-configuration-in-amazon-mq.md)
+ [使用 GitHub Actions、Artifactory 和 Terraform 在多存储库设置中自动部署 AWS Supply Chain 数据湖](automate-the-deployment-of-aws-supply-chain-data-lakes.md)
+ [在跨区域自动复制 Amazon RDS 实例 AWS 账户](automate-the-replication-of-amazon-rds-instances-across-aws-accounts.md)
+ [使用云托管人和 AWS CDK 将适用于 Systems Manager 的 AWS 托管策略自动附加到 EC2 实例配置文件](automatically-attach-an-aws-managed-policy-for-systems-manager-to-ec2-instance-profiles-using-cloud-custodian-and-aws-cdk.md)
+ [使用 AWS CDK 自动为微服务构建 CI/CD 管道和 Amazon ECS 集群](automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.md)
+ [自动检测变化并为 monorepo 启动不同的 CodePipeline 管道 CodeCommit](automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.md)
+ [使用 AWS DataOps 开发套件构建数据管道以提取、转换和分析 Google Analytics 数据](build-a-data-pipeline-to-ingest-transform-and-analyze-google-analytics-data-using-the-aws-dataops-development-kit.md)
+ [使用 Amazon A EC2 uto Scaling 和 Systems Manager 构建 Micro Focus 企业服务器 PAC](build-a-micro-focus-enterprise-server-pac-with-amazon-ec2-auto-scaling-and-systems-manager.md)
+ [使用 GitHub Actions 和 Terraform 构建 Docker 镜像并将其推送到 Amazon ECR](build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform.md)
+ [建造一个包含 MongoDB Atlas 的 AWS 着陆区](build-aws-landing-zone-that-includes-mongodb-atlas.md)
+ [使用 Terraform 在 AWS Organizations 中集中管理 IAM 访问密钥](centralize-iam-access-key-management-in-aws-organizations-by-using-terraform.md)
+ [使用 Terraform 在 AWS Organizations 中集中分发软件包](centralize-software-package-distribution-in-aws-organizations-by-using-terraform.md)
+ [使用在 Amazon Bedrock 中配置模型调用日志 AWS CloudFormation](configure-bedrock-invocation-logging-cloudformation.md)
+ [在 AWS 上的 SQL Server 的“始终打开”可用性组中配置只读路由](configure-read-only-routing-in-an-always-on-availability-group-in-sql-server-on-aws.md)
+ [使用 AWS Amplify、Angular 和模块联合为微前端创建门户](create-amplify-micro-frontend-portal.md)
+ [使用 GitHub Actions 和 Terragrunt 创建由 API 驱动的资源编排框架](create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.md)
+ [在组织中创建跨账户 Amazon EventBridge 连接](create-cross-account-amazon-eventbridge-connection-organization.md)
+ [自动为 Java 和 Python 项目创建动态 CI 管道](create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.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 CDK 和来部署和管理 AWS Control Tower 控件 CloudFormation](deploy-and-manage-aws-control-tower-controls-by-using-aws-cdk-and-aws-cloudformation.md)
+ [使用 Terraform 部署和管理 AWS Control Tower 控件](deploy-and-manage-aws-control-tower-controls-by-using-terraform.md)
+ [使用 Terraf CloudWatch orm 部署 Synthetics 加那利群岛](deploy-cloudwatch-synthetics-canaries-by-using-terraform.md)
+ [使用 Terraform 在亚马逊 EKS 中部署 CockroachDB 集群](deploy-cockroachdb-on-eks-using-terraform.md)
+ [使用 Terraform 和 DRA 部署 Lustre 文件系统以实现高性能数据处理](deploy-lustre-file-system-for-high-performance-data-processing-with-terraform-dra.md)
+ [使用 Terraform 和 Amazon AWS Bedrock 部署 RAG 用例](deploy-rag-use-case-on-aws.md)
+ [使用 Terraform 在 AWS Wavelength 区域中部署资源](deploy-resources-wavelength-zone-using-terraform.md)
+ [使用 Terraform 在亚马逊 EC2 和亚马逊 FSx 上部署 SQL Server 故障转移集群实例](deploy-sql-server-failover-cluster-instances-on-amazon-ec2-and-amazon-fsx.md)
+ [使用 Terraform 为 AWS WAF 解决方案部署安全自动化](deploy-the-security-automations-for-aws-waf-solution-by-using-terraform.md)
+ [检测具有即将过期的 CA 证书的 Amazon RDS 和 Aurora 数据库实例](detect-rds-instances-expiring-certificates.md)
+ [记录 AWS 登录区设计](document-your-aws-landing-zone-design.md)
+ [将 AWS Organizations 中整个组织的 AWS Backup 报告导出为 CSV 文件](export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.md)
+ [使用 Amazon Personalize 生成个性化和重新排名的推荐](generate-personalized-and-re-ranked-recommendations-using-amazon-personalize.md)
+ [使用 Account Factory for Terraform 来管理多个账户的权限集](govern-permission-sets-aft.md)
+ [在 Amazon Data Firehose 资源未使用密钥加密时进行识别并发出警报 AWS KMS](identify-and-alert-when-amazon-data-firehose-resources-are-not-encrypted-with-an-aws-kms-key.md)
+ [使用引导管道实施 Account Factory for Terraform（AFT）](implement-account-factory-for-terraform-aft-by-using-a-bootstrap-pipeline.md)
+ [在 Amazon API Gateway 中使用自定义域实施基于路径的 API 版本控制](implement-path-based-api-versioning-by-using-custom-domains.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)
+ [使用以下 AWS IAM Identity Center 命令将权限集作为代码进行管理 AWS CodePipeline](manage-aws-iam-identity-center-permission-sets-as-code-by-using-aws-codepipeline.md)
+ [使用 Terraform 动态管理 AWS 权限集](manage-aws-permission-sets-dynamically-by-using-terraform.md)
+ [管理多个 Amazon Web Services account 和 AWS 区域中的 AWS Service Catalog 产品](manage-aws-service-catalog-products-in-multiple-aws-accounts-and-aws-regions.md)
+ [通过使用 AWS CDK 设置 Amazon ECS Anywhere 来管理本地容器应用程序](manage-on-premises-container-applications-by-setting-up-amazon-ecs-anywhere-with-the-aws-cdk.md)
+ [使用 AWS CodePipeline 和 Amazon Bedrock 将 AWS Organizations 政策作为代码进行管理](manage-organizations-policies-as-code.md)
+ [将 DNS 记录批量迁移至 Amazon Route 53 私有托管区](migrate-dns-records-in-bulk-to-an-amazon-route-53-private-hosted-zone.md)
+ [将 Oracle 迁移 PeopleSoft 到亚马逊 RDS 定制版](migrate-oracle-peoplesoft-to-amazon-rds-custom.md)
+ [使用 AWS MGN 将 RHEL BYOL 系统迁移至 AWS License-Included 实例](migrate-rhel-byol-systems-to-aws-license-included-instances-by-using-aws-mgn.md)
+ [建立最小可行数据空间以在组织之间共享数据](minimum-viable-data-space-share-data-organizations.md)
+ [监控 Amazon ElastiCache 集群的静态加密](monitor-amazon-elasticache-clusters-for-at-rest-encryption.md)
+ [使用 L CloudWatch ogs Insights 监控应用程序活动](monitor-application-activity-by-using-cloudwatch-logs-insights.md)
+ [使用 AWS 服务监控 SAP RHEL Pacemaker 集群](monitor-sap-rhel-pacemaker-clusters-by-using-aws-services.md)
+ [使用 Terraform 在上 AWS 面创建分层的多区域 IPAM 架构](multi-region-ipam-architecture.md)
+ [使用 AWS CDK 和 GitHub 操作工作流程优化多账户无服务器部署](optimize-multi-account-serverless-deployments.md)
+ [使用 GitHub 操作基于 AWS CloudFormation 模板配置 AWS Service Catalog 产品](provision-aws-service-catalog-products-using-github-actions.md)
+ [通过部署角色自动分配机器解决方案，预调配最低权限 IAM 角色](provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.md)
+ [使用 AWS Lambda 自动化功能 AWS 账户 从 AWS Managed Microsoft AD 正面移除 Amazon EC2 条目](remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.md)
+ [使用 AWS Lambda 自动化功能 AWS 账户 从 AWS Managed Microsoft AD 中移除 Amazon EC2 条目](remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad.md)
+ [使用 Transfer Family、Amazon Cognito 和 GuardDuty](secure-file-transfers.md)
+ [在创建 IAM 用户时发送通知](send-a-notification-when-an-iam-user-is-created.md)
+ [为基于单元的架构设置无服务器单元路由器](serverless-cell-router-architecture.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)
+ [在 Amazon RDS Custom 上为 Oracle 电子商务套件设置 HA/DR 架构，并使用活动备用数据库](set-up-an-ha-dr-architecture-for-oracle-e-business-suite-on-amazon-rds-custom-with-an-active-standby-database.md)
+ [在多账户 AWS 环境中为混合网络设置 DNS 解析](set-up-dns-resolution-for-hybrid-networks-in-a-multi-account-aws-environment.md)
+ [使用 Amazon 为 SQL Server Always On FCI 设置多可用区基础架构 FSx](set-up-multi-az-infrastructure-for-a-sql-server-always-on-fci-by-using-amazon-fsx.md)
+ [在 Aurora PostgreSQL-Compatible 上设置 Oracle UTL\$1FILE 功能](set-up-oracle-utl_file-functionality-on-aurora-postgresql-compatible.md)
+ [使用应用程序负载均衡器简化 Amazon ECS 中双向 TLS 的应用程序身份验证](simplify-application-authentication-with-mutual-tls-in-amazon-ecs.md)
+ [使用 AWS Private CA 和 AWS RAM 简化私有证书管理](simplify-private-certificate-management-by-using-aws-private-ca-and-aws-ram.md)
+ [使用 SageMaker AI 和 Hydra 简化从本地开发到可扩展实验的机器学习工作流程](streamline-machine-learning-workflows-by-using-amazon-sagemaker.md)
+ [使用 AWS Organizations 自动标记中转网关连接](tag-transit-gateway-attachments-automatically-using-aws-organizations.md)
+ [在 Amazon RDS 上为 Oracle PeopleSoft 应用程序过渡角色适用于 Oracle 定制](transition-roles-for-an-oracle-peoplesoft-application-on-amazon-rds-custom-for-oracle.md)
+ [将 Amazon Q 开发者版用作编码助手来提高工作效率](use-q-developer-as-coding-assistant-to-increase-productivity.md)

# Web 应用程序和移动应用程序
<a name="websitesandwebapps-pattern-list"></a>

**Topics**
+ [使用 Amazon Cognito 和 AWS Amplify UI 对现有 React 应用程序用户执行身份验证](authenticate-react-app-users-cognito-amplify-ui.md)
+ [使用 AWS Amplify 创建 React 应用程序，并使用 Amazon Cognito 添加身份验证](create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito.md)
+ [使用 AWS Amplify、Angular 和模块联合为微前端创建门户](create-amplify-micro-frontend-portal.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 Cognito 和 iaC 自动化将 Amazon Quick Sight 视觉组件嵌入到网络应用程序中](embed-quick-sight-visual-components-into-web-apps-cognito-iac.md)
+ [使用 Green Boost 探索全栈云原生 Web 应用程序开发](explore-full-stack-cloud-native-web-application-development-with-green-boost.md)
+ [使用 AWS 对来自 GitHub 的 Node.js 应用程序运行单元测试 CodeBuild](run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild.md)
+ [使用 AWS Lambda 以六边形架构构建 Python 项目](structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.md)
+ [更多模式](websitesandwebapps-more-patterns-pattern-list.md)

# 使用 Amazon Cognito 和 AWS Amplify UI 对现有 React 应用程序用户执行身份验证
<a name="authenticate-react-app-users-cognito-amplify-ui"></a>

*Daniel Kozhemyako，Amazon Web Services*

## Summary
<a name="authenticate-react-app-users-cognito-amplify-ui-summary"></a>

此模式展示了如何使用 AWS Amplify UI 库和 Amazon Cognito 用户池向现有的前端 React 应用程序添加身份验证功能。

此模式使用 Amazon Cognito 为应用程序提供身份验证、授权和用户管理。它还使用 A [mplify UI](https://ui.docs.amplify.aws/react/getting-started/introduction) 中的组件，这是一个开源库，可将的功能扩展 AWS Amplify 到用户界面 (UI) 开发。[Authenticator UI](https://ui.docs.amplify.aws/react/connected-components/authenticator/advanced) 组件管理登录会话，并运行通过 Amazon Cognito 对用户进行身份验证的云连接工作流。

实现此模式后，用户可使用以下任何凭证登录：
+ 用户名和密码
+ 社交身份提供商，例如 Apple、Facebook、Google 和 Amazon
+ SAML 2.0 或 OpenID Connect (OIDC) 兼容的企业身份提供程序

**注意**  
为了创建自定义身份验证 UI 组件，可以在无头模式下运行 Authenticator UI 组件。

## 先决条件和限制
<a name="authenticate-react-app-users-cognito-amplify-ui-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ React 18.2.0 或更高版本的 Web 应用程序
+ Node.js 和 npm 6.14.4 或更高版本，[已安装](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm)

**限制**
+ 此模式仅适用于 React Web 应用程序。
+ 此模式使用预先构建的 Amplify UI 组件。该解决方案不包括实现自定义 UI 组件所需步骤。

**产品版本**
+ Amplify UI 6.1.3 或更高版本（第 1 代）
+ Amplify 6.0.16 或更高版本（第 1 代）

## 架构
<a name="authenticate-react-app-users-cognito-amplify-ui-architecture"></a>

**目标架构**

下图介绍了一种使用 Amazon Cognito 对 React Web 应用程序的用户进行身份验证的架构。

![\[Amazon Cognito 对 React 网络应用程序的用户进行身份验证。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/b2cea053-6931-4404-8aa8-c623ce2024ac/images/b7f69f20-a39d-4a78-8605-7dab73c59052.png)


## 工具
<a name="authenticate-react-app-users-cognito-amplify-ui-tools"></a>

**AWS 服务**
+ [Amazon Cognito](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) 为您的 Web 和移动应用程序提供身份验证、授权和用户管理。

**其他工具**
+ [Amplify UI](https://ui.docs.amplify.aws/react/getting-started/introduction) 是开源用户界面库，提供可自定义的组件，您可以将其连接到云端。
+ [Node.js](https://nodejs.org/en/docs/) 是一个事件驱动的 JavaScript 运行时环境，专为构建可扩展的网络应用程序而设计。
+ [npm](https://docs.npmjs.com/about-npm) 是在 Node.js 环境中运行的软件注册表，用于共享或借用软件包以及管理私有软件包的部署。

## 最佳实践
<a name="authenticate-react-app-users-cognito-amplify-ui-best-practices"></a>

如果正在构建新应用程序，我们建议您使用 Amplify Gen 2。

## 操作说明
<a name="authenticate-react-app-users-cognito-amplify-ui-epics"></a>

### 创建 Amazon Cognito 用户池
<a name="create-an-cog-user-pool"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建用户池。 | [创建 Amazon Cognito 用户池](https://docs.aws.amazon.com/cognito/latest/developerguide/tutorial-create-user-pool.html)。配置用户池的登录选项和安全要求，以适合您的使用案例。 | 应用程序开发人员 | 
| 添加应用程序客户端。 | [配置用户池应用程序客户端](https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-client-apps.html)。您的应用程序需要通过此客户端才能与 Amazon Cognito 用户池进行交互。 | 应用程序开发人员 | 

### 将 Amazon Cognito 用户池与身份验证器用户界面组件集成
<a name="integrate-your-cog-user-pool-with-the-authenticator-ui-component"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装依赖项。 | 要安装 `aws-amplify` 和 `@aws-amplify/ui-react` 软件包，请从应用程序的根目录运行以下命令：<pre>npm i @aws-amplify/ui-react aws-amplify</pre> | 应用程序开发人员 | 
| 配置用户池。 | 根据下面的示例，创建一个 `aws-exports.js` 文件并保存在 `src` 文件夹中。该文件应包含以下信息：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html)<pre>// replace the user pool region, id, and app client id details<br />const awsmobile = {<br />    "aws_project_region": "put_your_region_here",<br />    "aws_cognito_region": "put_your_region_here",<br />    "aws_user_pools_id": "put_your_user_pool_id_here",<br />    "aws_user_pools_web_client_id": "put_your_user_pool_app_id_here"<br />}<br /><br />export default awsmobile;</pre> | 应用程序开发人员 | 
| 导入与配置 Amplify 服务。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html) | 应用程序开发人员 | 
| 添加身份验证器 UI 组件。 | 若要显示 `Authenticator` UI 组件，请在应用程序的入口点文件 (`App.js`) 中添加以下代码行：<pre>import { Authenticator } from '@aws-amplify/ui-react';<br />import '@aws-amplify/ui-react/styles.css';</pre>示例代码片段导入 `Authenticator` UI 组件和 Amplify UI styles.css 文件，这是使用该组件的预构建主题时必需的项。该 `Authenticator` UI 组件提供两个返回值：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html)请参见以下示例组件：<pre>function App() {<br />    return (<br />        <Authenticator><br />            {({ signOut, user }) => (<br />                <div><br />                    <p>Welcome {user.username}</p><br />                    <button onClick={signOut}>Sign out</button><br />                </div><br />            )}<br />        </Authenticator><br />    );<br />}</pre>对于示例 `App.js` 文件，请参阅此模式的[其他信息](#authenticate-react-app-users-cognito-amplify-ui-additional)部分。 | 应用程序开发人员 | 
| （可选）检索会话信息。 | 用户通过身份验证后，您可从 Amplify 客户端检索有关其会话的数据。例如，您可从用户的会话中检索 JSON Web 令牌 (JWT)，这样您就可以对来自其会话的请求进行身份验证，然后再向后端 API 发送请求。参见以下含 JWT 请求标头示例：<pre>import { fetchAuthSession } from 'aws-amplify/auth';<br />(await fetchAuthSession()).tokens?.idToken?.toString();</pre> | 应用程序开发人员 | 

## 问题排查
<a name="authenticate-react-app-users-cognito-amplify-ui-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 新用户无法注册此应用程序。 | 如下所述，确保您的 Amazon Cognito 用户池已配置为允许用户自行注册以加入用户池。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/authenticate-react-app-users-cognito-amplify-ui.html) | 
| 从 v5 升级到 v6 后，身份验证组件停止工作。 | 在 Amplify v6 中，`Auth` 类别已移至功能化方法，并支持命名参数。现在，必须 APIs 直接从`aws-amplify/auth`路径导入函数。有关更多信息，请参阅 Amplify 文档中的[从 v5 迁移到 v6](https://docs.amplify.aws/gen1/react/build-a-backend/auth/auth-migration-guide/)。 | 

## 相关资源
<a name="authenticate-react-app-users-cognito-amplify-ui-resources"></a>
+ [亚马逊 Cognito（AWS 网站）入门](https://aws.amazon.com/cognito/getting-started/)
+ [创建新 React 应用程序](https://reactjs.org/docs/create-a-new-react-app.html)（React 文档）
+ [什么是 Amazon Cognito？](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html) （Amazon Cognito 文档）
+ [Amplify UI 库](https://ui.docs.amplify.aws/)（Amplify 文档）

## 附加信息
<a name="authenticate-react-app-users-cognito-amplify-ui-additional"></a>

该 `App.js` 文件应包含以下代码：

```
import './App.css';
import { Amplify } from 'aws-amplify';
import awsExports from './aws-exports';
import { fetchAuthSession } from 'aws-amplify/auth';
import { Authenticator } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';
Amplify.configure({ ...awsExports });
let token = (await fetchAuthSession()).tokens?.idToken?.toString();
function App() {
  return (
      <Authenticator>
        {({ signOut, user }) => (
            <div>
              <p>Welcome {user.username}</p>
                <p>Your token is: {token}</p>
              <button onClick={signOut}>Sign out</button>
            </div>
        )}
      </Authenticator>
  );
}

export default App;
```

# 使用 AWS Amplify 创建 React 应用程序，并使用 Amazon Cognito 添加身份验证
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito"></a>

*Rishi Singla，Amazon Web Services*

## Summary
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-summary"></a>

此模式演示了如何使用 AWS Amplify 创建基于 React 的应用程序，以及如何使用 Amazon Cognito 为前端添加身份验证。AWS Amplify 由一组工具(开源框架、可视化开发环境、控制台)和服务(网络应用程序和静态网站托管)组成，用于加速 AWS 上移动和网络应用程序的开发。

## 先决条件和限制
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 计算机上已安装 [Node.js](https://nodejs.org/en/download/) 和 [npm](https://www.npmjs.com/get-npm)

**产品版本**
+ Node.js 版本 10.x 或更高版本（要验证您的版本，请在终端窗口中运行 `node -v`）
+ npm 6.x 或更高版本（要验证您的版本，请在终端窗口中运行 `npm -v`）

## 架构
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-architecture"></a>

**目标技术堆栈**
+ AWS Amplify
+ Amazon Cognito

## 工具
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-tools"></a>
+ [Amplify 命令行界面（CLI）](https://docs.amplify.aws/cli/)
+ [Amplify Libraries](https://docs.amplify.aws/lib/q/platform/react-native/)（开源客户端库）
+ [Amplify Studio](https://docs.amplify.aws/console/)（可视化界面）

## 操作说明
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-epics"></a>

### 安装 AWS Amplify CLI
<a name="install-aws-amplify-cli"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装 Amplify CLI | Amplify CLI 是一个统一的工具链，用于为您的 React 应用程序创建 Amazon Web Services Cloud 服务。若要安装 Amplify CLI，请运行：<pre>npm install -g @aws-amplify/cli</pre>如果有新的主要版本可用，npm 将通知您。如果是这样，请使用以下命令升级您的 npm 版本：<pre>npm install -g npm@9.8.0</pre>其中 9.8.0 指的是您要安装的版本。 | 应用程序开发人员 | 

### 创建 React 应用程序
<a name="create-a-react-app"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 React 应用程序。 | 若要创建新的 React 应用程序，请使用命令：<pre>npx create-react-app amplify-react-application</pre>其中 `ampify-react-application` 是应用程序的名称。应用程序创建成功后，您将看到提示信息：<pre>Success! Created amplify-react-application</pre>将为 React 应用程序创建一个包含多个子文件夹的目录。 | 应用程序开发人员 | 
| 在本地计算机上启动应用程序。 | 转到上一步中创建的目录 `amplify-react-application` 并运行以下命令：<pre>amplify-react-application% npm start</pre>这将在您的本地计算机上启动 React 应用程序。 | 应用程序开发人员 | 

### 配置 Amplify CLI
<a name="configure-the-amplify-cli"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 配置 Amplify 以连接到您的 Amazon Web Services account。 | 通过运行以下命令配置 Amplify：<pre>amplify-react-application % amplify configure</pre>Amplify CLI 要求您按照以下步骤设置对您的 Amazon Web Services account 的访问权限：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito.html)此场景需要 IAM 用户具有编程访问权限和长期凭证，这会带来安全风险。为帮助减轻这种风险，我们建议仅向这些用户提供执行任务所需的权限，并在不再需要这些用户时将其移除。必要时可以更新访问密钥。有关更多信息，请参阅 *IAM 用户指南*中的[更新访问密钥](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html#Using_RotateAccessKey)。这些步骤在终端中显示如下。<pre>Follow these steps to set up access to your AWS account:<br />Sign in to your AWS administrator account:<br />https://console.aws.amazon.com/<br />Press Enter to continue<br />Specify the AWS Region<br />? region:  us-east-1<br />Follow the instructions at<br />https://docs.amplify.aws/cli/start/install/#configure-the-amplify-cli<br />to complete the user creation in the AWS console<br />https://console.aws.amazon.com/iamv2/home#/users/create<br />Press Enter to continue<br />Enter the access key of the newly created user:<br />? accessKeyId:  ********************<br />? secretAccessKey:  ****************************************<br />This would update/create the AWS Profile in your local machine<br />? Profile Name:  new<br /><br />Successfully set up the new user.</pre>有关这些步骤的更多信息，请参阅 Amplify 开发人员中心中的[文档](https://docs.amplify.aws/cli/start/install/#configure-the-amplify-cli)。 | 常规 AWS，应用程序开发人员 | 

### 初始化 Amplify
<a name="initialize-amplify"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 初始化 Amplify。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito.html) | 应用程序开发人员，常规 AWS | 

### 向前端添加身份验证
<a name="add-authentication-to-the-frontend"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 添加身份验证 | 您可以使用 `amplify add <category>` 命令添加诸如用户登录或后端 API 之类的功能。在此步骤中，您将使用该命令添加身份验证。Amplify 提供包含 Amazon Cognito、前端库和嵌入式身份验证器 UI 组件的后端身份验证服务。功能包括用户注册、用户登录、多重身份验证、用户注销和无密码登录。您还可以通过与 Amazon、Google 和 Facebook 等联合身份提供商集成来对用户进行身份验证。Amplify 身份验证类别与其他 Amplify 类别（如 API、分析和存储）无缝集成，因此您可以为经过身份验证和未经身份验证的用户定义授权规则。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito.html) | 应用程序开发人员，常规 AWS | 

### 更改 App.js 文件
<a name="change-the-app-js-file"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 更改 App.js 文件。 | 在 `src` 文件夹中，打开并修订 `App.js` 文件。修改后的文件应如下所示：<pre>{  App.Js File after modifications:<br />import React from 'react';<br />import logo from './logo.svg';<br />import './App.css';<br />import { Amplify } from 'aws-amplify';<br />import { withAuthenticator, Button, Heading } from '@aws-amplify/ui-react';<br />import awsconfig from './aws-exports';<br />Amplify.configure(awsconfig);<br />function App({ signOut }) {<br />  return (<br />      <div><br />      <h1>Thankyou for doing verification</h1><br />      <h2>My Content</h2><br />       <button onClick={signOut}>Sign out</button><br />    </div><br />  );<br />}<br />export default withAuthenticator(App);</pre> | 应用程序开发人员 | 
| 导入 React 程序包。 | `App.js` 文件导入了两个 React 程序包。使用命令安装这些程序包：<pre>amplify-react-application1 % npm install --save aws-amplify @aws-amplify/ui-react</pre> | 应用程序开发人员 | 

### 启动 React 应用程序并检查身份验证
<a name="launch-the-react-app-and-check-authentication"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 启动应用程序。 | 在本地计算机上启动 React 应用程序：<pre>amplify-react-application1 % npm start</pre> | 应用程序开发人员，常规 AWS | 
| 检查身份验证。 | 检查应用程序是否提示输入身份验证参数。（在我们的示例中，我们已将电子邮件配置为登录方式。）前端用户界面应提示您输入登录凭证，并提供用于创建账户的选项。您还可以配置 Amplify 构建流程，将后端添加为持续部署工作流的一部分。然而，此模式不涵盖该选项。 | 应用程序开发人员，常规 AWS | 

## 相关资源
<a name="create-a-react-app-by-using-aws-amplify-and-add-authentication-with-amazon-cognito-resources"></a>
+ [入门](https://docs.npmjs.com/getting-started)（npm 文档）
+ [创建独立 Amazon Web Services account](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html)（Amazon Web Services account 管理文档） 
+ [AWS Amplify 文档](https://docs.aws.amazon.com/amplify/latest/userguide/welcome.html)
+ [Amazon Cognito 文档](https://docs.aws.amazon.com/cognito/latest/developerguide/what-is-amazon-cognito.html)

# 使用 AWS Amplify、Angular 和模块联合为微前端创建门户
<a name="create-amplify-micro-frontend-portal"></a>

*Milena Godau 和 Pedro Garcia，Amazon Web Services*

## Summary
<a name="create-amplify-micro-frontend-portal-summary"></a>

通过微前端架构，多个团队能够独立处理前端应用程序的不同部分。每个团队都可以开发、构建和部署前端的某个片段，而不会干扰应用程序的其他部分。从最终用户的角度来看，它似乎就是一个单一的、有凝聚力的应用程序。但是，他们正在与由不同团队发布的多个独立应用程序进行交互。

本文档介绍了如何使用 [AWS Amplify](https://docs.amplify.aws/gen1/angular/)、[Angular](https://angular.dev/overview) 前端框架和 [Module Federation](https://webpack.js.org/concepts/module-federation/) 来创建微前端架构。在此模式中，微前端通过 Shell（或*父*）应用程序在客户端进行组合。Shell 应用程序可充当检索、显示和集成微前端的容器。Shell 应用程序可处理全局路由，以便加载不同的微前端。[@angular-architects/module-federation](https://www.npmjs.com/package/@angular-architects/module-federation) 插件可将 Module Federation 与 Angular 集成。您可以通过使用部署 shell 应用程序和微前端。 AWS Amplify最终用户可通过基于 Web 的门户访问应用程序。

该门户是垂直拆分的。这意味着这些微前端是整个视图或视图组，而不是同一视图的一部分。因此，Shell 应用程序一次只能加载一个微前端。

微前端是以远程模块的形式实施的。Shell 应用程序会延迟加载这些远程模块，因此将微前端初始化推迟到需要时再执行。这种方法通过仅加载必要的模块来优化应用程序性能。这就可以减少初始加载时间，并改善整体用户体验。此外，您可以通过 webpack 配置文件（**webpack.config.js**），跨模块共享常见的依赖项。这种做法可以促进代码重复使用，减少重复并简化捆绑过程。

## 先决条件和限制
<a name="create-amplify-micro-frontend-portal-prereqs"></a>

**先决条件**
+ 活跃的 AWS 账户
+ Node.js and npm，[已安装](https://nodejs.org/en/download/)
+ Amplify CLI，[已安装](https://docs.amplify.aws/gen1/angular/tools/cli/)
+ Angular CLI，[已安装](https://angular.io/cli)
+ 使用@@ [权限](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsamplify.html) AWS Amplify
+ 熟悉 Angular

**产品版本**
+ Angular CLI 版本 13.1.2 或更高版本
+ @angular-architects/module-federation 版本 14.0.1 或更高版本
+ webpack 版本 5.4.0 或更高版本
+ AWS Amplify 第 1 代

**限制**

微前端架构是一种构建具有弹性的可扩展 Web 应用程序的强大方法。但是，在采用这种方法之前，请务必了解以下潜在挑战：
+ **集成** – 与整体式前端相比，其中一个关键挑战是复杂性可能会增加。编排多个微前端、处理它们之间的通信以及管理共享依赖项可能会更加复杂。此外，微前端之间的通信可能会产生性能开销。这种通信会增加延迟并降低性能。这一问题需要通过高效消息收发机制和数据共享策略来解决。
+ **代码重复** – 由于每个微前端都是独立开发的，因此通用功能或共享库可能存在代码重复风险。这可能会增加应用程序的总体大小，并带来维护挑战。
+ **协调和管理** – 跨多个微前端协调开发和部署流程可能具有挑战性。在分布式架构中，确保版本控制一致、管理依赖项以及维护组件之间的兼容性变得更为重要。建立明确的治理、指导原则以及自动测试和部署管道，对于实现无缝协作和交付至关重要。
+ **测试** – 测试微前端架构可能比测试整体式前端更为复杂。它需要付出额外的努力和专门的测试策略来执行跨组件集成测试和 end-to-end测试，并验证跨多个微前端的一致用户体验。

在承诺使用微前端方法之前，我们建议您先查看 “[了解和实现微](https://docs.aws.amazon.com/prescriptive-guidance/latest/micro-frontends-aws/introduction.html)前端”。 AWS

## 架构
<a name="create-amplify-micro-frontend-portal-architecture"></a>

在微前端架构中，每个团队都可独立开发和部署功能。下图显示了多个 DevOps 团队如何协同工作。门户团队开发 Shell 应用程序。Shell 应用程序则可充当容器，它检索、显示和集成其他团队发布的微前端应用程序。 DevOps 您用于发布 AWS Amplify shell 应用程序和微前端应用程序。

![\[将多个微前端发布到 Shell 应用程序，而用户可通过 Web 门户访问该应用程序。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/ddf82a69-bf1b-4ad1-8e60-3dd375699936/images/cf045bf1-11ea-46d9-93cb-3c603122450d.png)


架构图显示了以下工作流程：

1. 门户团队开发和维护 Shell 应用程序。Shell 应用程序编排微前端的集成和渲染，从而构成整个门户。

1. 团队 A 和 B 开发并维护一个或多个集成到门户中的微前端或功能。每个团队都可以独立处理其各自的微前端。

1. 最终用户使用 Amazon Cognito 进行身份验证。

1. 最终用户访问门户，然后加载 Shell 应用程序。当用户导航时，Shell 应用程序会处理路由并检索请求的微前端，加载其捆绑包。

## 工具
<a name="create-amplify-micro-frontend-portal-tools"></a>

**AWS 服务**
+ [AWS Amplify](https://docs.amplify.aws/angular/start/)是一组专门构建的工具和功能，可帮助前端 Web 和移动开发人员快速构建全栈应用程序。 AWS在此模式下，您可以使用 Amplify CLI 来部署 Amplify 微前端应用程序。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一个开源工具，可帮助您 AWS 服务 通过命令行 shell 中的命令进行交互。

**其他工具**
+ [@angular-architects/module-federation](https://github.com/angular-architects/module-federation-plugin) 是可将 Angular 与 Module Federation 集成的插件。
+ [Angular](https://angular.dev/overview) 是一个开源 Web 应用程序框架，用于构建现代、可扩展且可测试的单页应用程序。它采用了基于组件的模块化架构，可促进代码的重复使用和维护。
+ [Node.js](https://nodejs.org/en/docs/) 是一个事件驱动的 JavaScript 运行时环境，专为构建可扩展的网络应用程序而设计。
+ [npm](https://docs.npmjs.com/about-npm) 是在 Node.js 环境中运行的软件注册表，用于共享或借用软件包以及管理私有软件包的部署。
+ [Webpack Module Federation](https://webpack.js.org/concepts/module-federation/) 可帮助您将独立编译和部署的代码（例如微前端或插件）加载到应用程序中。

**代码存储库**

此模式的代码可在[微前端门户中使用 Angular 和 Module Federation 存储库获得。](https://github.com/aws-samples/angular-module-federation-mfe) GitHub 此存储库包含以下两个文件夹：
+ `shell-app`，包含 Shell 应用程序的代码。
+ `feature1-app`，包含一个示例微前端。Shell 应用程序可获取这个微前端并将其显示为门户应用程序中的一个页面。

## 最佳实践
<a name="create-amplify-micro-frontend-portal-best-practices"></a>

微前端架构具有诸多优势，但也会带来复杂性。以下是有助于实现流畅开发、高质量代码和出色用户体验的一些最佳实践：
+ **规划和沟通** – 为了简化协作，请在前期规划、设计和清晰的沟通渠道等方面投入时间和精力。
+ **设计一致性** – 通过使用设计系统、样式指南和组件库，在所有微前端中强制实施一致的视觉风格。这样便能提供连贯的用户体验并加快开发速度。
+ **依赖项管理** – 由于微前端会独立演变发展，因此应采用标准化合同和版本控制策略，以便有效管理依赖项并防止兼容性问题。
+ **微前端架构** – 为了实现独立的开发和部署，每个微前端都应该对封装的功能承担清晰明确的责任。
+ **集成和通信** — 为了促进平稳集成并最大限度地减少冲突，请在微前端（包括 APIs事件和共享数据模型）之间定义明确的合同和通信协议。
+ **测试和质量保证** – 为微前端实施测试自动化和持续集成管道。这样可以提高整体质量，减少手动测试工作，并验证微前端交互之间的功能。
+ **性能优化** –** **持续监控性能指标并跟踪微前端之间的依赖关系。这可以帮助您识别瓶颈并保持最佳的应用程序性能。为此，请使用性能监控和依赖关系分析工具。
+ **开发人员体验** – 注重开发人员体验，提供清晰的文档、工具和示例。这可以帮助您简化开发流程及吸引新的团队成员。

## 操作说明
<a name="create-amplify-micro-frontend-portal-epics"></a>

### 创建 Shell 应用程序
<a name="create-the-shell-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 Shell 应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 安装 插件。 | 在 Angular CLI 中，输入以下命令，以安装 [@angular-architects/module-federation](https://www.npmjs.com/package/@angular-architects/module-federation) 插件：<pre>ng add @angular-architects/module-federation --project shell --port 4200</pre> | 应用程序开发人员 | 
| 将微前端 URL 添加为环境变量。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 定义路由。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 声明 `mfe1` 模块。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 准备微前端的预加载。 | 预加载微前端有助于 webpack 正确协商共享库和程序包。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 调整 HTML 内容。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 

### 创建微前端应用程序
<a name="create-the-micro-frontend-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建微前端。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 安装 插件。 | 输入以下命令，以安装 @angular-architects/module-federation 插件：<pre>ng add @angular-architects/module-federation --project mfe1 --port 5000</pre> | 应用程序开发人员 | 
| 创建模块和组件。 | 输入以下命令，以创建模块和组件并将其导出为远程条目模块：<pre>ng g module mfe1 --routing<br />ng g c mfe1</pre> | 应用程序开发人员 | 
| 设置默认路由路径。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 添加 `mfe1` 路由。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 编辑 **webpack.config.js** 文件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 调整 HTML 内容。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 

### 在本地运行应用程序
<a name="run-the-applications-locally"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 运行 `mfe1` 应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 运行 Shell 应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 

### 重构 Shell 应用程序，以处理微前端加载错误
<a name="refactor-the-shell-application-to-handle-a-micro-frontend-loading-error"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建模块和组件。 | 在 Shell 应用程序的根文件夹中，输入以下命令，以创建错误页面的模块和组件：<pre>ng g module error-page --routing<br />ng g c error-page</pre> | 应用程序开发人员 | 
| 调整 HTML 内容。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 设置默认路由路径。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 创建函数以加载微前端。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 
| 测试错误处理。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 

### 使用以下方法部署应用程序 AWS Amplify
<a name="deploy-the-applications-by-using-amplifylong"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署微前端。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | AWS 应用程序开发人员 DevOps | 
| 部署 Shell 应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员、应用程序所有者 | 
| 启用 CORS。 | 由于 Shell 和微前端应用程序独立托管在不同的域上，因此您必须在微前端启用跨源资源共享（CORS）。这允许 Shell 应用程序加载来自不同源的内容。要启用 CORS，请添加自定义标头。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | AWS 应用程序开发人员 DevOps | 
| 在 Shell 应用程序上创建重写规则。 | Angular 外壳应用程序配置为使用 HTML5 路由。如果用户执行硬刷新，Amplify 会尝试从当前 URL 加载页面。这便会生成 403 错误。为避免这种情况，您可以在 Amplify 控制台中添加一条重写规则。要创建重写规则，请执行以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | AWS 应用程序开发人员 DevOps | 
| 测试 Web 门户。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 应用程序开发人员 | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除应用程序。 | 如果您不再需要 Shell 和微前端应用程序，请将其删除。这有助于防止对您未使用的资源产生费用。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 常规 AWS | 

## 问题排查
<a name="create-amplify-micro-frontend-portal-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 运行`amplify init`命令时没有可用的 AWS 配置文件 | 如果您没有配置 AWS 配置文件，您仍然可以继续执行该`amplify init`命令。但是，当提示您选择身份验证方法时，您需要选择 `AWS access keys` 选项。准备好您的 AWS 访问密钥和私有密钥。或者，您也可以为 AWS CLI配置命名配置文件。有关说明，请参阅 AWS CLI 文档中的[配置和凭据文件设置](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)。 | 
| 加载远程条目时出错 | 如果在 Shell 应用程序的 **main.ts** 文件中加载远程条目时遇到错误，请确认已正确设置 `environment.mfe1URL` 变量。此变量的值应为微前端的 URL。 | 
| 访问微前端时出现 404 错误 | 如果您在尝试访问本地微前端（例如 `http://localhost:4200/mfe1`）时出现 404 错误，请检查以下内容：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-amplify-micro-frontend-portal.html) | 

## 附加信息
<a name="create-amplify-micro-frontend-portal-additional"></a>

**AWS 文档**
+ [在 AWS（AWS 规范性指导）上理解和实现微前端](https://docs.aws.amazon.com/prescriptive-guidance/latest/micro-frontends-aws/introduction.html)
+ [Amplify CLI](https://docs.amplify.aws/gen1/angular/tools/cli/)（Amplify 文档）
+ [Amplify Hosting](https://docs.aws.amazon.com/amplify/latest/userguide/welcome.html)（Amplify 文档）

**其他参考资料**
+ [Module Federation](https://webpack.js.org/concepts/module-federation/)
+ [Node.js](https://nodejs.org/en/)
+ [有角度](https://angular.io/)
+ [@angular-architects/module-federation](https://www.npmjs.com/package/@angular-architects/module-federation)

# 将基于 React 的单页应用程序部署到 Amazon S3 CloudFront
<a name="deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront"></a>

*Jean-Baptiste Guillois，Amazon Web Services*

## Summary
<a name="deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront-summary"></a>

单页应用程序 (SPA) 是一种网站或 Web 应用程序，它使用 JavaScript APIs动态更新所显示网页的内容。这种方法增强了网站的用户体验和性能，因为它仅更新新数据，而不是从服务器重新加载整个网页。

这种模式提供了 step-by-step一种在亚马逊简单存储服务 (Amazon S3) Simple Service 和亚马逊上用 React 编写的 SPA 编码和托管的方法。 CloudFront这种模式中的 SPA 使用在 Amazon API Gateway 中配置并通过亚马逊 CloudFront 分发公开的 REST API 来简化[跨域资源共享 (CORS) 管理](https://docs.aws.amazon.com/AmazonS3/latest/userguide/cors.html)。

## 先决条件和限制
<a name="deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront-prereqs"></a>

**先决条件**
+ 活跃 AWS 账户的.
+ Node.js 和 `npm`，已安装并配置。有关更多信息，请参阅 Node.js 文档的[下载](https://nodejs.org/en/download/)部分。
+ Yarn，已安装和配置。有关更多信息，请参阅 [Yarn 文档](https://classic.yarnpkg.com/lang/en/docs/install/#windows-stable)。
+ Git，已安装和配置。有关更多信息，请参阅 [Git 文档](https://github.com/git-guides/install-git)。

## 架构
<a name="deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront-architecture"></a>

![\[用于将基于 React 的 SPA 部署到 Amazon S3 的架构以及 CloudFront\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/970a9d13-e8a2-44ac-aca5-a066e4be60e8/images/96061e05-8ac8-446e-b1da-baa6fc1cc7b6.png)


此架构是使用 AWS CloudFormation （基础架构即代码）自动部署的。它使用诸如亚马逊 S3 之类的区域服务来存储静态资产，使用 CloudFront 带有 Amazon API Gateway 的亚马逊来公开区域 API (REST) 终端节点。应用程序日志是使用 Amazon 收集的 CloudWatch。所有 AWS API 调用均在中进行审计 AWS CloudTrail。所有安全配置（例如身份和权限）均在 AWS Identity and Access Management (IAM) 中管理。静态内容通过亚马逊 CloudFront 内容分发网络 (CDN) 传送，DNS 查询由亚马逊 Route 53 处理。

## 工具
<a name="deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront-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 账户 进行管理。
+ [Amazon](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) 通过全球数据中心网络交付您的网页内容，从而降低延迟并提高性能，从而 CloudFront加快网络内容的分发。
+ [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 的指标。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 通过控制谁经过身份验证并有权使用 AWS 资源，从而帮助您安全地管理对资源的访问权限。
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/) 是一种可用性高、可扩展性强的 DNS Web 服务。
+ [Amazon Simple Storage Service（Amazon S3）](https://docs.aws.amazon.com/AmazonS3/latest/userguide/)是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。

**代码**

此模式的示例应用程序代码可在 GitHub [基于 React 的 CORS 单页应用程序存储库](https://github.com/aws-samples/react-cors-spa)中找到。

## 最佳实践
<a name="deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront-best-practices"></a>

通过使用 Amazon S3 对象存储，您可以安全、高弹性、高性能且具成本效益的方式存储应用程序的静态资产。无需使用专用容器或 Amazon Elastic Compute Cloud（Amazon EC2）实例即可执行此任务。

通过使用 Amazon CloudFront 内容分发网络，您可以减少用户在访问您的应用程序时可能遇到的延迟。您还可以附加 Web 应用程序防火墙（[AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/cloudfront-features.html)），以保护您的资产免受恶意攻击。

## 操作说明
<a name="deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront-epics"></a>

### 本地构建和部署您的应用程序
<a name="locally-build-and-deploy-your-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 运行以下命令，克隆示例应用程序的存储库：<pre>git clone https://github.com/aws-samples/react-cors-spa react-cors-spa && cd react-cors-spa</pre> | AWS 应用程序开发人员 DevOps | 
| 本地部署应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront.html) | AWS 应用程序开发人员 DevOps | 
|  在本地访问应用程序。 | 打开浏览器窗口并输入访问应用程序的 `http://localhost:3000` URL。 | AWS 应用程序开发人员 DevOps | 

### 部署应用程序
<a name="deploy-the-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 AWS CloudFormation 模板。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront.html) | AWS 应用程序开发人员 DevOps | 
| 自定义应用程序源文件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront.html) | 应用程序开发人员 | 
| 构建应用程序包。 | 在项目目录中，运行 `yarn build` 命令以生成应用程序包。 | 应用程序开发人员 | 
| 部署应用程序包。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront.html) | AWS 应用程序开发人员 DevOps | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 访问和测试应用程序。 | 打开浏览器窗口，然后粘贴 CloudFront 分发域（您之前部署的 CloudFormation 堆栈的`SPADomain`输出）以访问该应用程序。 | AWS 应用程序开发人员 DevOps | 

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 删除 S3 存储桶内容。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront.html) | AWS DevOps，应用程序开发者 | 
| 删除 CloudFormation 堆栈。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront.html) | AWS DevOps，应用程序开发者 | 

## 相关资源
<a name="deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront-resources"></a>

要部署和托管 Web 应用程序，您还可以使用 [AWS Amplify Hosting](https://docs.aws.amazon.com/amplify/latest/userguide/getting-started.html)，它提供了基于 Git 的工作流，用于托管持续部署的全栈无服务器 Web 应用程序。Amplify Hosting是其中的一员 [AWS Amplify](https://docs.aws.amazon.com/amplify/latest/userguide/welcome.html)，它提供了一组专门构建的工具和功能，使前端网络和移动开发人员能够快速轻松地在其上构建全栈应用程序。 AWS

## 附加信息
<a name="deploy-a-react-based-single-page-application-to-amazon-s3-and-cloudfront-additional"></a>

为了处理用户提出的可能生成 403 错误的无效 URLs 请求，在 CloudFront 发行版中配置的自定义错误页面会捕获 403 错误并将其重定向到应用程序入口点 ()。`index.html`

为了简化 CORS 的管理，REST API 通过 CloudFront 发行版公开。

# 使用私有端点和应用程序负载均衡器在内部网站上部署 Amazon API Gateway API
<a name="deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer"></a>

*Saurabh Kothari，Amazon Web Services*

## Summary
<a name="deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer-summary"></a>

此模式向您展示如何在可从本地网络访问的内部网站上部署 Amazon API Gateway API。您将学习使用专有终端节点、Application Load Balancer、AWS PrivateLink 和 Amazon Route 53 设计的架构，为私有 API 创建自定义域名。此架构可防止使用自定义域名和代理服务器帮助在 API 上进行基于域的路由带来的意外后果。例如，如果您在不可路由的子网中部署虚拟私有云（VPC）端点，则您的网络将无法访问 API Gateway。常见的解决方案是使用自定义域名，然后在可路由的子网中部署 API，但是当代理配置将流量 (`execute-api.{region}.vpce.amazonaws.com`) 传递到 AWS Direct Connect 时，这可能会破坏其他内部站点。最后，此模式可以帮助您满足使用无法通过 Internet 访问的私有 API 和自定义域名的组织要求。

## 先决条件和限制
<a name="deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer-prereqs"></a>

**先决条件**
+ 一个有效的 Amazon Web Services account
+ 用于网站和 API 的 Server Name Indication (SNI) 证书
+ 从本地环境到使用 AWS Direct Connect 或 AWS Site-to-Site VPN 设置的 AWS 账户的连接
+ 带有相应域的[私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html)（例如 domain.com），该域从本地网络解析，并将 DNS 查询转发到 Route 53
+ 可从本地网络访问的可路由私有子网

**限制**

有关负载均衡器、规则和其他资源的配额（以前称为限制）的更多信息，请参阅 Elastic Load Balancing 文档中的[应用程序负载均衡器配额](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-limits.html)。

## 架构
<a name="deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer-architecture"></a>

**技术堆栈**
+ Amazon API Gateway
+ Amazon Route 53
+ 应用程序负载均衡器
+ AWS Certificate Manager
+ AWS PrivateLink

**目标架构**

下图显示了如何在 VPC 中部署应用程序负载均衡器，该均衡器根据应用程序负载均衡器侦听器规则将 Web 流量引导到网站目标组或 API Gateway 目标组。API Gateway 目标组是 API Gateway 中 VPC 端点的 IP 地址列表。API Gateway 配置为通过其资源策略将 API 设为私有。该策略拒绝所有不是来自特定 VPC 端点的调用。API 网关中的自定义域名已更新为对 API 及其阶段使用 api.domain.com。添加了应用程序负载均衡器规则，以根据主机名路由流量。

![\[使用应用程序负载均衡器侦听器规则来定向 Web 流量的架构。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/83145062-4535-4ad0-8947-4ea8950cd174/images/12715186-26ea-4123-b9ef-e3105a934ff3.png)


下图显示了如下工作流：

1. 本地网络中的用户尝试访问内部网站。该请求已发送至 ui.domain.com 和 api.domain.com。然后，请求被解析至可路由私有子网的内部应用程序负载均衡器。SSL 在 ui.domain.com 和 api.domain.com 的应用程序负载均衡器处终止。

1. 在应用程序负载均衡器上配置的侦听器规则将检查主机标头。

   a. 如果主机标头为 api.domain.com，则请求将转发到 API Gateway 目标组。应用程序负载均衡器通过端口 443 启动与 API Gateway 的新连接。

   b. 如果主机标头为 ui.domain.com，则请求将转发到网站目标组。

1. 当请求到达 API Gateway 时，API Gateway 中配置的自定义域映射将确定主机名以及要运行的 API。

**自动化和扩展**

可以使用 AWS CloudFormation 或 AWS Cloud Development Kit (AWS CDK) 自动执行此模式中的步骤。要配置 API Gateway 调用的目标组，您必须使用自定义资源来检索 VPC 端点的 IP 地址。API 调用[describe-vpc-endpoints](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-vpc-endpoints.html)并[describe-network-interfaces](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ec2/describe-network-interfaces.html)返回 IP 地址和安全组，这些地址和安全组可用于创建 API 目标 IP 地址组。

## 工具
<a name="deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer-tools"></a>
+ [Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 可帮助您创建、发布、维护、监控和保护任何规模的 RES WebSocket APIs T、HTTP。
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一种可用性高、可扩展性强的 DNS Web 服务。
+ [AWS Certifice 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 PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html) 可帮助您创建从您 VPCs 到 VPC 之外的服务的单向私有连接。

## 操作说明
<a name="deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer-epics"></a>

### 创建 SNI 证书
<a name="create-an-sni-certificate"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建 SNI 证书，并将该证书导入 ACM。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer.html) | 网络管理员 | 

### 在不可路由私有子网中部署 VPC 端点
<a name="deploy-a-vpc-endpoint-in-a-non-routable-private-subnet"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 API Gateway 中创建接口 VPC 端点。 | 要创建接口 VPC 端点，请按照 Amazon Virtual Private Cloud (Amazon VPC) 文档中的[使用接口 VPC 端点访问 Amazon Web Services](https://docs.aws.amazon.com/vpc/latest/privatelink/create-interface-endpoint.html) 中的说明进行操作。 | 云管理员 | 

### 配置应用程序负载均衡器。
<a name="configure-the-application-load-balancer"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为应用程序创建目标组。 | 为应用程序的 UI 资源[创建目标组](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/create-target-group.html)。 | 云管理员 | 
| 为 API Gateway 端点创建目标组。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-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-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer.html) | 云管理员 | 
| 创建侦听器规则。 | 创建[侦听器规则](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-listeners.html#listener-rules)，以执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer.html) | 云管理员 | 

### 配置 Route 53
<a name="configure-route-53"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建私有托管区。 | 为 domain.com [创建私有托管区](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zone-private-creating.html)。 | 云管理员 | 
| 创建域记录。 | 对于以下，[创建 CNAME 记录](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html)：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer.html) | 云管理员 | 

### 在 API Gateway 中创建私有 API 端点
<a name="create-a-private-api-endpoint-in-api-gateway"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建和配置私有 API 端点。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-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-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer.html) | 云管理员 | 

## 相关资源
<a name="deploy-an-amazon-api-gateway-api-on-an-internal-website-using-private-endpoints-and-an-application-load-balancer-resources"></a>
+ [Amazon API Gateway](https://aws.amazon.com/api-gateway/)
+ [Amazon Route 53](https://aws.amazon.com/route53/)
+ [应用程序负载均衡器](https://aws.amazon.com/elasticloadbalancing/application-load-balancer/)
+ [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html)
+ [AWS Certificate Manager](https://aws.amazon.com/certificate-manager/)

# 使用 Amazon Cognito 和 iaC 自动化将 Amazon Quick Sight 视觉组件嵌入到网络应用程序中
<a name="embed-quick-sight-visual-components-into-web-apps-cognito-iac"></a>

*Amazon Web Services 的 Ishita Gupta、Saurabh Singh 和 Srishti Wadhwa*

## Summary
<a name="embed-quick-sight-visual-components-into-web-apps-cognito-iac-summary"></a>

这种模式提供了一种专门的方法，通过使用注册用户嵌入和简化的 Amazon Cognito 身份验证，将 Amazon Quick Sight 视觉组件嵌入到 React 应用程序中。然后通过基础设施即代码 (IaC) 模板部署这些资源。与传统的仪表板嵌入不同，该解决方案隔离了特定的图表和图形，以便直接集成到React应用程序中，从而极大地提高了性能和用户体验。

该架构在 Amazon Cognito 用户管理和 Quick Sight 权限之间建立了高效的身份验证流程：用户通过 Amazon Cognito 进行身份验证，并根据 Quick Sight 中的控制面板共享规则访问其授权的可视化效果。这种简化的方法无需直接访问 Quick Sight 控制台，同时还能保持强大的安全控制。

整个环境通过单一模板进行部署，该 AWS CloudFormation 模板配置了所有必要的基础架构组件，包括：
+ 使用 AWS Lambda 和 Amazon API Gateway 的无服务器后端
+ 通过亚马逊 CloudFront、亚马逊简单存储服务 (Amazon S3) Semple Service 和 AWS WAF
+ 使用 Amazon Cognito 进行身份管理

所有组件均按照安全最佳实践进行配置，包括最低权限 AWS Identity and Access Management (IAM) 策略、 AWS WAF 保护和 end-to-end加密。

该解决方案非常适合希望将安全的交互式分析集成到其应用程序中，同时保持对用户访问权限的精细控制的开发团队和组织。该解决方案使用 AWS 托管服务和自动化来简化嵌入流程、增强安全性并确保可扩展性，以满足不断变化的业务需求。

目标受众和用例：
+ 想要将分析嵌入到 React 应用程序中的@@ **前端开发者**
+ 想要提供按用户或基于角色的数据可@@ **视化的软件即服务 (SaaS) 产品团队**
+ 有兴趣将 AWS 分析集成到自定义门户中的@@ **解决方案架构师**
+ **商业智能 (BI) 开发人员**，他们希望向经过身份验证的用户展示视觉效果而无需完全访问控制面板
+ 想要在内部工具中嵌入交互式 Quick Sight 图表的@@ **企业团队**

## 先决条件和限制
<a name="embed-quick-sight-visual-components-into-web-apps-cognito-iac-prereqs"></a>

**先决条件**

要成功实现此模式，请确保满足以下条件：
+ A@@ **ctiv** e AWS 账户 AWS 账户 — 有权部署 CloudFormation 堆栈和创建 Lambda、API Gateway、Amazon Cognito CloudFront 和 Amazon S3 资源。
+ **Amazon Quick Sight 账户** — 一个活跃的 Quick Sight 账户，其中至少有一个包含视觉效果的控制面板。有关设置说明，请参阅[教程：使用 Amazon Quick 文档中的示例数据创建 Amazon Quick Sight 控制面板](https://docs.aws.amazon.com/quicksuite/latest/userguide/example-analysis.html)。
+ **开发环境**包括：
  + Node.js（版本 16 或更高版本）
  + 安装了 npm 或纱线
  + Vite 作为 React 构建工具
  + React（版本 19.1.1）
+ **仪表板共享** — 仪表板必须在 Quick Sight 中共享，并且实现者必须登录才能访问嵌入式视觉对象或仪表板。

**限制**
+ 此模式使用注册用户嵌入方法，该方法要求实现者拥有有效的 Quick Sight 帐户。
+ 仅限于与实现此模式的经过身份验证的 Quick Sight 用户明确共享的仪表板和视觉对象。如果实现者没有正确的访问权限，则嵌入网址生成将失败，视觉效果将无法加载。
+  CloudFormation 堆栈必须部署在支持 Quick Sight、API Gateway 和 Amazon Cognito AWS 区域 的地方。有关区域可用性，请参阅[按区域划分的AWS 服务](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。

**产品版本**
+ [快速瞄准嵌入 SDK](https://www.npmjs.com/package/amazon-quicksight-embedding-sdk) 版本 2.10.1
+ [React](https://www.npmjs.com/package/react) 版本 19.1.1
+ [Node.js](https://nodejs.org/en/download) 版本 16 或更高版本，以确保与本解决方案中使用的最新 React 和 Vite 版本兼容

## 架构
<a name="embed-quick-sight-visual-components-into-web-apps-cognito-iac-architecture"></a>

**目标架构**

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

![\[将 Quick Sight 视觉效果嵌入 React 应用程序的架构和工作流程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/75ad12b1-caaa-4532-b709-8f3eaf3f9cc0/images/d0905f61-9055-49cf-887d-f46f5ca6c871.png)


在此工作流程中：

1. **用户访问应用程序。**用户使用浏览器打开 React Web 应用程序。请求被路由到 CloudFront 分发，该分发充当应用程序的内容交付网络。

1. **AWS WAF 过滤恶意请求**。 ****在请求到达之前 CloudFront，它就会通过 AWS WAF。 AWS WAF 根据安全规则检查流量并阻止任何恶意或可疑的请求。

1. **亚马逊 S3 提供静态文件**。如果请求是干净的，则使用原始访问控制 (OAC) 从私有 S3 存储桶中 CloudFront 检索静态前端资产（HTML、JS、CSS），然后将其交付给浏览器。

1. **用户登录**。应用程序加载完毕后，用户通过 Amazon Cognito 登录，Amazon Cognito 会对用户进行身份验证并返回安全 JSON 网络令牌 (JWT)，用于授权的 API 访问。

1. **应用程序发出 API 请求**。登录后，React 应用程序对 API Gateway 上的`/get-embed-url`端点进行安全调用，并在请求标头中传递 JWT 令牌进行身份验证。

1. **令牌已通过验证**。API Gateway 使用亚马逊 Cognito 授权机构验证令牌。如果令牌有效，则请求继续执行；否则，请求会被拒绝，并返回 401（未授权）响应。

1. **该请求被定向到 Lambda 进行处理。**然后，经过验证的请求会被转发到后端 Lambda 函数。此函数负责为请求的 Quick Sight 视觉效果生成嵌入网址。

1. **Lambda 从 Quick Sight 生成嵌入网址**。IAM 使用具有适当权限的 IAM 角色调用 Quick Sight `GenerateEmbedUrlForRegisteredUser` API 来生成安全的、用户范围的可视化网址。

1. **Lambda 将嵌入网址返回到 API** Gateway。作为 JSON 响应的一部分，Lambda 将生成的嵌入网址发送回 API Gateway。然后准备好将该响应传送到前端。

1. **嵌入的 URL 将发送到浏览器**。嵌入网址作为 API 响应返回给浏览器。

1. **视觉效果将显示给用户**。 ****React 应用程序接收响应并使用 Quick Sight Embedding SDK 向用户呈现特定的视觉效果。

**自动化和扩展**

后端和前端部署完全自动化 CloudFormation，使用在单个部署中预置所有必需的 AWS 资源，包括 Amazon Cognito、Lambda、API Gateway、A CloudFront mazon S3 AWS WAF、、、、IAM 角色和 CloudWatch 亚马逊。

这种自动化可确保在所有环境中实现一致且可重复的基础架构。所有组件都会自动扩展：Lambda 会根据函数调用进行调整，在全球范围内 CloudFront 提供缓存内容，API Gateway 可根据传入的请求进行扩展。

## 工具
<a name="embed-quick-sight-visual-components-into-web-apps-cognito-iac-tools"></a>

**AWS 服务**
+ [Amazon Quick Sight](https://aws.amazon.com/quicksuite/quicksight/) 是一项云原生商业智能服务，可帮助您创建、管理和嵌入交互式仪表板和视觉对象。
+ [Amazon API Gateway](https://aws.amazon.com/api-gateway/) 管理着它 APIs 充当 React 应用程序和后端服务之间的桥梁。
+ [AWS Lambda](https://aws.amazon.com/lambda/)是一种无服务器计算服务，这种模式使用它来生成安全的 Quick Sight URLs 动态嵌入，并根据请求自动扩展。
+ [Amazon Cognito](https://aws.amazon.com/cognito/) 为用户提供身份验证和授权，并为 API 访问颁发安全令牌。
+ [Amazon S3](https://aws.amazon.com/s3/) 托管这种模式的静态前端资产，并通过 CloudFront安全的方式为它们提供服务。
+ [Amazon](https://aws.amazon.com/cloudfront/getting-started/) 以低延迟在全球范围内 CloudFront 提供前端内容，并与之集成 AWS WAF 以进行流量过滤。
+ [AWS WAF](https://aws.amazon.com/waf/)通过应用安全规则和速率限制来保护 Web 应用程序免受恶意流量的侵害。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)可在单个部署中自动配置和配置所有应用程序资源。
+ [亚马逊](https://aws.amazon.com/cloudwatch/)从 Lambda、API Gateway CloudWatch 收集日志和指标， AWS WAF 用于监控和故障排除。

**开发工具**
+ [React JS](https://react.dev/) 是一个前端框架，这种模式使用它来构建 Web 应用程序和集成嵌入式 Quick Sight 视觉效果。
+ [Vite](https://vite.dev/) 是一种构建工具，用于快速开发和优化 React 应用程序的生产构建。
+ Qu@@ [ick Sight Embedding SDK](https://www.npmjs.com/package/amazon-quicksight-embedding-sdk/v/2.10.1) 有助于将 Quick Sight 视觉效果嵌入 React 应用程序，并实现应用程序和视觉效果之间的无缝交互。

**代码存储库**

此模式的代码可在 [React 存储库中的 GitHub Amazon Quick Sight Visual Embedding 中](https://github.com/aws-samples/sample-quicksight-visual-embedding)找到。

## 最佳实践
<a name="embed-quick-sight-visual-components-into-web-apps-cognito-iac-best-practices"></a>

此模式会自动实现以下安全最佳实践：
+ 使用 Amazon Cognito 用户池进行基于 JWT 的身份验证，以及可选的多因素身份验证 (MFA)。
+  APIs 使用 Amazon Cognito 授权机构进行保护，并在所有服务中强制执行最低权限 IAM 政策。
+ 实现 Quick Sight 注册用户嵌入，并自动为用户配置读者角色。
+ 通过 CloudFront 和 HTTPS 强制执行支持 TLS 1.2 及更高版本的传输中加密。
+ 使用带版本控制和 OAC 的 Amazon S3 的 AES-256 对静态数据进行加密。
+ 使用限制和配额配置 API Gateway 使用计划。
+ 使用预留并发性和环境变量保护来保护 Lambda。
+ 启用 Amazon S3 CloudFront、Lambda 和 API Gateway 的日志记录；使用监控服务。 CloudWatch
+ 加密日志、应用访问控制，并对非 HTTPS 或未加密的上传强制执行拒绝策略。

此外，我们建议采取以下措施：
+  CloudFormation 用于自动化部署并在不同环境中保持一致的配置。
+ 确保每个用户都具有访问嵌入式视觉效果的正确的 Quick Sight 权限。
+ 使用 Amazon Cognito 授权者保护 API Gateway 终端节点，并对所有 IAM 角色强制执行最低权限原则。
+ 将诸如 Amazon 资源名称 (ARNs) 和环境变量之类的敏感信息存储 IDs 在环境变量中，而不是对其进行硬编码。
+ 通过减少依赖关系和提高冷启动性能来优化 Lambda 函数。有关更多信息，请参阅 AWS 博客文章 “[优化 AWS Lambda 使用高级启动策略的冷启动性能](https://aws.amazon.com/blogs/compute/optimizing-cold-start-performance-of-aws-lambda-using-advanced-priming-strategies-with-snapstart/)”。 SnapStart
+ 将您的 CloudFront 域名添加到 Quick Sight 许可名单，以启用安全的视觉嵌入。
+ 使用和进行日志、警 AWS WAF 报 CloudWatch 和流量保护来监控性能和安全性。

**其他推荐的最佳做法**
+ 使用带有 SSL 证书的自定义域名， AWS Certificate Manager 以提供安全和品牌化的用户体验。
+ 使用客户托管 AWS Key Management Service (AWS KMS) 密钥加密 Amazon S3 数据和 CloudWatch 日志，以便更好地控制加密。
+ 使用地理封锁、SQL 注入 (SQLi)、跨站脚本 (XSS) 保护和自定义过滤器来扩展 AWS WAF 规则，以增强威胁防御。
+ 启用 CloudWatch 警报 AWS Config、和， AWS CloudTrail 以实现实时监控、审计和配置合规性。
+ 应用精细的 IAM 策略，强制执行 API 密钥轮换，并仅在绝对必要时才允许跨账户访问。
+ 定期进行安全评估，确保与合规框架保持一致，例如系统和组织控制2 (SOC 2)、《通用数据保护条例》(GDPR) 和《健康保险流通与责任法案》(HIPAA)。

## 操作说明
<a name="embed-quick-sight-visual-components-into-web-apps-cognito-iac-epics"></a>

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


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 克隆存储库。 | 将此解决方案的 GitHub 存储库克隆到您的本地系统并导航到项目目录：<pre>git clone https://github.com/aws-samples/sample-quicksight-visual-embedding.git<br /><br />cd sample-quicksight-visual-embedding</pre>该存储库包含部署解决方案所需的 CloudFormation 模板和 React 源代码。 | 应用程序开发人员 | 

### 部署堆 CloudFormation 栈
<a name="deploy-the-cfn-stack"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 部署 模板。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html) 有关更多信息，请参阅 CloudFormation 文档中的[创建和管理堆栈](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacks.html)。 | AWS 管理员 | 
| 监控堆栈创建。 | 在 “**事件**” 选项卡中监控堆栈，直到其状态为 **CREATE\$1** COMPLETE。 | AWS 管理员 | 
| 检索堆栈输出。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html) | AWS 管理员 | 

### 配置前端环境
<a name="configure-the-frontend-environment"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 检索快速视觉标识符。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html) | 快速瞄准管理员 | 
| 配置你的本地 React 环境。 | 要设置本地 React 环境并将其链接到 AWS 资源，请在本地 GitHub 存储库的`my-app/`文件夹中创建一个`.env`文件。在文件中填充以下内容：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html)以下是一个示例`.env`文件：<pre>VITE_AWS_REGION=us-east-1<br /><br /># Cognito Configuration (from CloudFormation outputs)<br />VITE_USER_POOL_ID=us-east-1_xxxxxxxxx VITE_USER_POOL_WEB_CLIENT_ID=xxxxxxxxxxxxxxxxxxxxxxxxxx<br /><br /># API Configuration (from CloudFormation outputs)<br />VITE_API_URL=https:/your-api-id.execute-api.us-east-1.amazonaws.com/prod<br /><br /># QuickSight Visual Configuration<br />VITE_DASHBOARD_ID=your-dashboard-id <br />VITE_SHEET_ID=your-sheet-id <br />VITE_VISUAL_ID=your-visual-id</pre> | 应用程序开发人员 | 

### 设置用户身份验证
<a name="set-up-user-authentication"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 在 Cognito 中创建或管理用户 | 要允许经过身份验证的用户访问嵌入式 Quick Sight 视觉对象，您需要先在 Amazon Cognito 中创建用户：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html) | AWS 管理员 | 
| 提供快速查看仪表板访问权限 | 要提供对 Quick Sight 视觉效果的访问权限，请向经过身份验证的用户提供查看者权限访问权限：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html)每位用户都将收到一封包含仪表板链接的电子邮件。您可以随时通过 “**共享**” 菜单修改权限。有关更多信息，请参阅 [Amazon Quick Sight 文档中的授予个人 Amazon Quick Sight 用户和群组访问 Amazon Quick Sight 中控制面板](https://docs.aws.amazon.com/quicksuite/latest/userguide/share-a-dashboard-grant-access-users.html)的权限。 | 快速瞄准管理员 | 

### 构建和部署 React 前端
<a name="build-and-deploy-the-react-frontend"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装依赖关系并生成项目。 | 在 React 应用程序目录中，运行以下命令以生成经过优化的生产文件：<pre>cd my-app<br />npm install<br />npm run build</pre> | 应用程序开发人员 | 
| 将构建文件上传到 Amazon S3。 | 将`my-app/dist/`目录中的所有文件上传到由配置的 S3 存储桶 CloudFormation （不要上传文件夹本身）。 | 应用程序开发人员 | 
| 创建 CloudFront 失效。 | 在[CloudFront 控制台](https://console.aws.amazon.com/cloudfront/v4/home)上，为部署后刷新缓存内容`/*`的路径创建失效。有关说明，请参阅 CloudFront 文档中的[使文件失效](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation_Requests.html)。 | AWS 管理员 | 

### 配置 Quick Sight 许可名单
<a name="configure-the-qsight-allowlist"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将该 CloudFront 域名添加到 Quick Sight 许可名单。 | 要使您的 CloudFront 域能够安全地嵌入 Quick Sight 视觉效果，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html) | 快速瞄准管理员 | 

### 访问应用程序并验证功能
<a name="access-the-application-and-verify-functionality"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 打开 React 应用程序。 | 使用**CloudFront 域**（来自 CloudFormation 输出）在浏览器中打开已部署的 React Web 应用程序。 | 应用程序所有者 | 
| 验证身份验证。 | 使用 Amazon Cognito 凭证登录应用程序，通过 API Gateway 验证身份验证流程和 JWT 验证。 | 应用程序所有者 | 
| 验证嵌入式视觉效果。 | 确认 Quick Sight 视觉效果是否基于用户特定的访问权限在应用程序中正确加载。 | 应用程序所有者 | 
| 验证 API 和 Lambda 的连接。 | 确认应用程序可以成功调用 `/get-embed-url` API 并检索有效的 Quick Sight 嵌入内容 URLs 而不会出现错误。 | 应用程序所有者 | 

### 监控和维护应用程序
<a name="monitor-and-maintain-the-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用监控 CloudWatch。 | 您可以使用可 AWS 观察性工具来监控应用程序，并在生产中保持安全、可扩展的性能。查看 Lambda 日志、API Gateway 指标和 Amazon Cognito 身份验证事件 CloudWatch ，以确保应用程序运行状况并检测异常情况。 | AWS 管理员 | 
| 跟踪 AWS WAF 和 CloudFront 记录。 | 检查 AWS WAF 日志中是否有被阻止或可疑的请求，并检查 CloudFront 访问日志以了解性能和缓存指标。 | AWS 管理员 | 

## 问题排查
<a name="embed-quick-sight-visual-components-into-web-apps-cognito-iac-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| “域名不允许” 错误 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html) | 
| 身份验证错误 | 可能的原因：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html)解决方案：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html) | 
| API Gateway 错误 | 可能的原因：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html)解决方案：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html) | 
| Quick Sight 视觉效果无法加载 | 可能的原因：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html)解决方案：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html) | 
| “用户无权访问” 错误 | 可能的原因：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html)解决方案：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/embed-quick-sight-visual-components-into-web-apps-cognito-iac.html) | 

## 相关资源
<a name="embed-quick-sight-visual-components-into-web-apps-cognito-iac-resources"></a>

** AWS 文档**
+ [注册 Amazon Quick 订阅](https://docs.aws.amazon.com/quicksight/latest/user/signing-up.html)
+ [亚马逊 Quick Sight 的嵌入式分析](https://docs.aws.amazon.com/quicksuite/latest/userguide/embedded-analytics.html)
+ [快速瞄准 API 参考 — GenerateEmbedUrlForRegisteredUser](https://docs.aws.amazon.com/quicksight/latest/APIReference/API_GenerateEmbedUrlForRegisteredUser.html)
+ [Amazon Cognito 用户群体](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools.html)
+ [AWS Lambda 开发人员指南](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html)
+ [亚马逊 API Gateway 开发者指南](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html)
+ [基本监控和详细监控 CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch-metrics-basic-detailed.html)
+ [AWS CloudFormation 用户指南](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)
+ [亚马逊 CloudFront 开发者指南](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html)
+ [AWS WAF 开发人员指南](https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html)

**教程和视频**
+ [亚马逊 Quick Sight 的嵌入式分析](https://docs.aws.amazon.com/quicksight/latest/user/embedded-analytics.html)
+ [Amazon 快速瞄准 YouTube 教程](https://www.youtube.com/results?search_query=amazon+quicksight+embedding)

# 使用 Green Boost 探索全栈云原生 Web 应用程序开发
<a name="explore-full-stack-cloud-native-web-application-development-with-green-boost"></a>

*Ben Stickley 和 Amiin Samatar，Amazon Web Services*

## Summary
<a name="explore-full-stack-cloud-native-web-application-development-with-green-boost-summary"></a>

为了应对开发人员不断变化的需求，Amazon Web Services (AWS) 意识到开发云原生 Web 应用程序的高效方法的迫切需求。AWS 的重点是帮助您克服与在 AWS Cloud上部署 Web 应用程序相关的常见障碍。通过利用 TypeScript AWS Cloud Development Kit (AWS CDK)、React 和 Node.js 等现代技术的功能，这种模式旨在简化和加快开发流程。

在 Green Boost (GB) 工具包的支持下，该模式提供了构建充分利用 AWS 广泛功能的 Web 应用程序的实用指南。它是一份全面的路线图，引导您完成与 Amazon Aurora PostgreSQL 兼容版本集成的基本 CRUD（创建、读取、更新、删除）网络应用程序的部署过程。这是通过使用 Green Boost 命令行界面 (Green Boost CLI) 和建立本地开发环境来实现的。

成功部署应用程序后，该模式深入研究 Web 应用程序的关键组件，包括基础设施设计、后端和前端开发，以及用于可视化的 cdk-dia 等基本工具，从而促进高效的项目管理。

## 先决条件和限制
<a name="explore-full-stack-cloud-native-web-application-development-with-green-boost-prereqs"></a>

**先决条件**
+ [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 已安装
+ [Visual Studio 代码（VS 代码）](https://code.visualstudio.com/download)已安装 
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)已安装
+ 已安装 [AWS CDK Toolkit](https://docs.aws.amazon.com/cdk/v2/guide/cli.html)
+ [Node.js 18](https://nodejs.org/en/download) 已安装，或者已激活[带 pnpm 的 Node.js 18](https://pnpm.io/cli/env)
+ [pnpm](https://pnpm.io/installation) 已安装，前提是它不是 Node.js 安装的一部分
+ 对 AWS CDK TypeScript、Node.js 和 React 有基本的熟悉程度
+ 一个[有效的 Amazon Web Services account](https://docs.aws.amazon.com/accounts/latest/reference/manage-acct-creating.html)
+ 通过在 `us-east-1` 中使用 AWS CDK [引导的 Amazon Web Services account](https://docs.aws.amazon.com/cdk/v2/guide/bootstrapping.html)。`us-east-1`AWS 区域****是支持 Amazon CloudFront Lambda @Edge 功能所必需的。
+ 在终端环境中正确配置的 [AWS 安全凭证](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html)，包括 `AWS_ACCESS_KEY_ID`
+ 对于 Windows 用户，管理员模式下的终端（以适应 pnpm 处理节点模块的方式）

**产品版本**
+ 适用于 JavaScript 版本 3 的 AWS 开发工具包
+ AWS CDK 版本 2
+ AWS CLI 版本 2.2
+ Node.js 版本 18
+ React 版本 18

## 架构
<a name="explore-full-stack-cloud-native-web-application-development-with-green-boost-architecture"></a>

**目标技术堆栈**
+ Amazon Aurora PostgreSQL 兼容版
+ Amazon CloudFront
+ Amazon CloudWatch
+ 亚马逊弹性计算云（亚马逊 EC2）
+ AWS Lambda
+ AWS Secrets Manager
+ Amazon Simple Notification Service(Amazon SNS)
+ Amazon Simple Storage Service(Amazon S3)
+ AWS WAF

**目标架构**

下图显示了用户请求在与 S3 存储桶、Aurora 数据库 CloudFront、实例进行交互并最终到达开发人员之前，先通过亚马逊、AWS WAF 和 AWS Lambda 传递。 EC2 另一方面，管理员则使用 Amazon SNS 和 Amazon CloudWatch 进行通知和监控。

![\[使用 Green Boost CLI 部署与 Amazon Aurora PostgreSQL 集成的 CRUD Web 应用程序的过程。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/bacafc47-07c0-494b-8bbf-24bdc9b54f6a/images/129691e9-7fd3-4208-ab8c-05b9f40a5c4c.png)


要在部署后更深入地了解应用程序，可以使用 [cdk-dia](https://github.com/pistazie/cdk-dia) 创建图表，如以下示例所示。

![\[第一张图显示了以用户为中心的视图；cdk-dia 图显示了技术基础设施视图。\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/bacafc47-07c0-494b-8bbf-24bdc9b54f6a/images/5e4c3321-47bd-44e7-bf14-f470eed984c1.png)


这些图表从两个不同的角度展示 Web 应用程序架构。cdk-dia 图表提供了 AWS CDK 基础设施的详细技术视图，重点介绍了特定的 Amazon Web Services，例如 Amazon Aurora PostgreSQL-Compatible 和 AWS Lambda。相比之下，另一个图采用了更广泛的视角，强调数据和用户交互的逻辑流。主要区别在于详细程度：cdk-dia 深入研究了技术的复杂性，而第一个图提供了更加以用户为中心的视图。

操作说明*使用 AWS CDK 了解应用程序基础设施*中介绍了 cdk-dia 图的创建。

## 工具
<a name="explore-full-stack-cloud-native-web-application-development-with-green-boost-tools"></a>

**Amazon Web Services**
+ [Amazon Aurora PostgreSQL 兼容版](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/Aurora.AuroraPostgreSQL.html)是一个完全托管的、与 ACID 兼容的关系数据库引擎，可帮助您建立、运行和扩缩 PostgreSQL 部署。
+ [AWS Cloud Development Kit (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一个软件开发框架，可帮助您在代码中定义并预置 Amazon Web Services Cloud 基础设施。
+ [AWS 命令行界面（AWS CLI）](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)是一种开源工具，它可帮助您通过命令行 Shell 中的命令与 Amazon Web Services 交互。
+ [Amazon](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) 通过全球数据中心网络交付您的网页内容，从而降低延迟并提高性能，从而 CloudFront加快网络内容的分发。
+ [Amazon CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html) 可帮助您实时监控您的 AWS 资源和在 AWS 上运行的应用程序的指标。
+ [亚马逊弹性计算云 (Amazon EC2)](https://docs.aws.amazon.com/ec2/) 在 AWS 云中提供可扩展的计算容量。您可以根据需要启动任意数量的虚拟服务器，并快速纵向扩展或缩减这些服务器。
+ [AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 是一项计算服务，可帮助您运行代码，而无需预置或管理服务器。它仅在需要时运行您的代码，并且能自动扩缩，因此您只需为使用的计算时间付费。
+ [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) 帮助您将代码中的硬编码凭证（包括密码）替换为对 Secrets Manager 的 API 调用，以便以编程方式检索密钥。
+ [AWS Systems Manager](https://docs.aws.amazon.com/systems-manager/latest/userguide/what-is-systems-manager.html) 可帮助您管理在 Amazon Web Services Cloud 中运行的应用程序和基础设施。它简化了应用程序和资源管理，缩短了检测和解决操作问题的时间，并帮助您大规模安全地管理 AWS 资源。此模式使用 AWS Systems Manager 会话管理器。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一项基于云的对象存储服务，可帮助您存储、保护和检索任意数量的数据。[Amazon Simple Notification Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可帮助您协调和管理发布者与客户端（包括 Web 服务器和电子邮件地址）之间的消息交换。
+ [AWS WAF](https://docs.aws.amazon.com/waf/latest/developerguide/what-is-aws-waf.html) 是一种 Web 应用程序防火墙，可帮助您监视转发至受保护 Web 应用程序资源的 HTTP 和 HTTPS 请求。

**其他工具**
+ [Git](https://git-scm.com/docs) 是开源分布式版本控制系统。
+ [Green Boost](https://awslabs.github.io/green-boost/overview/intro) 是用于在 AWS 上构建网络应用程序的工具包。
+ [Next.js](https://nextjs.org/docs) 是用于添加功能和优化的 React 框架。
+ [Node.js](https://nodejs.org/en/docs/) 是一个事件驱动的 JavaScript 运行时环境，专为构建可扩展的网络应用程序而设计。
+ [pgAdmin](https://www.pgadmin.org/) 是一种适用于 PostgreSQL 的开源管理工具。它提供了一个图形界面，可帮助您创建、维护和使用数据库对象。
+ [pnpm](https://pnpm.io/motivation) 是 Node.js 项目依赖项的包管理器。

## 最佳实践
<a name="explore-full-stack-cloud-native-web-application-development-with-green-boost-best-practices"></a>

有关以下建议的更多信息，请参阅[操作说明](#explore-full-stack-cloud-native-web-application-development-with-green-boost-epics)部分：
+ 使用 Amazon CloudWatch 控制面板和警报监控基础设施。
+ 使用 cdk-nag 运行静态基础设施即代码（IaC）分析，以执行 AWS 最佳实践。
+ 使用 Systems Manager 会话管理器通过SSH (Secure Shell) 隧道建立数据库端口转发，这比公开的 IP 地址更安全。
+ 通过运行 `pnpm audit` 来管理漏洞。
+ 使用执行静态 TypeScript 代码分析 [ESLint](https://eslint.org/)，使用 Pr [ettier](https://prettier.io/) 来标准化代码格式，从而强制执行最佳实践。

## 操作说明
<a name="explore-full-stack-cloud-native-web-application-development-with-green-boost-epics"></a>

### 部署与 Aurora PostgreSQL 兼容的 CRUD Web 应用程序
<a name="deploy-a-crud-web-app-with-aurora-postgresql-compatible"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 安装 Green Boost CLI。 | 要安装 Green Boost CLI，请运行以下命令。<pre>pnpm add -g gboost</pre> | 应用程序开发人员 | 
| 创建 GB 应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 
| 安装依赖项并部署应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html)等待部署完成(大约 20 分钟)。在等待期间，请在 CloudFormation 控制台中监控 AWS CloudFormation 堆栈。请注意代码中定义的构造如何映射至部署的资源。在 CloudFormation 控制台中查看 [CDK 构造树视图](https://docs.aws.amazon.com/cdk/v2/guide/constructs.html)。 | 应用程序开发人员 | 
| 访问该应用程序。 | 在本地部署 GB 应用程序后，您可以使用 CloudFront URL 对其进行访问。URL 打印终端输出中，但查找起来可能有点让人不知所措。若要更快地找到它，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html)或者，您可以通过访问 Amazon CloudFront 控制台来找到 CloudFront URL：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html)复制与分配关联的**域名**。这与 `your-unique-id.cloudfront.net` 类似。 | 应用程序开发人员 | 

### 使用 Amazon 进行监控 CloudWatch
<a name="monitor-by-using-amazon-cloudwatch"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看 CloudWatch 控制面板。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 
| 启用警报。 |  CloudWatch 控制面板可帮助您主动监控您的 Web 应用程序。若要被动监控您的 Web 应用程序，您可以启用警报。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 

### 通过 AWS CDK 了解应用程序基础设施
<a name="understand-the-app-infrastructure-by-using-aws-cdk"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建架构图。 | 使用 [cdk-dia](https://github.com/pistazie/cdk-dia) 生成 Web 应用程序的架构图。可视化架构有助于增进团队成员之间的理解与沟通。它清晰地概述系统的组件及其关系。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 
| 使用 cdk-nag 强制执行最佳实践。 | 使用 [cdk-nag](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/check-aws-cdk-applications-or-cloudformation-templates-for-best-practices-by-using-cdk-nag-rule-packs.html) 通过实施最佳实践，降低安全漏洞和配置错误的风险，以帮助您维护安全和合规的基础设施。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 

### 评估数据库配置与架构
<a name="evaluate-the-database-configuration-and-schema"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 获取环境变量。 | 若要获取所需环境变量，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 
| 创建端口转发。 | 若要创建端口转发，请使用以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 
| 调整 Systems Manager 会话管理器超时。 | （可选）如果默认 20 分钟的会话超时时间太短，则可以在 Systems Manager 控制台中选择 **Session Manager**、**偏好**、**编辑**、**空闲会话超时**，将其延长至 60 分钟。 | 应用程序开发人员 | 
| 可视化数据库。 | pgadmin 是一款用户友好开源工具，用于管理 PostgreSQL 数据库。它简化了数据库任务，使您可高效地创建、管理和优化数据库。本节将指导您 [安装 pgadmin](https://www.pgadmin.org/download/) 并使用其功能进行 PostgreSQL 数据库管理。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 

### 使用 Node.js 调试
<a name="debug-with-node-js"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 调试创建项目用例。 | 若要调试创建项目用例，请执行以下步骤：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html)[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 

### 开发前端
<a name="develop-the-frontend"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置开发服务器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 

### 含绿色增强功能的工具
<a name="tooling-with-green-boost"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 设置 monorepo 与 pnpm 包管理器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 
| 运行 pnpm 脚本。 | 在存储库的根目录中运行以下命令：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html)请注意这些命令如何在所有工作区中运行。这些命令是在每个工作空间的 `package.json#scripts` 字段中定义的。 | 应用程序开发人员 | 
|  ESLint 用于静态代码分析。 | 要测试的静态代码分析能力 ESLint，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 
| 管理依赖项和漏洞。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 
| 使用 Husky 预先提交挂钩。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html)这些工具是帮助防止不良代码进入您的应用程序的机制。 | 应用程序开发人员 | 

### 拆除基础设施
<a name="tear-down-the-infrastructure"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 从您的账户中移除部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/explore-full-stack-cloud-native-web-application-development-with-green-boost.html) | 应用程序开发人员 | 

## 问题排查
<a name="explore-full-stack-cloud-native-web-application-development-with-green-boost-troubleshooting"></a>


| 问题 | 解决方案 | 
| --- | --- | 
| 无法建立端口转发 | 确保您的 AWS 凭证配置正确并具有必要的权限。仔细检查堡垒主机 ID (`DB_BASTION_ID`) 与数据库端点 (`DB_ENDPOINT`) 环境变量是否设置正确。如果您仍然遇到问题，请参阅 AWS 文档以[排除 SSH 连接和会话管理器](https://docs.aws.amazon.com/systems-manager/latest/userguide/session-manager-getting-started-enable-ssh-connections.html)。 | 
| `localhost:3000` 网站未加载  | 确认终端输出显示端口转发成功，包含转发地址。确保本地计算机上没有使用端口 3000 的冲突进程。验证 Green Boost 应用程序是否已正确配置并在预期端口 (3000) 上运行。检查您的 Web 浏览器是否有任何可能阻止本地连接的安全扩展或设置。 | 
| 本地部署期间的错误消息 (`pnpm deploy:local`) | 仔细查看错误消息，以确定问题的原因。验证必要的环境变量以及配置文件是否设置正确。 | 

## 相关资源
<a name="explore-full-stack-cloud-native-web-application-development-with-green-boost-resources"></a>
+ [AWS CDK 文档](https://docs.aws.amazon.com/cdk/latest/guide/home.html)
+ [Green Boost 文档](https://awslabs.github.io/green-boost/learn/m1-deploy-gb-app)
+ [Next.js 文档](https://nextjs.org/docs)
+ [Node.js 文档](https://nodejs.org/en/docs/)
+ [React 文档](https://reactjs.org/docs/getting-started.html)
+ [TypeScript 文档](https://www.typescriptlang.org/docs/)

 

# 使用 AWS 对来自 GitHub 的 Node.js 应用程序运行单元测试 CodeBuild
<a name="run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild"></a>

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

## Summary
<a name="run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild-summary"></a>

此模式为 Node.js 游戏 API 提供了示例源代码和关键单元测试组件。它还包括使用 AWS 从 GitHub 存储库运行这些单元测试的说明 CodeBuild，这是持续集成和持续交付 (CI/CD) 工作流程的一部分。

单元测试是一个软件开发过程，在这个过程中，对应用程序的不同部分（称为*单元*）进行单独和独立的测试，以确保其正确运行。测试验证代码的质量并确认其功能是否符合预期。其他开发人员也可以通过查阅测试轻松熟悉您的代码库。单元测试可缩短未来的重构时间，帮助工程师更快地掌握代码库，并让他们对预期行为充满信心。

单元测试涉及测试单个函数，包括 AWS Lambda 函数。要创建单元测试，您需要一个测试框架和一种验证测试（断言）的方法。此模式中的代码示例使用 [Mocha](https://mochajs.org/) 测试框架和 [Chai 断言库](https://www.chaijs.com/)。 

有关单元测试和测试组件示例的更多信息，请参阅[其他信息](#run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild-additional)部分。

## 先决条件和限制
<a name="run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild-prereqs"></a>
+ 具有正确 CodeBuild 权限的活跃 AWS 账户
+  GitHub 账户（参见[注册说明](https://docs.github.com/en/get-started/signing-up-for-github/signing-up-for-a-new-github-account)）
+ Git（请参阅[安装说明](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)）
+ 用于进行更改并将代码推送到的代码编辑器 GitHub

## 架构
<a name="run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild-architecture"></a>

此模式实施下图中所示的架构。

![\[AWS 云架构，用于使用 CodeBuild 和 GitHub 存储库运行单元测试\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e18428ce-9ecf-4204-9f1f-5a6683a720b2/images/4f4a3d1a-705a-45a6-b937-9212b188d226.png)


## 工具
<a name="run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild-tools"></a>

**工具**
+ [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 是一个可用于代码开发的版本控制系统。
+ [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/) 是一项完全托管的持续集成服务，可编译源代码、运行测试并生成可随时部署的软件包。使用 CodeBuild，您无需预置、管理和扩展自己的构建服务器。 CodeBuild 持续扩展并同时处理多个构建，因此您的构建不会在队列中等待。您可以使用预先打包的构建环境快速开始，也可以创建使用您自己的构建工具的自定义构建环境。使用 CodeBuild，按分钟计费所使用的计算资源。

**代码**

此模式的源代码可在 GitHub[示例游戏单元测试应用程序](https://github.com/aws-samples/node-js-tests-sample)存储库中找到。您可以根据此示例（选项 1）创建自己的 GitHub 存储库，也可以直接使用示例存储库（选项 2）来创建此模式。按照下一节中每个选项的说明操作。选项的选择因用例而定。

## 操作说明
<a name="run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild-epics"></a>

### 选项 1-使用在您的个人 GitHub 存储库上运行单元测试 CodeBuild
<a name="option-1---run-unit-tests-on-your-personal-github-repository-with-codebuild"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 根据示例项目创建自己的 GitHub 存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 创建新 CodeBuild 项目。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 开始构建。 | 在**审核**页面上，选择**开始构建**以运行构建。 | 应用程序开发人员、AWS 管理员、AWS DevOps | 

### 选项 2-使用以下命令在公共存储库上运行单元测试 CodeBuild
<a name="option-2---run-unit-tests-on-a-public-repository-with-codebuild"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建新的 CodeBuild 构建项目。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild.html) | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 开始构建。 | 在**审核**页面上，选择**开始构建**以运行构建。 | 应用程序开发人员、AWS 管理员、AWS DevOps | 

### 分析单元测试
<a name="analyze-the-unit-tests"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 查看测试结果。 | 在 CodeBuild 控制台中，查看 CodeBuild 作业的单元测试结果。这些结果应与[其他信息](#run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild-additional)部分中显示的结果相符。这些结果验证了 GitHub 存储库与的集成 CodeBuild。  | 应用程序开发人员、AWS 管理员、AWS DevOps | 
| 应用 Webhook。 | 现在，您可以应用 Webhook，这样无论何时将代码变更推送到存储库的主分支，都可以自动启动构建。有关说明，请参阅 [CodeBuild 文档](https://docs.aws.amazon.com/codebuild/latest/userguide/github-webhook.html)。 | 应用程序开发人员、AWS 管理员、AWS DevOps | 

## 相关资源
<a name="run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild-resources"></a>
+ [示例游戏单元测试应用程序](https://github.com/aws-samples/node-js-tests-sample)（包含示例代码的GitHub 存储库）
+ [AWS CodeBuild 文档](https://docs.aws.amazon.com/codebuild/)
+ [GitHub webhook 事件](https://docs.aws.amazon.com/codebuild/latest/userguide/github-webhook.html)（CodeBuild 文档）
+ [创建新存储库](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository)（GitHub 文档）

## 附加信息
<a name="run-unit-tests-for-a-node-js-application-from-github-by-using-aws-codebuild-additional"></a>

**单元测试结果**

在 CodeBuild 控制台中，项目成功生成后，您应该会看到以下测试结果。 

![\[单元测试的预期结果\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/e18428ce-9ecf-4204-9f1f-5a6683a720b2/images/db861831-cfed-4e87-a498-0216606941f8.png)


**单元测试组件示例**

本节介绍单元测试中使用的四种类型的测试组件：断言、间谍、存根和模拟。它包括每个组件的简要说明和代码示例。 

**断言**

断言用于验证预期结果。这是一个重要的测试组件，因为它可以验证给定函数的预期响应。以下示例断言验证了初始化新游戏时返回的 ID 是否介于 0 和 1000 之间。

```
const { expect }  = require('chai');
const { Game } = require('../src/index');

describe('Game Function Group', () => {
 it('Check that the Game ID is between 0 and 1000', function() {
      const game = new Game();
      expect(game.id).is.above(0).but.below(1000)
 });
});
```

**间谍**

间谍用于观察函数运行时发生的情况。例如，您可能希望验证函数的调用是否正确。以下示例显示了在**游戏**类对象上调用启动和停止方法。

```
const { expect }  = require('chai');
const { spy } = require('sinon');

const { Game } = require('../src/index');

describe('Game Function Group', () => {
   it('should verify that the correct function is called', () => {
      const spyStart = spy(Game.prototype, "start");
      const spyStop = spy(Game.prototype, "stop");
     
      const game = new Game();
      game.start();
      game.stop();
     
      expect(spyStart.called).to.be.true
      expect(spyStop.called).to.be.true
    });
});
```

**存根**

存根用于覆盖函数的默认响应。当函数发出外部请求时，这特别有用，因为您想避免从单元测试中发出外部请求。（外部请求更适合集成测试，集成测试可以对不同组件之间的请求进行物理测试。） 在以下示例中，存根强制从 **getId** 函数返回一个 ID。

```
const { expect }  = require('chai');
const {.stub } = require('sinon');

const { Game } = require('../src/index');

describe('Game Function Group', () =>  {
   it('Check that the Game ID is between 0 and 1000', function() {
      let generateIdStub = stub(Game.prototype, 'getId').returns(999999);

      const game = new Game();

      expect(game.getId).is.equal(999999);

      generateIdStub.restore();
    });
});
```

**模拟**

模拟是一种虚假的方法，具有用于测试不同场景的预编程行为。模拟可以被视为存根的扩展形式，可以同时执行多个任务。在以下示例中，使用模拟来验证三个场景：
+ 调用函数 
+ 使用参数调用函数
+ 函数返回整数 9

```
const { expect }  = require('chai');
const {.mock } = require('sinon');

const { Game } = require('../src/index');

describe('Game Function Group', () =>  {
   it('Check that the Game ID is between 0 and 1000', function() {
      let mock = mock(Game.prototype).expects('getId').withArgs().returns(9);

      const game = new Game();
      const id = get.getId();

      mock.verify();
      expect(id).is.equal(9);
    });
});
```

# 使用 AWS Lambda 以六边形架构构建 Python 项目
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda"></a>

*Furkan Oruc、Dominik Goby、Darius Kunce 和 Michal Ploski，Amazon Web Services*

## Summary
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-summary"></a>

此模式展示了如何使用 AWS Lambda 以六边形架构构建 Python 项目。该模式使用 AWS Cloud Development Kit (AWS CDK) 作为基础设施即代码（IaC）工具，使用 Amazon API Gateway 作为 REST API，使用 Amazon DynamoDB 作为持久层。六边形架构遵循域驱动设计原则。在六边形架构中，软件由三个组件组成：域、端口和适配器。有关六边形架构及其优势的详细信息，请参阅指南[在 AWS 上构建六边形架构](https://docs.aws.amazon.com/prescriptive-guidance/latest/hexagonal-architectures/)*。*

## 先决条件和限制
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-prereqs"></a>

**先决条件**
+ 一个活跃的 AWS 账户
+ Python 经验
+ 熟悉 AWS Lambda、AWS CDK、Amazon API Gateway 和 DynamoDB
+  GitHub 账户（参见[注册说明](https://docs.github.com/en/get-started/signing-up-for-github/signing-up-for-a-new-github-account)）
+ Git（请参阅[安装说明](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)）
+ 一种代码编辑器，用于进行更改并将代码推送到 GitHub （例如，[Visual Studio Code](https://code.visualstudio.com/) 或 [JetBrains PyCharm](https://www.jetbrains.com/pycharm/)）
+ 已安装 Docker，而且 Docker 进程守护程序已经启动并且正在运行

**产品版本**
+ Git 版本 2.24.3 或更高版本
+ Python 版本 3.7 或更高版本
+ AWS CDK v2
+ EMR 版本 1.1.13 或更高版本
+ AWS Lambda Powertools for Python 版本 1.25.6 或更高版本
+ pytest 版本 7.1.1 或更高版本
+ Moto 版本 3.1.9 或更高版本
+ pydantic 版本 1.9.0 或更高版本
+ Boto3 版本 1.22.4 或更高版本
+ mypy-boto3-dynamodb 版本 1.24.0 或更高版本

## 架构
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-architecture"></a>

**目标技术堆栈 **

目标技术堆栈由使用 API Gateway、Lambda 和 DynamoDB 的 Python 服务构成。该服务使用 DynamoDB 适配器保存数据。它提供了使用 Lambda 作为入口点的函数。该服务使用 Amazon API Gateway 公开 REST API。API 使用 AWS Identity and Access Management (IAM) [对客户端执行身份验证](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html)。

**目标架构 **

为说明实现方式，此模式部署了无服务器目标架构。客户端可向 API Gateway 端点发送请求。API Gateway 将请求转发至实现六边形架构模式的目标 Lambda 函数。Lambda 函数可对 DynamoDB 表执行创建、读取、更新和删除（CRUD）操作。


| 
| 
| 此模式已在 PoC 环境中接受了测试。在将任何架构部署到生产环境之前，您必须执行安全审查，以便识别威胁模式和创建安全的代码库。 | 
| --- |

![\[用于以六边形架构构建 Python 项目的目标架构\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/25bd7169-ea5e-4a21-a865-c91c30a3c0da/images/de0d4f0d-ad19-43ec-bd10-676b25477b64.png)


该 API 支持对产品实体的五种操作：
+ `GET /products` 返回所有产品。
+ `POST /products` 创建新产品。
+ `GET /products/{id}` 返回特定产品。
+ `PUT /products/{id}` 更新特定产品。
+ `DELETE /products/{id}` 删除特定产品。

您可使用以下文件夹结构来组织项目，以遵循六边形架构模式：  

```
app/  # application code
|--- adapters/  # implementation of the ports defined in the domain
     |--- tests/  # adapter unit tests
|--- entrypoints/  # primary adapters, entry points
     |--- api/  # api entry point
          |--- model/  # api model
          |--- tests/  # end to end api tests
|--- domain/  # domain to implement business logic using hexagonal architecture
     |--- command_handlers/  # handlers used to execute commands on the domain
     |--- commands/  # commands on the domain
     |--- events/  # events triggered via the domain
     |--- exceptions/  # exceptions defined on the domain
     |--- model/  # domain model
     |--- ports/  # abstractions used for external communication
     |--- tests/  # domain tests
|--- libraries/  # List of 3rd party libraries used by the Lambda function
infra/  # infrastructure code
simple-crud-app.py  # AWS CDK v2 app
```

## 工具
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-tools"></a>

**AWS 服务**
+ [Amazon API Gateway](https://aws.amazon.com/api-gateway/) 是一项完全托管的服务，可让开发人员轻松创建、发布、维护、监控和保护 APIs 任何规模。
+ [Amazon DynamoDB](https://aws.amazon.com/dynamodb/) 是一个完全托管的无服务器键值的 NoSQL 数据库，专为运行任何规模的高性能应用程序而设计。
+ [AWS Lambda](https://aws.amazon.com/lambda/) 是一项无服务器、事件驱动计算服务，让您能够为几乎任何类型的应用程序或后端服务运行代码，而无需预调配或管理服务器。您可以从 200 多种 Amazon Web Services 和软件即服务（SaaS）应用程序启动 Lambda 函数，并且只需为您使用的部分付费。

**工具**
+ [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) 用作此模式中代码开发的版本控制系统。
+ [Python](https://www.python.org/) 用作此模式的编程语言。Python 提供高级数据结构和面向对象编程方法。AWS Lambda 提供内置的 Python 运行时系统，可简化 Python 服务的操作。
+ [Visual Studio Code](https://code.visualstudio.com/) 用作用于开发和测试此模式的 IDE。您可以使用任何支持 Python 开发的 IDE（例如 [PyCharm](https://www.jetbrains.com/pycharm/)）。
+ [AWS Cloud Development Kit（AWS CDK）](https://aws.amazon.com/cdk/)是一个开源软件开发框架，能够让您使用熟悉的编程语言来定义云应用程序资源。此模式使用 CDK 以代码形式编写和部署云基础设施。
+ [Poetry](https://python-poetry.org/) 用于管理模式中的依赖项。
+ AWS CDK 使用 [Docker](https://www.docker.com/) 构建 Lambda 包和层。

**代码**

此模式的代码可在 GitHub [Lambda 六边形架构示例存储](https://github.com/aws-samples/lambda-hexagonal-architecture-sample)库中找到。

## 最佳实践
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-best-practices"></a>

要在生产环境使用此模式，请遵循以下最佳实践：
+ 使用 AWS 密钥管理服务 (AWS KMS) 中的客户托管密钥对[亚马逊 CloudWatch 日志组和亚马逊](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/encrypt-log-data-kms.html) [DynamoDB 表](https://docs.aws.amazon.com/kms/latest/developerguide/services-dynamodb.html)进行加密。
+ 为 [Amazon API Gateway 配置 AWS WAF](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-control-access-aws-waf.html)，以允许仅从贵组织的网络进行访问。
+ 如果 IAM 不能满足您的需求，可考虑其他的 API Gateway 授权选项。例如，您可使用 [Amazon Cognito 用户池](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-integrate-with-cognito.html)或 [API Gateway Lambda 授权者](https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-use-lambda-authorizer.html)。
+ 使用 [DynamoDB 备份](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/BackupRestore.html)。
+ 使用[虚拟私有云（VPC）部署](https://docs.aws.amazon.com/lambda/latest/dg/configuration-vpc.html)来配置 Lambda 函数，将网络流量保持在云内。
+ 为[跨源资源共享 (CORS) 预检](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)更新允许的源配置，以限制仅访问请求的源域。
+ 使用 [cdk-nag](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/check-aws-cdk-applications-or-cloudformation-templates-for-best-practices-by-using-cdk-nag-rule-packs.html) 检查 AWS CDK 代码，了解安全最佳实践。
+ 考虑使用代码扫描工具来查找代码中常见的安全问题。例如，[Bandit](https://bandit.readthedocs.io/en/latest/) 是旨在查找 Python 代码中常见安全问题的工具。[Pip-audit](https://pypi.org/project/pip-audit/) 将扫描 Python 环境中是否存在已知漏洞的程序包。

此模式使用 [AWS X-Ray](https://aws.amazon.com/xray/?nc1=h_ls) 通过应用程序的入口点、域和适配器跟踪请求。AWS X-Ray 帮助开发人员识别瓶颈并确定高延迟以提高应用程序性能。

## 操作说明
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-epics"></a>

### 初始化项目
<a name="initialize-the-project"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 创建您自己的存储库。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 
| 安装依赖项。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 
| 配置您的 IDE。 | 我们推荐 Visual Studio Code，但您可以使用您选择的任何支持 Python 的 IDE。以下步骤适用于 Visual Studio Code。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 
| 运行单元测试，选项 1：使用 Visual Studio Code。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 
| 运行单元测试，选项 2：使用 Shell 命令。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 

### 部署和测试应用程序
<a name="deploy-and-test-the-application"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 请求临时凭证。 | 要在运行 `cdk deploy` 时在 Shell 中使用 AWS 凭证，请使用 AWS IAM Identity Center（AWS Single Sign-On 的后继任务）创建临时凭证。有关说明，请参阅博客文章[如何检索短期凭证，以便在 AWS IAM Identity Center 使用 CLI](https://aws.amazon.com/blogs/security/aws-single-sign-on-now-enables-command-line-interface-access-for-aws-accounts-using-corporate-credentials/)。 | AWS 应用程序开发人员 DevOps | 
| 部署 应用程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | AWS 应用程序开发人员 DevOps | 
| 测试 API，选项 1：使用控制台。 | 使用 [API Gateway 控制台](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-test-method.html)测试 API。有关 API 操作和 request/response 消息的更多信息，请参阅 GitHub 存储库中[自述文件的 API 用法部分](https://github.com/aws-samples/lambda-hexagonal-architecture-sample/blob/main/README.md#api-usage)。 | AWS 应用程序开发人员 DevOps | 
| 测试 API，选项 2：使用 Postman。 | 如果您要使用 [Postman](https://www.postman.com/) 这样的工具，请执行以下操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | AWS 应用程序开发人员 DevOps | 

### 开发服务
<a name="develop-the-service"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 为业务域编写单元测试。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 
| 实施命令和命令处理程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 
| 为辅助适配器编写集成测试。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 
| 实施辅助适配器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 
| 写 end-to-end测试。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 
| 实施主适配器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/structure-a-python-project-in-hexagonal-architecture-using-aws-lambda.html) | 应用程序开发人员 | 

## 相关资源
<a name="structure-a-python-project-in-hexagonal-architecture-using-aws-lambda-resources"></a>

**APG 指南**
+ [在 AWS 上构建六边形架构](https://docs.aws.amazon.com/prescriptive-guidance/latest/hexagonal-architectures/)

**AWS 参考**
+ [AWS Lambda 文档](https://docs.aws.amazon.com/lambda/)
+ [AWS CDK 文档](https://docs.aws.amazon.com/cdk/)
  + [您的第一个 AWS CDK 应用程序](https://docs.aws.amazon.com/cdk/v2/guide/hello_world.html)
+ [API Gateway 文档](https://docs.aws.amazon.com/apigateway/)
  + [使用 IAM 权限控制对 API 的访问](https://docs.aws.amazon.com/apigateway/latest/developerguide/permissions.html)
  + [使用 API Gateway 控制台测试 REST API 方法](https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-test-method.html)
+ [Amazon DynamoDB 文档](https://docs.aws.amazon.com/dynamodb/)

**工具**
+ [git-scm.com 网站](https://git-scm.com/)
+ [安装 Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
+ [创建新 GitHub 存储库](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-new-repository)
+ [Python 网站](https://www.python.org/)
+ [AWS Lambda Powertools for Python](https://docs.powertools.aws.dev/lambda/python/latest/)
+ [Postman 网站](https://www.postman.com/)
+ [Python 模拟对象库](https://docs.python.org/3/library/unittest.mock.html)
+ [Poetry 网站](https://python-poetry.org/)

**IDEs**
+ [Visual Studio Code 网站](https://code.visualstudio.com/)
+ [PyCharm 网站](https://www.jetbrains.com/pycharm/)

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

**Topics**
+ [使用 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)
+ [将一个 AWS CodeCommit 存储库 AWS 账户 与另一个账户中的 Amazon A SageMaker I Studio Classic 关联起来](associate-an-aws-codecommit-repository-in-one-aws-account-with-sagemaker-studio-in-another-account.md)
+ [自动删除 AWS CloudFormation 堆栈和相关资源](automate-deletion-cloudformation-stacks-associated-resources.md)
+ [使用，根据 IP 地址或地理位置限制访问 AWS WAF](aws-waf-restrict-access-geolocation.md)
+ [使用 AWS Amplify 构建无服务器 React Native 移动应用程序](build-a-serverless-react-native-mobile-app-by-using-aws-amplify.md)
+ [使用 AWS CodeCommit、AWS 和 AWS Device Farm 构建和测试 iOS 应用程序 CodePipeline](build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm.md)
+ [使用在 Amazon Logs 中为.NET 应用程序配置 CloudWatch 日志记录 NLog](configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog.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 EFS 创建 Amazon ECS 任务定义并在 EC2 实例上挂载文件系统](create-an-amazon-ecs-task-definition-and-mount-a-file-system-on-ec2-instances-using-amazon-efs.md)
+ [在 Amazon EKS 集群上部署基于 gRPC 的应用程序并使用应用程序负载均衡器访问它](deploy-a-grpc-based-application-on-an-amazon-eks-cluster-and-access-it-with-an-application-load-balancer.md)
+ [部署 ChatOps 解决方案来管理 SAST 扫描结果，方法是在聊天应用程序中使用 Amazon Q Developer 自定义操作和 CloudFormation](deploy-chatops-solution-to-manage-sast-scan-results.md)
+ [使用 Terraf CloudWatch orm 部署 Synthetics 加那利群岛](deploy-cloudwatch-synthetics-canaries-by-using-terraform.md)
+ [使用 AWS Fargate 在 Amazon ECS 上部署 Java 微服务](deploy-java-microservices-on-amazon-ecs-using-aws-fargate.md)
+ [使用 Terraform 和 Amazon AWS Bedrock 部署 RAG 用例](deploy-rag-use-case-on-aws.md)
+ [使用 Terraform 在 AWS Wavelength 区域中部署资源](deploy-resources-wavelength-zone-using-terraform.md)
+ [在 Amazon API Gateway 中使用自定义域实施基于路径的 API 版本控制](implement-path-based-api-versioning-by-using-custom-domains.md)
+ [将消息队列从 Microsoft Azure 服务总线迁移到 Amazon SQS](migrate-a-messaging-queue-from-microsoft-azure-service-bus-to-amazon-sqs.md)
+ [将 .NET 应用程序从 Microsoft Azure 应用服务迁移到 AWS Elastic Beanstalk](migrate-a-net-application-from-microsoft-azure-app-service-to-aws-elastic-beanstalk.md)
+ [使用二进制方法将本地 Go Web 应用程序迁移至 AWS Elastic Beanstalk](migrate-an-on-premises-go-web-application-to-aws-elastic-beanstalk-by-using-the-binary-method.md)
+ [将本地 SFTP 服务器迁移到使用 AWS AWS Transfer for SFTP](migrate-an-on-premises-sftp-server-to-aws-using-aws-transfer-for-sftp.md)
+ [在 Amazon 上从 IBM WebSphere 应用程序服务器迁移到 Apache Tomcat EC2](migrate-from-ibm-websphere-application-server-to-apache-tomcat-on-amazon-ec2.md)
+ [使用 Auto Scaling 从 IBM WebSphere 应用程序服务器迁移到亚马逊 EC2 上的 Apache Tomcat](migrate-from-ibm-websphere-application-server-to-apache-tomcat-on-amazon-ec2-with-auto-scaling.md)
+ [使用 AWS App2Container 将本地 Java 应用程序迁移到 AWS](migrate-on-premises-java-applications-to-aws-using-aws-app2container.md)
+ [使用 ACM 将 Windows SSL 凭证迁移到应用程序负载均衡器](migrate-windows-ssl-certificates-to-an-application-load-balancer-using-acm.md)
+ [在 AWS 上实现 ASP.NET Web 表单应用程序的现代化](modernize-asp-net-web-forms-applications-on-aws.md)
+ [使用 L CloudWatch ogs Insights 监控应用程序活动](monitor-application-activity-by-using-cloudwatch-logs-insights.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)
+ [将自定义属性发送至 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)
+ [在 AWS 上设置高度可用的 PeopleSoft 架构](set-up-a-highly-available-peoplesoft-architecture-on-aws.md)
+ [使用自动化工作流简化 Amazon Lex 机器人的开发和部署](streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.md)
+ [使用 Amazon Bedroc AWS Step Functions k 对中的状态进行故障排除](troubleshooting-states-in-aws-step-functions.md)
+ [使用网络防火墙从出站流量的服务器名称指示（SNI）中捕获 DNS 域名](use-network-firewall-to-capture-the-dns-domain-names-from-the-server-name-indication-sni-for-outbound-traffic.md)
+ [使用 Flask 和 AWS Elastic Beanstalk 可视化 AI/ML 模型结果 AWS Beanstalk](visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk.md)