

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

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