

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

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

**Topics**
+ [使用後台和自助式 Amazon SageMaker AI 範本加速 MLOps](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 動作自動化 AWS CDK Python 應用程式的 Amazon CodeGuru 檢閱](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)
+ [使用 AWS Service Catalog 和 自動化動態管道管理，以在 Gitflow 環境中部署 Hotfix 解決方案 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)
+ [使用 Cloud Custodian 和 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 動作和 Terraform 建置 Docker 映像並將其推送至 Amazon ECR](build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform.md)
+ [使用 AWS CodeCommit、AWS CodePipeline 和 AWS Device Farm 建置和測試 iOS 應用程式](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)
+ [使用 GitHub Actions 建立 Terraform 受管 AWS 基礎設施的自動提取請求](create-automated-pull-requests-for-terraform-managed-aws-infrastructure.md)
+ [自動為 Java 和 Python 專案建立動態 CI 管道](create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.md)
+ [使用 Terraform 部署 CloudWatch Synthetics Canary](deploy-cloudwatch-synthetics-canaries-by-using-terraform.md)
+ [在聊天應用程式自訂動作和 中使用 Amazon Q Developer 部署 ChatOps 解決方案來管理 SAST 掃描結果 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 任務 AWS CodePipeline](deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline.md)
+ [使用 AWS CodePipeline、AWS CodeCommit 和 AWS CodeBuild 在多個 AWS 區域中部署程式碼](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 檔案 AWS Organizations](export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file.md)
+ [將 Amazon 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 流程分支策略](implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.md)
+ [為多帳戶 DevOps 環境實作 Gitflow 分支策略](implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.md)
+ [實作多帳戶 DevOps 環境的主體分支策略](implement-a-trunk-branching-strategy-for-multi-account-devops-environments.md)
+ [實作集中式自訂 Checkov 掃描，以在部署 AWS 基礎設施之前強制執行政策](centralized-custom-checkov-scanning.md)
+ [使用 K8sGPT 和 Amazon Bedrock 整合實作採用 AI 技術的 Kubernetes 診斷和故障診斷](implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration.md)
+ [在 CodeCommit 中自動偵測變更並啟動單一儲存庫的不同 CodePipeline 管道 CodeCommit](automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.md)
+ [使用 AWS CloudFormation 將 Bitbucket 儲存庫與 AWS Amplify 整合](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 多區域金鑰，管理將微服務部署至多個帳戶和區域的藍/綠部署](manage-blue-green-deployments-of-microservices-to-multiple-accounts-and-regions-by-using-aws-code-services-and-aws-kms-multi-region-keys.md)
+ [使用 AWS CloudFormation 和 AWS Config 監控 Amazon ECR 儲存庫是否有萬用字元許可](monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config.md)
+ [使用 AWS CDK 和 GitHub Actions 工作流程最佳化多帳戶無伺服器部署](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)
+ [將 Amazon 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 帳戶 從 移除相同 中的 Amazon EC2 AWS Managed Microsoft AD 項目](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)
+ [使用 cert-manager 和 Let's Encrypt 為 Amazon EKS 上的應用程式設定end-to-end加密](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 CodePipeline 中使用第三方 Git 來源儲存庫](use-third-party-git-source-repositories-in-aws-codepipeline.md)
+ [使用 AWS CodePipeline 建立 CI/CD 管道來驗證 Terraform 組態](create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.md)
+ [更多模式](devops-more-patterns-pattern-list.md)

# 使用後台和自助式 Amazon SageMaker AI 範本加速 MLOps
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates"></a>

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

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

使用機器學習操作 (MLOps) 系統的組織在擴展、標準化和保護其 ML 基礎設施方面面臨重大挑戰。此模式引進一種轉型方法，結合了開放原始碼開發人員入口網站 [Backstage](https://backstage.io/) 與 [Amazon SageMaker AI](https://aws.amazon.com/sagemaker/) 和強化基礎設施即程式碼 (IaC) 模組，以改善資料科學團隊如何開發、部署和管理 ML 工作流程。

此模式的 IaC 模組會在 GitHub [AWS AIOps 模組](https://github.com/awslabs/aiops-modules/tree/main/modules/sagemaker)儲存庫中提供。這些模組提供預先建置的範本，用於設定 ML 基礎設施和建立一致的 ML 環境。不過，資料科學家通常很難直接使用這些範本，因為他們需要基礎設施專業知識。新增開發人員入口網站，例如 Backstage，為資料科學家建立易於使用的方式，以部署標準化的 ML 環境，而無需了解基礎基礎設施詳細資訊。

透過使用 Backstage 做為自助式平台並整合預先設定的 SageMaker AI 範本，您可以：
+ 加速 ML 計畫的價值實現時間。
+ 協助強制執行一致的安全性和控管。
+ 為資料科學家提供標準化、合規的環境。
+ 降低營運開銷和基礎設施複雜性。

此模式提供解決 MLOps 重大挑戰的解決方案，也提供可擴展、可重複的架構，在維持組織標準的同時實現創新。

**目標對象**

此模式適用於組織內涉及 ML、雲端架構和平台工程的廣泛受眾。其中包含：
+ 想要標準化和自動化 ML 工作流程部署的 ML **工程師**。
+ 希望自助存取預先設定且合規 ML 環境**的資料科學家**。
+ 負責建置和維護內部開發人員平台和共用基礎設施的平台**工程師**。
+ 為 MLOps 設計可擴展、安全且符合成本效益之雲端解決方案的雲端**架構師**。
+ 有興趣將持續整合和持續交付 (CI/CD) 實務延伸至 ML 基礎設施佈建和工作流程的 **DevOps 工程師**。
+ **技術主管和經理**負責監督 ML 計畫，並希望改善團隊生產力、控管和上市時間。

如需有關 MLOps 挑戰、SageMaker AI MLOps 模組，以及此模式提供的解決方案如何滿足 ML 團隊需求的詳細資訊，請參閱[其他資訊](#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 帳戶
+ 了解 [Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio-updated.html)、[SageMaker Projects](https://docs.aws.amazon.com/sagemaker/latest/dg/sagemaker-projects-whatis.html)、[SageMaker Pipelines](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-overview.html) 和 [SageMaker Model Registry](https://docs.aws.amazon.com/sagemaker/latest/dg/model-registry.html) 概念
+ 了解 IaC 原則和使用 等工具的經驗 [AWS Cloud Development Kit (AWS CDK)](https://aws.amazon.com/cdk/)

**限制**
+ 範本**涵蓋範圍有限**。目前，該解決方案僅支援更廣泛的 AIOps 解決方案中的 SageMaker AI 相關 [AIOps ](https://github.com/awslabs/aiops-modules)模組。其他模組，例如 Ray on Amazon Elastic Kubernetes Service (Amazon EKS)、MLflow、Apache Airflow，以及 Amazon Bedrock 的微調，尚無法做為後台範本使用。
+ **不可設定的預設設定**。範本使用來自 AIOps SageMaker 模組的固定預設組態，無需自訂。您無法透過 Backstage 介面修改執行個體類型、儲存體大小、聯網組態或安全政策，這會限制特定使用案例的彈性。
+ **AWS僅限 支援**。平台專為 AWS 部署而設計，不支援多雲端案例。在 外部使用雲端服務的組織 AWS 雲端 ，無法將這些範本用於其 ML 基礎設施需求。
+ **手動憑證管理**。您必須為每個部署手動提供登入 AWS 資料。此解決方案不提供與公司身分提供者 AWS IAM Identity Center或自動憑證輪換的整合。
+ **有限的生命週期管理**。範本缺少全面的資源生命週期管理功能，例如自動清除政策、成本最佳化建議和基礎設施偏離偵測。建立後，您必須手動管理和監控部署的資源。

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

下圖顯示統一開發人員入口網站的解決方案架構，該入口網站使用 SageMaker AI 標準化和加速跨環境的 ML 基礎設施部署。

![\[適用於具有 Backstage、CNOE、GitHub Actions 和 Seed-Farmer 的統一開發人員入口網站的架構。\]](http://docs.aws.amazon.com/zh_tw/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解決方案。Backstage 透過[Keycloak](https://www.keycloak.org/) 綁定了強大的身分驗證，並透過[Argo CD](https://argo-cd.readthedocs.io/en/stable/) 綁定了全面的部署工作流程。此整合式平台會建立集中式環境來管理開發程序，並為團隊提供單一位置，以跨多個環境存取、部署和監控其基礎設施和應用程式。

1. GitHub 儲存庫包含預先設定的 AIOps 軟體範本，涵蓋整個 SageMaker AI 生命週期。這些範本可解決重要的 ML 基礎設施需求，包括 SageMaker Studio 佈建、模型訓練、推論管道和模型監控。這些範本可協助您加速 ML 計畫，並確保不同專案和團隊的一致性。

1. [GitHub Actions](https://github.com/features/actions) 實作自動化工作流程，透過 [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 雲端 基礎設施。
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) 可協助您在 上執行 Kubernetes， AWS 而無需安裝或維護您自己的 Kubernetes 控制平面或節點。
+ [Amazon SageMaker AI](https://docs.aws.amazon.com/sagemaker/) 是一種受管 ML 服務，可協助您建置和訓練 ML 模型，然後將模型部署到生產就緒的託管環境中。

**其他工具**
+ [Backstage](https://backstage.io/) 是一種開放原始碼架構，可協助您建置內部開發人員入口網站。
+ [GitHub Actions](https://github.com/features/actions) 是一種 CI/CD 平台，可自動化軟體開發工作流程，包括建置、測試和部署程式碼等任務。

**程式碼儲存庫**

此模式使用來自下列 GitHub 儲存庫的程式碼和範本：
+ [AIOps 內部開發人員平台 (IDP) 與 Backstage](https://github.com/aws-samples/sample-aiops-idp-backstage/) 儲存庫
+ 來自 AIOps 模組儲存庫的 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)後台的生產級部署模式。此方法可大幅簡化設定程序，同時整合安全性和可擴展性的 AWS 最佳實務。

此模式的 [Epics](#accelerate-mlops-with-backstage-and-sagemaker-templates-epics) 區段概述了實作方法。如需詳細的step-by-step部署說明，請參閱 [AIOps 內部開發人員平台 (IDP) 與 Backstage](https://github.com/aws-samples/sample-aiops-idp-backstage/) 儲存庫中提供的完整[部署指南](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md)。實作包括：
+ 初始後台平台部署
+ 將 SageMaker 軟體範本與 Backstage 整合
+ 使用和維護後台範本

部署指南也包含持續維護、疑難排解和平台擴展的指引。

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

遵循這些最佳實務，以協助確保 MLOps 基礎設施實作的安全性、控管和卓越營運。

**範本管理**
+ 絕不對即時範本進行重大變更。
+ 在生產部署之前，請務必徹底測試更新。
+ 維護清楚且記錄良好的範本版本。

**安全性**
+ 將 GitHub 動作釘選至特定遞交安全雜湊演算法 (SHAs)，以協助防止供應鏈攻擊。
+ 使用具有精細許可的最低權限 IAM 角色。
+ 將敏感登入資料儲存在 [GitHub Secrets](https://docs.github.com/en/actions/concepts/security/secrets) 和 中[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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 Backstage。 | 此步驟使用 儲存庫[上現代工程 AWS](https://github.com/aws-samples/appmod-blueprints)的藍圖，建置強大且可擴展的基礎設施，整合多個 AWS 服務 以建立 ML 工作流程的集中式 IDP。遵循部署指南[後台部署一節](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#backstage-deployment)中的指示，複製儲存庫、安裝相依性、引導 AWS CDK 設定環境變數，以及部署後台平台。基礎設施使用 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 範本） 整合到您的後台部署中，讓您可以自行滿足 ML 基礎設施需求。 | 平台工程師 | 
| 使用 Backstage 中的 SageMaker AI 範本。 | 遵循部署指南[的使用 SageMaker 範本](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#using-sagemaker-templates)一節中的指示，存取 Backstage 入口網站並在 SageMaker Studio 中建立 ML 環境。在 Backstage 入口網站中，您可以從可用的 SageMaker AI 範本中選擇，包括 SageMaker Studio 環境、SageMaker 筆記本、自訂 SageMaker 專案範本和模型部署管道的選項。在您提供組態參數之後，平台會自動建立專用儲存庫，並透過 GitHub Actions 和 Seed-Farmer 佈建 AWS 資源。您可以透過 GitHub 動作日誌和 Backstage 元件目錄來監控進度。 | 資料科學家、資料工程師、開發人員 | 

### 管理用於控管和合規的範本
<a name="manage-templates-for-governance-and-compliance"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 更新 SageMaker AI 範本。 | 若要更新後台中的 SageMaker AI 範本，請遵循下列步驟。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/accelerate-mlops-with-backstage-and-sagemaker-templates.html) | 平台工程師 | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將範本涵蓋範圍擴展到 SageMaker AI 之外。 | 目前的解決方案只會實作 SageMaker AI 相關的 AIOps 範本。您可以新增 [AIOps 模組](https://github.com/awslabs/aiops-modules)並整合其他 AWS 服務 和應用程式的自訂軟體範本，以擴展 ML 環境。您可以使用 Backstage 中的範本設計工具界面、實作自訂 scaffolder 動作，或使用標準中繼資料維護範本儲存庫，來建立這些項目。平台支援範本版本控制、跨團隊共用和驗證工作流程，以確保一致性。如需詳細資訊，請參閱 [Backstage 文件](https://backstage.io/docs/overview/what-is-backstage/)。您也可以實作範本繼承模式來建立基礎範本的專用版本。此可擴展性可讓您管理 SageMaker AI 以外的各種 AWS 資源和應用程式，同時保留簡化的開發人員體驗和維護組織的標準。 | 平台工程師 | 
| 使用動態參數注入。 | 目前範本使用預設組態而不進行自訂，並執行 Seed-Farmer CLI 以部署具有預設變數的資源。您可以針對模組特定的組態使用動態參數注入來擴展預設組態。 | 平台工程師 | 
| 增強安全性和合規性。 | 若要增強建立 AWS 資源的安全性，您可以啟用角色型存取控制 (RBAC) 與單一登入 (SSO)、SAML、OpenID Connect (OIDC) 和政策整合，做為程式碼強制執行。 | 平台工程師 | 
| 新增自動資源清除。 | 您可以啟用自動清除政策的功能，也可以新增基礎設施偏離偵測和修復。 | 平台工程師 | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 移除後台基礎設施和 SageMaker AI 資源。 | 使用完 ML 環境後，請遵循部署指南的[清除和資源管理](https://github.com/aws-samples/sample-aiops-idp-backstage/blob/main/SETUP.md#cleanup-and-resource-management)一節中的指示，移除後台基礎設施並刪除 ML 環境中的 SageMaker AI 資源。 | 平台工程師 | 

## 疑難排解
<a name="accelerate-mlops-with-backstage-and-sagemaker-templates-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| AWS CDK 引導失敗 |  驗證 AWS 登入資料和區域組態。 | 
| Amazon EKS 叢集存取問題 | 檢查 **kubectl** 組態和 IAM 許可。 | 
| Application Load Balancer 連線問題 | 確定安全群組允許連接埠 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 Cloud Adoption Framework： Platform perspective* 指南中）
+ [Amazon SageMaker AI 文件](https://docs.aws.amazon.com/sagemaker/)
+ [後台軟體範本 ](https://backstage.io/docs/features/software-templates/)（後台網站）
+ [AIOps 模組儲存庫](https://github.com/awslabs/aiops-modules) (ML 可重複使用 IaC 模組的集合）
+ [AIOps 內部開發人員平台 (IDP) 與 Backstage](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 模型、資料集和管道。這會導致多餘的工作和錯失重複使用的機會。
+ **複雜的控管和合規**。確保 ML 專案遵守組織安全政策、資料隱私權法規和合規標準，例如健康保險流通與責任法案 (HIPAA) 和一般資料保護法規 (GDPR)，在沒有自動化防護機制的情況下可能具有挑戰性。
+ **值時間變慢**。這些挑戰的累積效果會導致長期的 ML 專案生命週期，並延遲從 ML 投資實現商業價值。
+ **安全風險**。不一致的組態和手動程序可能會引入安全漏洞，導致難以強制執行最低權限和網路隔離。

這些問題會延長開發週期、增加營運開銷，並帶來安全風險。ML 的反覆性質需要可重複的工作流程和高效的協同合作。

截至 2026 年，Gartner 預測 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 專案、管道和相關聯網和儲存資源的最佳實務，目標是降低複雜性並加速 ML 環境的設定。您可以將這些範本用於各種 MLOps 使用案例，以建立一致且安全的部署模式，促進更受管且更有效率的 ML 工作流程方法。

直接使用 AIOps 模組通常需要平台團隊部署和管理這些 IaC 範本，這可能為希望自助存取的資料科學家帶來挑戰。探索和了解可用的範本、設定必要的參數，以及觸發其部署，可能需要導覽 AWS 服務 主控台或直接與 IaC 工具互動。這可能會為偏好專注於 ML 任務的資料科學家產生摩擦、增加認知負載，如果這些範本不是透過集中且易於使用的界面進行管理，可能會導致參數化不一致或偏離組織標準。將這些強大的 AIOps 模組與 Backstage 等 IDP 整合，可提供簡化的自助式體驗、增強的可探索性和更強大的控管控制，以使用這些標準化的 MLOps 建置區塊，協助解決這些挑戰。

**後台做為 IDP**

內部開發人員平台 (IDP) 是由平台團隊建置的自助服務層，可簡化和標準化開發人員建置、部署和管理應用程式的方式。它可消除基礎設施的複雜性，並讓開發人員透過統一的界面輕鬆存取工具、環境和服務。

IDP 的主要目標是透過以下方式增強開發人員體驗和生產力：
+ 為服務建立和部署等任務啟用自助式服務。
+ 透過標準範本提升一致性和合規性。
+ 整合整個開發生命週期 (CI/CD、監控和文件） 的工具。

Backstage 是由 Spotify 建立的開放原始碼開發人員入口網站，現在是雲端原生運算基金會 (CNCF) 的一部分。它透過提供集中、可擴展的平台來管理軟體元件、工具和文件，協助組織建置自己的 IDP。透過 Backstage，開發人員可以：
+ 透過軟體目錄探索和管理所有內部服務。
+ 透過 scaffolder 外掛程式使用預先定義的範本建立新專案。
+ 從單一位置存取整合式工具，例如 CI/CD 管道、Kubernetes 儀表板和監控系統。
+ 透過 TechDocs 維護一致的 Markdown 型文件。

**常見問答集**

**使用此後台範本與透過 SageMaker 主控台手動部署 SageMaker Studio 有何不同？**

Backstage 範本提供優於手動 AWS 主控台部署的多種優勢，包括遵循組織最佳實務的標準化組態、使用 Seed-Farmer 和 的自動化 IaC 部署 AWS CDK、內建安全政策和合規措施，以及透過 GitHub 與您組織的開發人員工作流程整合。範本也會使用版本控制建立可重現的部署，讓您更輕鬆地跨不同階段 （開發、預備、生產） 複寫環境，並維持團隊之間的一致性。此外，範本包含自動清除功能，並透過 Backstage 與您組織的身分管理系統整合。透過主控台手動部署需要深入的 AWS 專業知識，並且不提供版本控制或範本提供的相同層級的標準化和管理。因此，相較於生產 ML 環境，主控台部署更適合一次性實驗。

**什麼是 Seed-Farmer？為什麼使用此解決方案？**

Seed-Farmer 是一種 AWS 部署協調工具，可透過使用 管理基礎設施模組 AWS CDK。此模式使用 Seed-Farmer，因為它提供標準化、可重複使用的基礎設施元件，專為 AI/ML 工作負載而設計， AWS 服務 自動處理之間的複雜相依性，並確保在不同環境中進行一致的部署。

**我需要安裝 AWS CLI 才能使用這些範本嗎？**

否，您不需要 AWS CLI 在電腦上安裝 。範本完全透過雲端中的 GitHub 動作執行。您可以透過 Backstage 介面提供 AWS 登入資料 （存取金鑰、私密金鑰和工作階段字符），而部署會自動在 GitHub Actions 環境中進行。

**部署 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*

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

在雲端原生解決方案中，自動化常見的基礎設施操作在維護有效率、安全且符合成本效益的環境方面扮演重要角色。手動處理操作耗時且容易發生人為錯誤。此外，具有不同 AWS 專業知識層級的團隊成員需要執行這些任務，同時確保遵守安全通訊協定。此模式示範如何使用 Amazon Bedrock 透過自然語言處理 (NLP) 自動化常見的 AWS 基礎設施操作。

此模式可協助組織開發可重複使用、模組化且安全的程式碼，以便在多個環境中部署生成式 AI 型基礎設施。透過專注於基礎設施即程式碼 (IaC) 和自動化，它提供了重要的 DevOps 優勢，包括版本控制、一致的部署、減少錯誤、更快速的佈建和改善的協同合作。

模式實作安全架構，讓團隊能夠管理與金鑰相關的操作， AWS 服務 包括：
+ Amazon Simple Storage Service (Amazon S3) 儲存貯體版本控制管理
+ 建立 Amazon Relational Database Service (Amazon RDS) 快照
+ Amazon Elastic Compute Cloud (Amazon EC2) 執行個體管理

架構採用 Amazon Virtual Private Cloud (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 AWS Provider 第 4 版或更新版本。
+ 安裝[https://developer.hashicorp.com/terraform/install](https://developer.hashicorp.com/terraform/install)並設定 Terraform 1.5.7 版或更新版本。
+ 在 [Amazon Bedrock 中檢閱和定義代理程式動作群組的 OpenAPI 結構描述](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-api-schema.html)，以協助防止未經授權的存取和維護資料完整性。
+ [在 中針對所需的 Amazon Titan Text Embeddings v2 和 Claude 3.5 Sonnet 或 Claude 3 Haiku 基礎模型啟用](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access-modify.html)存取。 AWS 帳戶 [https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html](https://docs.aws.amazon.com/bedrock/latest/userguide/models-supported.html)為了避免部署失敗，請確認您的目標部署 AWS 區域 [支援所需的模型](https://docs.aws.amazon.com/bedrock/latest/userguide/models-regions.html)。
+ 設定虛擬私有雲端 (VPC)，遵循 [AWS Well Architected Framework](https://docs.aws.amazon.com/wellarchitected/latest/framework/sec-design.html) 最佳實務。
+ 已完成 [Amazon Responsible AI 政策](https://aws.amazon.com/ai/responsible-ai/policy/)的檢閱。

**產品版本**
+ Amazon Titan Text Embeddings v2
+ Anthropic Claude 3.5 Sonnet 或 Claude 3 Haiku
+ Terraform AWS Provider 第 4 版或更新版本
+ Terraform 1.5.7 版或更新版本

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

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

![\[使用 Amazon Bedrock 自動化常見 AWS 基礎設施操作的工作流程。\]](http://docs.aws.amazon.com/zh_tw/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 Text Embeddings v2 模型進行自然語言處理。

1. 如果使用者提示包含動作請求，Amazon Bedrock 動作群組會使用 Anthropic Claude 3 Haiku 或 Claude 3.5 Sonnet 模型 （取決於您的選擇） 執行邏輯，並透過 OpenAPI 結構描述定義操作。

1. 動作群組使用 到達 Amazon VPC [端點](https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/what-are-vpc-endpoints.html)， AWS PrivateLink 以安全進行服務通訊。

1. 透過 Amazon Bedrock 服務的 Amazon VPC 端點達到 AWS Lambda 函數。

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 使用來自領導 AI 新創公司的高效能基礎模型 (FMs) 和 Amazon。
+ [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 Serverless](https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-overview.html) 是 Amazon OpenSearch Service 的隨需無伺服器組態。
+ [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 (Amazon 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/) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。

**程式碼儲存庫**

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

## 最佳實務
<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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要在本機電腦上複製儲存庫，請執行下列命令：<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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 存取解決方案。 | 成功部署後，請依照下列步驟使用聊天型界面：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-aws-infrastructure-operations-by-using-amazon-bedrock.html) | AWS DevOps，DevOps 工程師 | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除建立的資源。 | 若要刪除此模式建立的所有基礎設施，請執行下列命令：<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 文件中的疑難排解](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot.html) IAM。 | 

## 相關資源
<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)
+ [Amazon Bedrock 代理程式的運作方式](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-how.html)
+ [使用 Amazon Bedrock 知識庫擷取資料並產生 AI 回應](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*

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

當 Amazon Elastic Kubernetes Service (Amazon EKS) 的使用者透過 Helm Chart 刪除和重新安裝其輸入組態時，會建立新的 Application Load Balancer (ALB)。這會造成問題，因為 Amazon CloudFront 會繼續參考舊 ALB 的 DNS 記錄。因此，無法連線到目標為此端點的服務。（如需此有問題工作流程的詳細資訊，請參閱[其他資訊](#automate-cloudfront-updates-when-load-balancer-endpoints-change-additional)。)

為了解決此問題，此模式描述使用使用 Python 開發的自訂 AWS Lambda 函數。此 Lambda 函數會自動偵測何時透過 Amazon EventBridge 規則建立新的 ALB。然後 適用於 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 文件》中的在 Amazon EKS 上使用 Helm 部署應用程式](https://docs.aws.amazon.com/eks/latest/userguide/helm.html)。
+ 設定 CloudFront 將呼叫路由到由 Helm [輸入控制器](https://kubernetes.io/docs/concepts/services-networking/ingress-controllers/)建立的 ALB。如需詳細資訊，請參閱 Amazon EKS 文件中的 [Install AWS Load Balancer 控制器與 Helm](https://docs.aws.amazon.com/eks/latest/userguide/lbc-helm.html)，以及 CloudFront 文件中的[限制對 Application Load Balancer 的存取](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/restrict-access-to-load-balancer.html)。
+ 在本機工作區中[安裝](https://developer.hashicorp.com/terraform/install?product_intent=terraform)和設定 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 版或更新版本

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

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

![\[使用透過 EventBridge 規則偵測到的新 ALB DNS 地址更新 CloudFront 的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/03c30b18-4dd7-4dd4-b960-5a5cc58cec63/images/28854767-0902-4398-80af-b19141dd94e4.png)


此解決方案會執行下列步驟：

1. 每當 Helm 重新啟動或部署時，Amazon EKS 輸入控制器都會建立新的 Application Load Balancer (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 CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Introduction.html) 透過全球資料中心網路提供 Web 內容，從而降低延遲並改善效能，從而加快 Web 內容的發佈速度。
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) 可協助您在 上執行 Kubernetes， AWS 而無需安裝或維護您自己的 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/) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。

**程式碼儲存庫**

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

## 史詩
<a name="automate-cloudfront-updates-when-load-balancer-endpoints-change-epics"></a>

### 設定本機工作站
<a name="set-up-local-workstation"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 Git CLI。 | 若要在本機工作站中安裝和設定 Git 命令列界面 (CLI)，請遵循 [Git 文件中的入門 – 安裝](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) Git 說明。 | DevOps 工程師 | 
| 建立專案資料夾並新增檔案。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署解決方案。 | 若要在目標中部署資源 AWS 帳戶，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-cloudfront-updates-when-load-balancer-endpoints-change.html) | DevOps 工程師 | 

### 驗證部署
<a name="verify-the-deployment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-cloudfront-updates-when-load-balancer-endpoints-change.html) | DevOps 工程師 | 

### 清除基礎設施
<a name="clean-up-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除基礎設施。 | 若要清除您先前建立的基礎設施，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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**
+ [限制對 Application Load Balancer 的存取](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/restrict-access-to-load-balancer.html)
+ [使用 AWS Load Balancer控制器路由網際網路流量](https://docs.aws.amazon.com/eks/latest/userguide/aws-load-balancer-controller.html)

**Terraform 文件**
+ [AWS 供應商](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>

**有問題的工作流程**

![\[在 CloudFront 中產生out-of-date ALB DNS 項目的工作流程。\]](http://docs.aws.amazon.com/zh_tw/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 Chart 進行。每當有部署或有人重新啟動 Helm 時，也會重新建立個別的輸入。因此，外部負載平衡器控制器會重新建立 ALB。此外，在每次重新建立期間，會使用不同的 DNS 名稱重新建立 ALB。因此，CloudFront 在原始伺服器設定中會有過時的項目。由於此項目過時，使用者將無法連線應用程式。此問題會導致使用者停機。

**替代解決方案**

另一個可能的解決方法是為 ALB 建立[外部 DNS](https://github.com/kubernetes-sigs/external-dns)，然後將其指向 CloudFront 中的 Amazon Route 53 私有託管區域端點。不過，此方法會在應用程式流程中新增另一個跳轉，這可能會導致應用程式延遲。此模式的 Lambda 函數解決方案不會中斷目前的流程。

# 使用 GitHub 動作自動化 AWS CDK Python 應用程式的 Amazon CodeGuru 檢閱
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications"></a>

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

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

注意：自 2025 年 11 月 7 日起，您無法在 Amazon CodeGuru Reviewer 中建立新的儲存庫關聯。若要了解具有類似 CodeGuru Reviewer 功能的服務，請參閱 [ CodeGuru Reviewer 文件中的 Amazon CodeGuru Reviewer 可用性變更](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/codeguru-reviewer-availability-change.html)。 CodeGuru 

此模式展示透過 GitHub 動作協調的 AWS Cloud Development Kit (AWS CDK) Python 應用程式的 Amazon CodeGuru 自動化程式碼檢閱整合。解決方案會部署 AWS CDK Python 中定義的無伺服器架構。透過在開發管道中自動化專家程式碼分析，此方法可以對 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) 撰寫的應用程式](https://docs.aws.amazon.com/codeguru/latest/profiler-ug/what-is-codeguru-profiler.html#what-is-language-support)，以及執行時間和 Python 3.6 或更新版本。
+ Amazon CodeGuru Reviewer 僅[支援來自下列來源提供者的 Java 和 Python 程式碼儲存庫關聯](https://docs.aws.amazon.com/codeguru/latest/reviewer-ug/working-with-repositories.html)：Bitbucket AWS CodeCommit、GitHub、GitHub Enterprise Cloud 和 GitHub Enterprise Server。此外，僅透過 GitHub 動作支援 Amazon Simple Storage Service (Amazon S3) 儲存庫。
+ 在持續整合和持續部署 (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)，然後選擇服務的連結。

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

下圖顯示此解決方案的架構。

![\[使用 GitHub 動作整合 AWS CDK Python 應用程式 CodeGuru 程式碼檢閱的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/c5395e3e-ff2a-41cf-bd64-c73cc928b60b/images/18f880a2-9bc3-4d71-a598-bb83b68ee383.png)


如圖所示，當開發人員建立提取請求 (PR) 以供檢閱時，GitHub Actions 會觸發下列步驟：

1. IAM 角色假設 – 管道使用 GitHub Secrets 中指定的 IAM 角色來執行部署任務。

1. 程式碼分析
   + CodeGuru Reviewer 會分析存放在 Amazon S3 儲存貯體中的程式碼。它可識別瑕疵並提供修正和最佳化的建議。
   + CodeGuru Security 會掃描政策違規和漏洞。

1. 調查結果檢閱
   + 管道會在主控台輸出中列印問題清單儀表板的連結。
   + 如果偵測到關鍵問題清單，管道會立即失敗。
   + 對於高、正常或低嚴重性的問題清單，管道會繼續進行下一個步驟。

1. PR 核准
   + 檢閱者必須手動核准 PR。
   + 如果 PR 遭拒，管道會失敗並停止進一步的部署步驟。

1. CDK 部署 – 在 PR 核准時，CDK 部署程序就會開始。它會設定下列 AWS 服務 和資源：
   + CodeGuru Profiler
   + AWS Lambda 函數
   + Amazon Simple Queue Service (Amazon SQS) 佇列

1. 分析資料產生 – 若要為 CodeGuru Profiler 產生足夠的分析資料：
   + 管道會定期傳送訊息至 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) 使用程式分析和機器學習來偵測開發人員難以找到的潛在瑕疵。然後，CodeGuru Profiler 會提供改善 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 Actions](https://docs.github.com/en/actions/writing-workflows/quickstart) 是與 GitHub 儲存庫緊密整合的持續整合和持續交付 (CI/CD) 平台。您可以使用 GitHub 動作來自動化建置、測試和部署管道。

**程式碼儲存庫**

此模式的程式碼可在 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 Actions [工作流程 中使用 時，請遵循 IAM 中的安全最佳實務](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)，包括： AWS 服務 
  + 請勿將登入資料存放在您的儲存庫程式碼中。
  + [擔任 IAM 角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-workloads-use-roles) 來接收臨時登入資料，並盡可能使用臨時登入資料。
  + 將[最低權限授予](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)  GitHub 動作工作流程中使用的 IAM 角色。僅授予在 GitHub 動作工作流程中執行動作所需的許可。
  + [監控 GitHub 動作工作流程中使用的 IAM 角色活動](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#remove-credentials) 。 GitHub 
  + 定期輪換您使用的任何長期登入資料。

## 史詩
<a name="automate-amazon-codeguru-reviews-for-aws-cdk-python-applications-epics"></a>

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 合成 AWS CDK 應用程式。 | 若要合成 AWS CDK 應用程式，請執行下列命令：<pre>cdk synth</pre>如需此命令的詳細資訊，請參閱 AWS CDK 文件中的 [cdk 合成](https://docs.aws.amazon.com/cdk/v2/guide/ref-cli-cmd-synth.html)。 | 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 GitHub 中建立所需的秘密。 | 若要允許 GitHub Actions 工作流程安全地存取 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_tw/prescriptive-guidance/latest/patterns/automate-amazon-codeguru-reviews-for-aws-cdk-python-applications.html) | AWS DevOps，DevOps 工程師 | 
| 建立 GitHub 個人存取字符。 | 若要為您的 GitHub 動作工作流程設定安全的方式來驗證身分並與 GitHub 互動，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-amazon-codeguru-reviews-for-aws-cdk-python-applications.html) | AWS DevOps，DevOps 工程師 | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除資源。 | 若要清除 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 雲端開發套件](https://aws.amazon.com/cdk/)
+ [Amazon 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，Amazon Web Services*

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

此模式提供自動化方法來使用多儲存庫持續整合和持續部署 (CI/CD) 管道來部署和管理 AWS Supply Chain 資料湖。它示範了兩種部署方法：使用 GitHub Actions 工作流程自動部署，或直接使用 Terraform 手動部署。這兩種方法都使用 Terraform for infrastructure as code (IaC)，搭配自動方法新增 GitHub Actions 和 JFrog Artifactory 來增強 CI/CD 功能。

解決方案利用 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/) 3.13 版
+ [Terraform](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli) 1.12 版或更新版本

在部署之前，請確定已備妥下列項目：
+ 作用中 AWS 帳戶。
+ [虛擬私有雲端 (VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/create-vpc.html)， AWS 區域 在您的 中選擇的 AWS 帳戶 中有兩個[私有子網路](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-example-private-subnets-nat.html)。
+ 用於部署至下列服務的 AWS Identity and Access Management (IAM) 角色的足夠許可：
  + AWS Supply Chain – 偏好完整存取來部署其元件，例如資料集和整合流程，以及從 存取。 AWS 管理主控台
  + Amazon CloudWatch Logs – 用於建立和管理 CloudWatch 日誌群組。
  + Amazon Elastic Compute Cloud (Amazon EC2) – 適用於 Amazon EC2 安全群組和 Amazon Virtual Private Cloud (Amazon VPC) 端點。
  + Amazon 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 – 用於建立部署 AWS Supply Chain 元件的 Lambda 函數。
  + Amazon S3 – 用於存取 Amazon S3 成品儲存貯體、伺服器存取記錄儲存貯體和 AWS Supply Chain 預備儲存貯體。如果您使用手動部署，也需要 Amazon S3 Terraform 成品儲存貯體的許可。
  + Amazon 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 管理主控台。如需詳細資訊，請參閱 [IAM 文件中的建立角色以授予許可給 IAM 使用者](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user.html)。

如果您偏好手動部署，請執行下列動作：
+ 建立 IAM 使用者以擔任具有先前提及許可的 IAM 角色。如需詳細資訊，請參閱 [IAM 文件中的建立角色以授予許可給 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)，然後選擇服務的連結。

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

您可以使用自動化 GitHub 動作工作流程或使用 Terraform 手動部署此解決方案。

**使用 GitHub 動作自動部署**

下圖顯示使用 GitHub 動作工作流程的自動化部署選項。JFrog Artifactory 用於成品管理。它存放資源資訊和輸出，以用於多儲存庫部署。

![\[使用 GitHub Actions 工作流程和 JFrog 的自動化部署選項。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/2f0b78b0-a174-4703-b533-d66b3fb005e0/images/d454a5c5-ed51-421c-a87f-ff74cfcb30be.png)


**使用 Terraform 手動部署**

下圖顯示透過 Terraform 的手動部署選項。Amazon S3 用於成品管理，而不是 JFrog Artifactory。

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


**部署工作流程**

圖表顯示下列工作流程：

1. 使用下列其中一種部署方法部署 AWS Supply Chain 服務資料集基礎設施和資料庫：
   + **自動化部署** – 使用 GitHub Actions 工作流程協調所有部署步驟，並使用 JFrog Artifactory 進行成品管理。
   + **手動部署** – 直接針對每個部署步驟執行 Terraform 命令，並使用 Amazon S3 進行成品管理。

1. 建立 AWS Supply Chain 服務操作所需的支援 AWS 資源：
   + Amazon VPC 端點和安全群組
   + AWS KMS keys
   + CloudWatch Logs 日誌群組

1. 建立和部署下列基礎設施資源：
   + 管理 （建立、更新和刪除） AWS Supply Chain 服務執行個體、命名空間和資料集的 Lambda 函數。
   + AWS Supply Chain 暫存 Amazon S3 儲存貯體以進行資料擷取

1. 部署 Lambda 函數，管理預備儲存貯體和 AWS Supply Chain 資料集之間的整合流程。部署完成後，剩餘的工作流程步驟會管理資料擷取和分析。

1. 設定 AWS Supply Chain 暫存 Amazon 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 Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.html) 可協助您集中所有系統、應用程式的日誌， 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 (Amazon 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 Actions](https://docs.github.com/en/actions) 是與 GitHub 儲存庫緊密整合的持續整合和持續交付 (CI/CD) 平台。您可以使用 GitHub 動作來自動化建置、測試和部署管道。
+ [HashiCorp Terraform](https://www.terraform.io/) 是一種基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。
+ [JFrog Artifactory](https://jfrog.com/help/r/jfrog-artifactory-documentation/jfrog-artifactory) 透過應用程式交付程序，提供二進位檔和成品的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)中所述，請確定具有兩個[私有子網路的](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 帳戶 中的 中。
+ 盡可能使用 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要複製此模式的儲存庫，請在本機工作站中執行下列命令：<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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製 `ASC-Datasets`目錄。 | 若要將`ASC-Datasets`目錄複製到新位置，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製 `ASC-Integration-Flows`目錄。 | 若要將`ASC-Integration-Flows`目錄複製到新位置，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 導覽至 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 導覽至 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 上傳範例 CSV 檔案。 | 若要上傳資料集的範例 CSV 檔案，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 AWS Supply Chain 存取權。 | 若要從 設定 AWS Supply Chain 存取權 AWS 管理主控台，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 觸發整合流程資源的銷毀工作流程。 | `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 導覽至 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 導覽至 `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_tw/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>

此解決方案可以透過 提供的預先建置儀表板 AWS Supply Chain 或與 Amazon Quick Sight 的自訂整合，複寫更多資料集，並查詢以供進一步分析。此外，您可以使用 Amazon Q 來詢問與 AWS Supply Chain 執行個體相關的問題。

**使用 AWS Supply Chain Analytics 分析資料**

如需設定 AWS Supply Chain Analytics 的說明，請參閱 AWS Supply Chain 文件中的[設定 AWS Supply Chain Analytics](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/setting_analytics.html)。

此模式示範了建立**行事曆**和 **Outbound\$1Order\$1Line** 資料集。若要建立使用這些資料集的分析，請使用下列步驟：

1. 若要分析資料集，請使用**季節性分析**儀表板。若要新增儀表板，請遵循 AWS Supply Chain 文件中[預先建置儀表板](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/prebuilt_dashboards.html)中的步驟。

1. 選擇儀表板以查看以行事曆資料和外撥訂單行資料的範例 CSV 檔案為基礎的分析。

儀表板會根據資料集的擷取資料，提供多年來的需求洞察。您可以進一步指定 ProductID、CustomerID、年份和其他參數進行分析。

**使用 Amazon Q 詢問與 AWS Supply Chain 執行個體相關的問題**

[Amazon Q in AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/qinasc.html) 是互動式生成式 AI 助理，可協助您更有效率地操作供應鏈。Amazon Q 可以執行下列動作：
+ 分析資料湖中的 AWS Supply Chain 資料。
+ 提供營運和財務洞察。
+ 回答您的立即供應鏈問題。

如需使用 Amazon Q 的詳細資訊，請參閱 AWS Supply Chain 文件中的在 [中啟用 AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/enabling_QinASC.html) Amazon Q 和在 [中使用 Amazon Q AWS Supply Chain](https://docs.aws.amazon.com/aws-supply-chain/latest/userguide/using_QinASC.html)。

# 自動化 AWS 資源評估
<a name="automate-aws-resource-assessment"></a>

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

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

此模式描述使用 [AWS 雲端開發套件 (AWS CDK)](https://docs.aws.amazon.com/cdk/v2/guide/home.html) 設定資源評估功能的自動化方法。透過使用此模式，營運團隊會以自動化方式收集資源稽核詳細資訊，並在單一儀表板上檢視 AWS 帳戶中部署的所有資源詳細資訊。這在下列使用案例中很有用：
+ 將基礎設施識別為程式碼 (IaC) 工具，並隔離由不同 IaC 解決方案建立的資源，例如 [HashiCorp Terraform](https://www.terraform.io/)、[AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)、AWS CDK 和 [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)
+ 擷取資源稽核資訊

此解決方案也會協助領導團隊從單一儀表板取得 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 Access Management (IAM) 角色和許可
+ 建立的 [Amazon Quick 帳戶](https://docs.aws.amazon.com/quicksight/latest/user/signing-up.html)可存取 [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 和 [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html)
+ 已安裝 AWS CDK 2.55.1 版或更新版本 
+ 已安裝 [Python](https://www.python.org/downloads/release/python-390/) 3.9 版或更新版本

**限制**
+ 此解決方案會部署到單一 AWS 帳戶。
+ 除非 AWS CloudTrail 已設定並將資料儲存在 S3 儲存貯體中，否則解決方案不會追蹤部署之前發生的事件。

**產品版本**
+ AWS CDK 2.55.1 版或更新版本
+ Python 3.9 版或更新版本

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

**目標技術堆疊**
+ Amazon Athena
+ AWS CloudTrail
+ AWS Glue
+ AWS Lambda
+ Amazon Quick Sight
+ Amazon S3

**目標架構**

AWS CDK 程式碼會部署在 AWS 帳戶中設定資源評估功能所需的所有資源。下圖顯示將 CloudTrail 日誌傳送至 AWS Glue、Amazon Athena 和 Quick Sight 的程序。

![\[在六個步驟中，使用 AWS Glue、Amazon Athena 和 Amazon QuickSight 進行 AWS 資源評估。 Amazon Athena Amazon QuickSight\]](http://docs.aws.amazon.com/zh_tw/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. AWS Glue 爬蟲程式是在 S3 儲存貯體中篩選的資料上設定，以在 AWS Glue Data Catalog 資料表中建立結構描述。

1. 篩選的資料已準備好供 Amazon Athena 查詢。

1. Quick Sight 會存取查詢的資料以進行視覺化。

**自動化和擴展**
+ 如果 AWS Organizations 中有全組織的 CloudTrail 追蹤，此解決方案可以從一個 AWS 帳戶擴展到多個 AWS 帳戶。 AWS Organizations 透過在組織層級部署 CloudTrail，您也可以使用此解決方案來擷取所有必要資源的資源稽核詳細資訊。
+ 此模式使用 AWS 無伺服器資源來部署解決方案。

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

**AWS 服務**
+ [Amazon Athena](https://docs.aws.amazon.com/athena/latest/ug/what-is.html) 是一種互動式查詢服務，可協助您使用標準 SQL 直接在 Amazon S3 中分析資料。
+ [AWS 雲端開發套件 (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 區域的整個生命週期中管理這些資源。
+ [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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在本機電腦上複製儲存庫。 | 若要複製儲存庫，請執行 `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_tw/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps，DevOps 工程師 | 

### 在本機電腦上設定 AWS 登入資料
<a name="set-up-aws-credentials-on-your-local-machine"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 匯出要部署堆疊之帳戶和區域的變數。 | 若要使用環境變數為 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在帳戶中部署資源。 | 若要使用 AWS CDK 在 AWS 帳戶中部署資源，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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)中建立和更新分割區。 AWS Glue 在輸出 S3 儲存貯體中提供資料後，請使用下列步驟執行 AWS Glue 爬蟲程式並建立資料目錄資料表結構描述以進行測試：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html) | AWS DevOps，DevOps 工程師 | 
| 建立 Quick Sight 儀表板。 | 若要建立 Quick Sight 儀表板和分析範例，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-aws-resource-assessment.html)如需詳細資訊，請參閱在 [Amazon Quick Sight 中啟動分析](https://docs.aws.amazon.com/quicksight/latest/user/creating-an-analysis.html)和在 [Amazon Quick 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 移除 AWS 資源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 監控並清除手動建立的資源。 | （選用） 如果您的組織有使用 IaC 工具建立資源的合規要求，您可以使用 AWS 資源評估工具自動化來擷取手動佈建的資源，以實現合規。您也可以使用 工具將資源匯入 IaC 工具，或重新建立資源。若要監控手動佈建的資源，請執行下列高階任務：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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*

## 總結
<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) 系統和非 HA 系統。

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

**先決條件**
+ 作用中的 AWS 帳戶
+ 包含所有 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)
  + **讀取和寫入許可：**Amazon S3、Amazon Elastic Compute Cloud (Amazon EC2)、Amazon Elastic File System (Amazon EFS)、IAM、Amazon CloudWatch、Amazon DynamoDB
+ Route 53 [私有託管區域](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-private.html)
+ 在 Amazon Marketplace 中使用 [HA 和更新服務 8.2 Amazon Machine Image (AMI) 的 Red Hat Enterprise Linux for SAP](https://aws.amazon.com/marketplace/pp/prodview-5grz5a5thx7c2) 訂閱
+ [AWS KMS 客戶受管金鑰](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingKMSEncryption.html#aws-managed-customer-managed-keys)
+ [安全殼層 (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 的主機名稱 （主機名稱很可能是 **localhost**) 在連接埠 22 上進行 SSH 連線
+ HashiCorp 的 [Vagrant](https://www.vagrantup.com/) 已安裝並設定
+ 已安裝並設定 [VirtualBox](https://www.virtualbox.org/) by 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 或更新版本

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

下圖顯示使用開放原始碼工具自動化 AWS 帳戶中 SAP 系統安裝的範例工作流程：

![\[工作流程範例使用開放原始碼工具，自動在 AWS 帳戶中安裝 SAP 系統。\]](http://docs.aws.amazon.com/zh_tw/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 EC2 執行個體上安裝 SAP S/4HANA 1909 資料庫、ASCS 執行個體和包含所有已定義先決條件的 PAS 執行個體。

**注意**  
此模式中的範例設定會自動在您的 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 Elastic Compute Cloud (Amazon EC2)](https://docs.aws.amazon.com/ec2/?id=docs_gateway) 在 AWS 雲端中提供可擴展的運算容量。您可以視需要啟動任意數量的虛擬伺服器，並快速向上或向下擴展。
+ [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) 可協助您建立和控制密碼編譯金鑰，以保護資料。
+ [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/) 是一種開放原始碼自動化伺服器，可讓開發人員建置、測試和部署其軟體。

**Code**

此模式的程式碼可在 GitHub [aws-install-sap-with-jenkins-ansible](https://github.com/aws-samples/aws-install-sap-with-jenkins-ansible) 儲存庫中使用。

## 史詩
<a name="install-sap-systems-automatically-by-using-open-source-tools-epics"></a>

### 設定先決條件
<a name="configure-the-prerequisites"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將您的 SAP 媒體檔案新增至 Amazon S3 儲存貯體。 | [建立包含所有 SAP 媒體檔案的 Amazon S3 儲存貯](https://docs.aws.amazon.com/AmazonS3/latest/userguide/create-bucket-overview.html)體。請務必遵循啟動精靈文件中適用於 **S/4HANA** 的 AWS Launch Wizard 資料夾階層。 [https://docs.aws.amazon.com/launchwizard/latest/userguide/launch-wizard-sap-software-install-details.html](https://docs.aws.amazon.com/launchwizard/latest/userguide/launch-wizard-sap-software-install-details.html) | 雲端管理員 | 
| 安裝 VirtualBox。 | 安裝和設定 [VirtualBox](https://www.virtualbox.org/) by Oracle。 | DevOps 工程師 | 
| 安裝 Vagrant。 | 安裝和設定 HashiCorp 的 [Vagrant](https://www.vagrantup.com/)。 | DevOps 工程師 | 
| 設定您的 AWS 帳戶。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 從 GitHub 複製程式碼儲存庫。 | 在 GitHub 上複製 [aws-install-sap-with-jenkins-ansible](https://github.com/aws-samples/aws-install-sap-with-jenkins-ansible) 儲存庫。 | 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_tw/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_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/install-sap-systems-automatically-by-using-open-source-tools.html)如需管道步驟的資訊，請參閱 AWS 部落格上的了解[使用開放原始碼工具自動化 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 for SAP – SAP 安裝：從 2 個月到 2 小時](https://videos.itrevolution.com/watch/707351918/) (DevOps Enterprise Summit Video Library)

# 使用 AWS CDK 自動化 AWS Service Catalog 產品組合和產品部署
<a name="automate-aws-service-catalog-portfolio-and-product-deployment-by-using-aws-cdk"></a>

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

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

AWS Service Catalog 可協助您集中管理已核准在組織的 AWS 環境中使用的 IT 服務或*產品的*目錄。產品組合稱為*產品組合*，而產品組合也包含組態資訊。使用 AWS Service Catalog，您可以為組織中的每種類型的使用者建立自訂產品組合，然後授予適當產品組合的存取權。這些使用者可以從產品組合中快速部署所需的任何產品。

如果您有複雜的聯網基礎設施，例如多區域和多帳戶架構，建議您在單一中央帳戶中建立和管理 Service Catalog 產品組合。此模式說明如何使用 AWS Cloud Development Kit (AWS CDK) 在中央帳戶中自動建立 Service Catalog 產品組合、授予最終使用者對它們的存取權，然後選擇性地在一或多個目標 AWS 帳戶中佈建產品。此ready-to-use型解決方案會在來源帳戶中建立 Service Catalog 產品組合。它也可以選擇性地使用 AWS CloudFormation 堆疊在目標帳戶中佈建產品，並協助您為產品設定 TagOptions：
+ **AWS CloudFormation StackSets** – 您可以使用 StackSets 跨多個 AWS 區域和帳戶啟動 Service Catalog 產品。在此解決方案中，您可以選擇在部署此解決方案時自動佈建 產品。如需詳細資訊，請參閱[使用 AWS CloudFormation StackSets](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/using-stacksets.html) (Service Catalog 文件） 和 [StackSets 概念](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-concepts.html) (CloudFormation 文件）。
+ **TagOption 程式庫** – 您可以使用 TagOption 程式庫來管理佈建產品的標籤。*TagOption* 是在 AWS Service Catalog 中管理的鍵/值對。它不是 AWS 標籤，但可做為根據 TagOption 建立 AWS 標籤的範本。如需詳細資訊，請參閱 [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>

**先決條件**
+ 您要用作來源帳戶的作用中 AWS 帳戶，用於管理 Service Catalog 產品組合。
+ 如果您使用此解決方案在一或多個目標帳戶中佈建產品，則目標帳戶必須已存在且處於作用中狀態。
+ 存取 AWS Service Catalog、AWS CloudFormation 和 AWS IAM 的 AWS Identity and Access Management (IAM) 許可。 AWS Service Catalog AWS CloudFormation

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

## Architecture
<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_tw/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 管理員**角色，並部署您在 **config.json **檔案中定義的 AWS CloudFormation 堆疊集。

1. 在目標帳戶中，StackSets 會擔任 **StackSet 執行**角色並佈建產品。

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

**AWS 服務**
+ [AWS 雲端開發套件 (AWS CDK)](https://docs.aws.amazon.com/cdk/latest/guide/home.html) 是一種軟體開發架構，可協助您在程式碼中定義和佈建 AWS 雲端基礎設施。
+ [AWS CDK Toolkit](https://docs.aws.amazon.com/cdk/latest/guide/cli.html) 是命令列雲端開發套件，可協助您與 AWS CDK 應用程式互動。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 可協助您設定 AWS 資源、快速且一致地佈建資源，以及在整個 AWS 帳戶和區域的生命週期中管理這些資源。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 可透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [AWS Service Catalog](https://docs.aws.amazon.com/servicecatalog/latest/adminguide/introduction.html) 可協助您集中管理針對 AWS 核准的 IT 服務目錄。最終使用者可在機構所設的限制範圍內，迅速地只部署自己需要且經核准的 IT 服務。

**程式碼儲存庫**

此模式的程式碼可在 [aws-cdk-servicecatalog-automation](https://github.com/aws-samples/aws-cdk-servicecatalog-automation.git) 儲存庫的 GitHub 上取得。程式碼儲存庫包含下列檔案和資料夾：
+ **cdk-sevicecatalog-app** – 此資料夾包含此解決方案的 AWS CDK 應用程式。
+ **config** – 此資料夾包含 **config.json** 檔案和 CloudFormation 範本，用於部署 Service Catalog 產品組合中的產品。
+ **config/config.json** – 此檔案包含所有組態資訊。您可以更新此檔案，為您的使用案例自訂此解決方案。
+ **config/templates** – 此資料夾包含 Service Center 產品的 CloudFormation 範本。
+ **setup.sh** – 此指令碼部署解決方案。
+ **uninstall.sh** – 此指令碼會刪除部署此解決方案時建立的堆疊和所有 AWS 資源。

若要使用範例程式碼，請遵循 [Epics](#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 角色應遵循[最低權限 (IAM 文件） 原則](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)。
+ 遵守[使用 AWS CDK 開發雲端應用程式的最佳實務](https://aws.amazon.com/blogs/devops/best-practices-for-developing-cloud-applications-with-aws-cdk/) (AWS 部落格文章）。
+ 遵守 [AWS 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝 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 的完整命令。這會從 GitHub 複製 [aws-cdk-servicecatalog-automation](https://github.com/aws-samples/aws-cdk-servicecatalog-automation) 儲存庫。<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 工程師 | 
| 設定 StackSets 所需的 IAM 角色。 | 如果您使用 StackSets 在目標帳戶中自動佈建產品，則需要設定管理和執行堆疊集的 IAM 角色。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 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_tw/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 應用程式，並佈建 Service Catalog 產品組合和產品，如 **config.json** 檔案中所指定。<pre>sh +x setup.sh</pre> | 應用程式開發人員、DevOps 工程師、AWS DevOps | 
| 驗證部署。 | 執行下列動作來驗證部署是否成功：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| （選用） 移除此解決方案部署的 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 行銷）
+ [搭配 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"
            }
        }
    ]
}
```

# 使用 AWS Service Catalog 和 自動化動態管道管理，以在 Gitflow 環境中部署 Hotfix 解決方案 AWS CodePipeline
<a name="automate-dynamic-pipeline-management-for-deploying-hotfix-solutions"></a>

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

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

此模式解決了管理動態 Hotfix 管道的案例，該管道專門用於將 Hotfix 解決方案安全地部署到生產環境。解決方案是透過使用 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)中所述。

一般而言，會部署 Hotfix 來解決即時環境中報告的關鍵或安全問題，例如生產。應僅將 Hotfix 直接部署到預備和生產環境。預備和生產管道廣泛用於定期開發請求。這些管道無法用來部署 Hotfix，因為品質保證中有持續的功能無法提升為生產。若要釋出 Hotfix，此模式會描述具有下列安全功能的動態、短期管道：
+ **自動建立** – 只要在 AWS CodeCommit 儲存庫中建立 Hotfix 分支，就會自動建立 Hotfix 管道。
+ **存取限制** – 開發人員無法存取 在 Hotfix 程序之外建立此管道。
+ **受控階段** – 管道具有具有特殊存取字符的受控階段，確保提取請求 (PR) 只能建立一次。
+ **核准階段** – 核准階段包含在管道中，以取得相關利益相關者的必要核准。
+ **自動刪除** – 每當在 CodeCommit 儲存庫中將`hotfix`分支與 PR 合併後刪除，就會自動刪除 Hotfix 管道。

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

**先決條件**
+  AWS 帳戶 需要三個作用中的 ，如下所示：
  + 工具帳戶 - 用於持續整合和持續交付 (CI/CD) 設定。
  + 階段帳戶 - 用於使用者接受度測試。
  + 生產帳戶 - 適用於企業最終使用者。
  + （選用） 新增 AWS 帳戶 以做為 QA 帳戶。如果您想要同時使用主要管道設定，包括 QA 和 Hotfix 管道解決方案進行測試，則需要此帳戶。
+ 具有選用條件的 AWS CloudFormation 堆疊，可視需要使用主要管道在 QA 帳戶中部署。透過建立和刪除`hotfix`分支，仍然可以在沒有主要管道設定的情況下測試模式。
+ Amazon Simple Storage Service (Amazon S3) 儲存貯體，用於存放用於建立 Service Catalog 產品的 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)，然後選擇服務的連結。

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

本節中的圖表提供建立生命週期事件和刪除生命週期事件的工作流程。

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


上述用於建立生命週期事件的圖表顯示下列項目：

1. 開發人員會在 CodeCommit 儲存庫中建立`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) 的 Hotfix。

1. 階段環境的部署階段會使用包含 Hotfix 的最新容器映像來更新 Amazon Elastic Container Service (Amazon ECS)。透過建立和執行 CloudFormation 變更集來部署 Hotfix。

1. 在階段環境中成功部署後，會叫用 `prcreation-lambda` Lambda 函數。此 Lambda 函數會建立從`hotfix-*`分支到儲存庫 `develop`和 `main`分支的 PR。Lambda 函數可確保在`hotfix-*`分支中開發的修正會反向合併並包含在後續部署中。

1. 手動核准階段有助於確保必要的利益相關者檢閱修正，並核准在生產環境中部署。

1. 生產環境的部署階段會使用包含 Hotfix 的最新容器映像來更新 Amazon ECS。透過建立和執行 CloudFormation 變更集來部署 Hotfix。

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


上述刪除生命週期事件的圖表顯示下列項目：

1. 開發人員成功將 Hotfix 部署至生產環境後，會刪除`hotfix-*`分支。

1. `hotfix-*` 分支刪除事件是透過 EventBridge 規則擷取。事件詳細資訊包括儲存庫名稱和分支名稱。

1. EventBridge 規則會叫用 Lambda 函數。EventBridge 規則會將事件資訊傳遞給 Lambda 函數做為輸入。

1. Lambda 函數會處理輸入以擷取儲存庫名稱和分支名稱。Lambda 函數會從傳遞的輸入決定個別的 Service Catalog 產品，然後終止產品。

1. Service Catalog 佈建產品終止會刪除先前在該產品中建立的管道和相關資源。

**自動化和擴展**
+ 模式包含 EventBridge 規則和 Lambda 函數，可平行處理多個 Hotfix 分支建立請求。Lambda 函數會為相符的事件規則佈建 Service Catalog 產品。
+ 管道設定是使用 Service Catalog 產品來處理，其提供版本控制功能。解決方案也會自動擴展，以平行處理相同應用程式的多個 Hotfix 開發。
+ [prcreation-lambda](https://github.com/aws-samples/dynamic_hotfix_codepipeline/blob/main/pre-requisites/lambdasetup.yaml#L55) 函數可確保這些 Hotfix 變更也會透過自動提取請求建立合併回 `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) 是一種 linter，可根據 CloudFormation [資源規格檢查 CloudFormation ](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-resource-specification.html)YAML 或 JSON 範本。它也會執行其他檢查，例如檢查資源屬性的有效值，以及是否遵守最佳實務。
+ [cfn-nag](https://github.com/stelligent/cfn_nag) 是一種開放原始碼工具，可透過搜尋模式來識別 CloudFormation 範本中的潛在安全問題。
+ [Docker](https://www.docker.com/) 是一組平台即服務 (PaaS) 產品，可在作業系統層級使用虛擬化在容器中交付軟體。此模式使用 Docker 在本機建置和測試容器映像。
+ [Git](https://git-scm.com/docs) 是開放原始碼的分散式版本控制系統。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [dynamic\$1hotfix\$1codepipeline](https://github.com/aws-samples/dynamic_hotfix_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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要將範例[儲存庫](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_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在工具帳戶中建立 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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 Service Catalog 產品組合和產品。 | 若要設定 Service Catalog 產品組合和產品，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | AWS DevOps | 
| 設定 Lambda 函數。 | 此解決方案使用下列 Lambda 函數來管理 Hotfix 工作流程：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定`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_tw/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | AWS DevOps | 

### 建立 Hotfix-\$1 分支的管道並部署 Hotfix
<a name="create-the-pipeline-for-a-hotfix--branch-and-deploy-the-hotfix"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立`hotfix-*`分支並遞交變更。 | 若要為`hotfix-*`分支建立管道並將 Hotfix 部署到工作負載帳戶，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/automate-dynamic-pipeline-management-for-deploying-hotfix-solutions.html) | AWS DevOps | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除已部署的資源。 | 若要清除先前部署的資源，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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)
+ [連線至 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 映像推送至 Amazon 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、階段和生產環境。

在此設定中，在持續積極開發新功能時，套用 Hotfix 或安全修補程式的速度比平常的部署週期更快是一項挑戰。需要專用程序來處理 Hotfix 或安全請求，以確保即時環境保持正常運作和安全。

不過，如果符合下列條件，您可以使用其他可用的選項，而不需要專用的部署程序：
+ CI/CD 程序配備良好的自動化測試，例如功能測試和end-to-end測試，無需手動測試並防止部署到生產環境的延遲。不過，如果自動化測試未與 CI/CD 程序充分整合，則對開發人員而言，將小型修正推送至生產環境可能會變得複雜且繁瑣。這是因為在 QA 環境中可能有新功能等待核准和簽署。Hotfix 或安全修正無法以直接的方式同時推送至生產環境。
+ 開發團隊會持續將新功能部署到生產環境中，將 Hotfix 或安全修補程式整合到每個新功能的排程部署中。換句話說，生產環境的下一個功能更新包含兩個元件：新增新功能，以及包含修正程式或安全修補程式。不過，如果部署週期不連續，則可能有多個新功能已在 QA 環境中等待核准。然後，管理不同的版本並確保重新套用正確的變更可能會變得複雜且容易出錯。

**注意**  
如果您使用 第 [2 版](https://docs.aws.amazon.com/codepipeline/latest/userguide/pipeline-types.html#:~:text=V2%20type%20pipelines%20have%20the%20same%20structure) AWS CodePipeline ，並在`hotfix`分支上設定適當的觸發條件，您仍然需要專用程序來處理未排程的請求。在第 2 版中，您可以設定推送或提取請求的觸發條件。會根據管道的先前狀態，立即將執行排入佇列或執行。不過，透過專用管道，修正會立即套用至生產環境，確保緊急問題不會延遲解決。

# 自動化刪除 AWS CloudFormation 堆疊和相關聯的資源
<a name="automate-deletion-cloudformation-stacks-associated-resources"></a>

*SANDEEP SINGH 和 Amazon Web Services 的 James Jacob*

## 總結
<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 Elastic Compute Cloud (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 函數，以自動產生 [Amazon CloudWatch Logs ](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)

**限制**
+ 命名慣例用於識別應刪除的資源。此模式中的範例程式碼使用資源名稱的字首，但您可以定義自己的命名慣例。不會識別未使用此命名慣例的資源，也不會隨後刪除。

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

下圖顯示此架構如何識別目標 CloudFormation 堆疊及其相關聯的其他資源。

![\[探索、處理和刪除 CloudFormation 堆疊及其相關聯資源的階段。\]](http://docs.aws.amazon.com/zh_tw/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) 儲存庫、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 服務。

**其他工具**
+ [按一下](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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立收集、預先處理和刪除目標資源的函數。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-deletion-cloudformation-stacks-associated-resources.html) | DevOps 工程師，Python | 

### 建立範例資源
<a name="create-sample-resources"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 CloudFormation 堆疊。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除 CloudFormation 堆疊。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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*

## 總結
<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 版上測試。

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

下列架構圖會反白顯示解決方案 AWS 服務 中使用的 。

![\[自動化 Amazon MWAA 自訂指標擷取的工作流程。\]](http://docs.aws.amazon.com/zh_tw/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 for LiveAnalytics](https://docs.aws.amazon.com/timestream/latest/developerguide/what-is-timestream.html) 是一種快速、可擴展、全受管的專用時間序列資料庫，可讓您輕鬆地每天存放和分析數兆個時間序列資料點。適用於 LiveAnalytics 的 Timestream 也與資料收集、視覺化和機器學習的常用服務整合。在此模式中，它會用來擷取產生的 Amazon MWAA 自訂指標。

**其他工具**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一種基礎設施即程式碼 (IaC) 工具，可協助您使用程式碼來佈建和管理雲端基礎設施和資源。此模式使用 Terraform 模組自動佈建 中的基礎設施 AWS。

**程式碼儲存庫**

此模式的程式碼可在 GitHub 的 [visualize-amazon-mwaa-custom-metrics-grafana](https://github.com/aws-samples/visualize-amazon-mwaa-custom-metrics-grafana) 儲存庫中取得。`stacks/Infra` 資料夾包含下列項目：
+ 所有 AWS 資源的 Terraform 組態檔案
+ `grafana` 資料夾中的 Grafana 儀表板 .json 檔案
+ `mwaa/dags` 資料夾中的 Amazon Managed Workflows for Apache Airflow DAGs 
+ Lambda 程式碼可剖析 .csv 檔案，並將指標存放在 `src` 資料夾中的 Timestream 資料庫
+ `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 基礎設施。 | 若要部署解決方案基礎設施，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html) | AWS DevOps | 

### 驗證部署的基礎設施資源
<a name="validate-the-deployed-infrastructure-resources"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證 Amazon MWAA 環境。 | 若要驗證 Amazon MWAA 環境，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定對 Amazon Managed Grafana 工作區的存取。 | Terraform 指令碼建立了所需的 Amazon Managed Grafana 工作區、儀表板和指標頁面。若要設定存取權以便您可以檢視，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢視 Amazon Managed Grafana 儀表板。 | 若要檢視擷取至 Amazon Managed Grafana 工作區的指標，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/automate-ingestion-and-visualization-of-amazon-mwaa-custom-metrics.html)或者，此儀表板的原始碼可在 [GitHub 儲存庫](https://github.com/aws-samples/visualize-amazon-mwaa-custom-metrics-grafana/blob/main/stacks/infra/grafana/dashboard.json)的 `stacks/infra/grafana` 資料夾中的 `dashboard.json` 檔案中取得。 | AWS DevOps | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 暫停 Amazon MWAA DAG 執行。 | 若要暫停 DAG 執行，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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)
+ [設定 Amazon Managed Grafana 使用 Okta](https://docs.aws.amazon.com/grafana/latest/userguide/AMG-SAML-providers-okta.html)
+ [AWS IAM Identity Center 搭配 Amazon Managed Grafana 工作區使用](https://docs.aws.amazon.com/grafana/latest/userguide/authentication-in-AMG-SSO.html)
+ [在 Amazon MWAA 上使用 DAG](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?controls=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/Z4JHxl2xpOg?controls=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 中產生的警示觸發這些平台中的事件和通知。此外，此模式提供 [GitHub 儲存庫](https://github.com/aws-samples/visualize-amazon-mwaa-custom-metrics-grafana)來建立 AWS 資源。您可以進一步將此程式碼與您的基礎設施部署工作流程整合。

# 使用 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*

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

在持續整合和持續交付 (CI/CD) 程序中，您可能想要自動將應用程式部署到所有現有的 AWS 帳戶，以及您在 AWS Organizations 中新增至組織的新帳戶中。當您為此需求建構 CI/CD 解決方案時，AWS CloudFormation 的[委派堆疊集管理員](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-orgs-delegated-admin.html)功能非常有用，因為它透過限制對管理帳戶的存取來啟用一層安全性。不過，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 範本來啟用此功能。

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

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


CI/CD 部署管道的此架構會處理下列項目：
+ 將堆疊集部署責任委派給專用 CI/CD 帳戶，做為應用程式部署的堆疊集管理員，以限制直接存取管理帳戶。
+ 使用服務受管許可模型，每當在 OU 下建立新帳戶並映射時，就會自動部署應用程式。
+ 確保環境層級所有帳戶的應用程式版本一致性。
+ 在儲存庫和管道層級使用多個核准階段，為部署的應用程式提供額外的安全與控管層。
+ 使用 CodeBuild 中的自訂建置部署指令碼來自動部署或移除堆疊集和堆疊執行個體，以克服 CodePipeline 目前的限制。 CodeBuild 如需自訂指令碼實作之 API 呼叫的流程控制和階層說明，請參閱[其他資訊](#automate-stack-set-deployment-by-using-aws-codepipeline-and-aws-codebuild-additional)一節。
+ 為開發、測試和生產環境建立個別堆疊集。此外，您可以建立堆疊集，在每個階段結合多個 OUs 和區域。例如，您可以在開發部署階段中結合沙盒和開發 OUs。
+ 支援將應用程式部署至帳戶子集或 OUs 清單或從中排除。

**自動化和擴展**

您可以使用此模式隨附的程式碼，為您的應用程式建立 AWS CodeCommit 儲存庫和程式碼管道。然後，您可以將這些堆疊集部署到 OU 層級的多個帳戶。此程式碼也會自動化 Amazon Simple Notification 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 Elastic Compute Cloud (Amazon EC2) 或內部部署執行個體、AWS Lambda 函數或 Amazon Elastic Container Service (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 Notification Service (Amazon SNS)](https://docs.aws.amazon.com/sns/latest/dg/welcome.html) 可協助您協調和管理發佈者和用戶端之間的訊息交換，包括 Web 伺服器和電子郵件地址。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [automated-code-pipeline-stackset-deployment](https://github.com/aws-samples/automated-code-pipeline-stackset-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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟用管理帳戶中的所有功能。 | 遵循 [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 帳戶註冊為委派堆疊集管理員。如需說明，請參閱 [AWS 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製程式碼儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製應用程式儲存庫。 | 您先前使用的 CI/CD 管道範本會建立範例應用程式儲存庫和程式碼管道。若要複製和驗證儲存庫：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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_tw/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>


| 問題 | 解決方案 | 
| --- | --- | 
| 部署失敗，但有例外：*將範本參數檔案的名稱變更為 <application name>-parameter-<evn>.json，不允許預設名稱* | CloudFormation 範本參數檔案必須遵循指定的命名慣例。更新參數檔案名稱，然後再試一次。 | 
| 部署失敗，但有例外：*將 CloudFormation 範本的名稱變更為不允許 <application name>.yml、預設 template.yml 或 template.yaml* | CloudFormation 範本名稱必須遵循指定的命名慣例。更新檔案名稱，然後再試一次。 | 
| 部署失敗，但有例外：*找不到 \$1environment name\$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-deployment](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_tw/prescriptive-guidance/latest/patterns/images/pattern-img/a5c47de7-9039-415d-a9e5-9de0d4c3a260/images/1898883a-62b7-40c2-8f08-9f2a9dda8404.png)


**部署組態檔案範例**

**建立新的堆疊集**

下列部署組態檔案會在`us-east-1`三個 OUs `sample-stack-set` 的 AWS 區域中建立新的堆疊集，稱為 。

```
{
     "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 區域**

如果您部署上一個範例中顯示的組態，而且想要將堆疊集部署到開發環境中兩個 OUs ( 和 `us-east-2`) 的其他 AWS 區域 (`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 `us-east-1`的 AWS 區域移除堆疊執行個體。   

```
{
     "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"
 }
```

****從部署中排除帳戶**

 下列部署組態檔案`dev-org-unit-1`會從部署中排除`111122223333`屬於 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"], 
                                        "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 中的三個帳戶 (`111122223333``444455556666`、 和 `777788889999`)`dev-org-unit-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"], 
                                        "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"
 }
```

# 使用 Cloud Custodian 和 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*

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

您可以將 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體與 AWS Systems Manager 整合，以自動化操作任務並提供更高的可見性和控制。若要與 Systems Manager 整合，EC2 執行個體必須具有已安裝的 [AWS Systems Manager Agent (SSM Agent)](https://docs.aws.amazon.com/systems-manager/latest/userguide/ssm-agent.html) 和連接到其執行個體描述檔的 `AmazonSSMManagedInstanceCore` AWS Identity and Access Management (IAM) 政策。 

不過，如果您想要確保所有 EC2 執行個體描述檔都已連接`AmazonSSMManagedInstanceCore`政策，則更新沒有執行個體描述檔的新 EC2 執行個體，或沒有執行個體描述檔但沒有`AmazonSSMManagedInstanceCore`政策的 EC2 執行個體時，可能會面臨挑戰。跨多個 Amazon Web Services (AWS) 帳戶和 AWS 區域新增此政策可能也很困難。

此模式透過在您的 AWS 帳戶中部署三個 [Cloud Custodian](https://cloudcustodian.io/) 政策，協助解決這些挑戰：
+ 第一個 Cloud Custodian 政策會檢查是否有具有執行個體描述檔但沒有`AmazonSSMManagedInstanceCore`政策的現有 EC2 執行個體。然後連接`AmazonSSMManagedInstanceCore`政策。 
+ 第二個 Cloud Custodian 政策會檢查沒有執行個體描述檔的現有 EC2 執行個體，並新增已連接`AmazonSSMManagedInstanceCore`政策的預設執行個體描述檔。
+ 第三個 Cloud Custodian 政策會在您的帳戶中建立 [AWS Lambda 函數](https://cloudcustodian.io/docs/aws/lambda.html)，以監控 EC2 執行個體和執行個體描述檔的建立。這可確保在建立 EC2 執行個體時自動連接`AmazonSSMManagedInstanceCore`政策。

此模式使用 [AWS DevOps](https://aws.amazon.com/devops/) 工具，將 Cloud Custodian 政策持續大規模部署至多帳戶環境，而無需佈建個別的運算環境。 

## 先決條件和限制
<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 Command Line Interface (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 雲端開發套件 (AWS CDK) 和 Git)。您可以使用 `devops-cdk-cloudcustodian.zip` 檔案中的 `install-prerequisites.sh` 檔案來****安裝這些工具。****請確定您使用根權限執行此檔案。 

**限制**
+ 雖然此模式可用於生產環境，但請確保所有 IAM 角色和政策都符合您組織的需求和政策。 

**套件版本**
+ 雲端託管人 0.9 版或更新版本
+ TypeScript 3.9.7 版或更新版本
+ Node.js 14.15.4 版或更新版本
+ `npm` 7.6.1 版或更新版本
+ AWS CDK 1.96.0 版或更新版本

## Architecture
<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_tw/prescriptive-guidance/latest/patterns/images/pattern-img/169a7bde-789e-4ebd-b4ca-80eb28ac9927/images/8ec0b6b4-d4b0-42e5-833d-24d1e6098fd9.png)


 

該圖顯示以下工作流程：

1. 雲端託管政策會推送到安全帳戶中的 AWS CodeCommit 儲存庫。Amazon CloudWatch Events 規則會自動啟動 AWS CodePipeline 管道。

1. 管道會從 CodeCommit 擷取最新的程式碼，並將其傳送至 AWS CodeBuild 處理的持續整合和持續交付 (CI/CD) 管道的持續整合部分。

1. CodeBuild 會執行完整的 DevSecOps 動作，包括 Cloud Custodian 政策的政策語法驗證，並在`--dryrun`模式下執行這些政策，以檢查識別哪些資源。

1. 如果沒有錯誤，下一個任務會提醒管理員檢閱變更，並核准成員帳戶中的部署。

**技術堆疊**
+ AWS CDK
+ CodeBuild：
+ CodeCommit：
+ CodePipeline
+ IAM
+ Cloud Custodian 

**自動化和擴展**

除了使用 AWS CloudFormation 堆疊部署 AWS 資源之外 CodeBuild ，AWS CDK 管道模組還會佈建使用 CodePipeline 協調建置和測試原始程式碼的 CI/CD 管道。您可以針對組織中的所有成員帳戶和區域使用此模式。您也可以擴展`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 Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可讓您使用命令列 shell 中的命令與 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) 是一種版本控制服務，可用來私下存放和管理資產。
+ [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 資源的存取。
+ [Cloud Custodian](https://cloudcustodian.io/) 是一種工具，可將大多數組織用來管理公有雲端帳戶的數十種工具和指令碼統一為單一開放原始碼工具。
+ [Node.js](https://nodejs.org/en/) 是建置在 Google Chrome 的 V8 JavaScript 引擎上的 JavaScript 執行期。 JavaScript 

**Code**

如需此模式中使用的模組、帳戶函數、檔案和部署命令的詳細清單，請參閱 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 CodeCommit 儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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)。 AWS CodeCommit  | 開發人員 | 
| 安裝必要的工具。 | 使用 `install-prerequisites.sh` 檔案在 Amazon Linux 上安裝所有必要的工具。這不包含 AWS CLI，因為它已預先安裝。如需詳細資訊，請參閱 [AWS CDK 文件中 AWS CDK 入門](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html)的[先決條件](https://docs.aws.amazon.com/cdk/latest/guide/getting_started.html#getting_started_prerequisites)一節。 | 開發人員 | 
| 安裝所需的 AWS CDK 套件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 更新所需的變數。 | 在 CodeCommit 儲存庫的根資料夾中開啟 `vars.py` 檔案，並更新下列變數：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 的 Cloud Custodian 組態檔案範例：<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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 提升安全帳戶。 | 執行下列命令`deploy_account`，以`cloudcustodian_stack`應用程式引導 ：<pre>cdk bootstrap -a 'python3 <br />cloudcustodian/cloudcustodian_stack.py</pre> | 開發人員 | 
| 選項 1 - 自動引導成員帳戶。 | 如果 `cdk_bootstrap_member_accounts` 變數`True`在 `vars.py` 檔案中設定為 ，則 `member_accounts`變數中指定的帳戶會自動由管道引導。如有需要，您可以使用可從安全帳戶擔任的 `*cdk_bootstrap_role*` IAM 角色進行更新，而且該角色具有啟動 AWS CDK 所需的許可。新增至`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>請務必使用您可以從安全帳戶取得的 IAM 角色名稱，以及具有啟動 AWS CDK 所需許可的 `{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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在成員帳戶中建立 IAM 角色。 | 執行下列命令來部署`member_account_roles_stack`堆疊，並在成員帳戶中建立 IAM 角色：<pre>cdk deploy --all -a 'python3 cloudcustodian/member_account_roles_stack.py' --require-approval never</pre> | 開發人員 | 
| 部署 Cloud Custodian 管道堆疊。 | 執行下列命令來建立部署到安全帳戶的 Cloud Custodian `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*

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

此模式說明如何自動建立持續整合和持續交付 (CI/CD) 管道，以及在 Amazon Elastic Container Service (Amazon ECS) 上建置和部署微服務的基礎基礎設施。如果您想要設定proof-of-concept CI/CD 管道，向組織展示 CI/CD、微服務和 DevOps 的優勢，您可以使用此方法。您也可以使用此方法建立初始 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 雲端開發套件 (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 CodePipeline、AWS CodeBuild、CodeCommit、Amazon Elastic Container Registry (Amazon ECR)、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 版進行測試。

## Architecture
<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_tw/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 映像並將其推送至 Amazon 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 可協助開發人員封裝、運送和執行任何應用程式，做為輕量、可攜式且自給自足的容器。

**Code**

此模式的程式碼可在 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 AWS CDK 的工作目錄。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立共用基礎設施。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/automatically-build-ci-cd-pipelines-and-amazon-ecs-clusters-for-microservices-using-aws-cdk.html)請務必記錄兩個 VPCs IDs 和兩個 VPCs 中預設安全群組的安全群組 IDs。 | AWS DevOps、雲端基礎設施 | 

### 為微服務建立 CI/CD 管道
<a name="create-a-ci-cd-pipeline-for-a-microservice"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立微服務的基礎設施。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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 動作和 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*

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

此模式說明如何建立可重複使用的 GitHub 工作流程來建置 Dockerfile，並將產生的映像推送至 Amazon Elastic Container Registry (Amazon ECR)。模式會使用 Terraform 和 GitHub Actions 自動化 Dockerfiles 的建置程序。這可將人為錯誤的可能性降至最低，並大幅縮短部署時間。

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) Terraform 第 1 版或更新版本。
+ [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`。如果未設定，則會停用狀態鎖定。
+ AWS Identity and Access Management (IAM) 角色，具有為 Terraform 設定 Amazon S3 後端的許可。如需組態指示，請參閱 [Terraform 文件](https://developer.hashicorp.com/terraform/language/settings/backends/s3#assume-role-configuration)。

**限制 **

此可重複使用的程式碼已僅使用 GitHub 動作進行測試。

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

**目標技術堆疊**
+ Amazon ECR 儲存庫
+ GitHub Actions
+ Terraform

**目標架構**

![\[建立可重複使用 GitHub 工作流程的工作流程，以建置 Dockerfile 並將映像推送至 Amazon ECR。\]](http://docs.aws.amazon.com/zh_tw/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 Actions](https://docs.github.com/en/actions) 已整合至 GitHub 平台，協助您在 GitHub 儲存庫中建立、共用和執行工作流程。您可以使用 GitHub 動作來自動化任務，例如建置、測試和部署程式碼。
+ [Terraform](https://developer.hashicorp.com/terraform/intro) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署基礎設施。

**程式碼儲存庫**

此模式的程式碼可在 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>
+ 如需撰寫 Dockerfiles 的最佳實務，請參閱 [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，這項技術可讓您透過私有 IP 地址私密存取 Amazon ECR APIs。對於使用 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 OpenID Connect。 | 建立 OpenID Connect (OIDC) 供應商。您將針對此動作中使用的 IAM 角色，使用信任政策中的提供者。如需說明，請參閱 GitHub 文件[中的在 Amazon Web Services 中設定 OpenID Connect](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)。 | 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 自訂啟動 Docker 工作流程的事件。 | 此解決方案的工作流程位於 [workflow.yaml。](https://github.com/aws-samples/docker-ecr-actions-workflow/blob/main/.github/workflows/workflow.yaml)此指令碼目前設定為在收到`workflow_dispatch`事件時部署資源。您可以將事件變更為 ，`workflow_call`並從另一個父工作流程呼叫工作流程，以自訂此組態。 | DevOps 工程師 | 
| 自訂工作流程。 | [workflow.yaml](https://github.com/aws-samples/docker-ecr-actions-workflow/blob/main/.github/workflows/workflow.yaml) 檔案設定為建立動態、可重複使用的 GitHub 工作流程。您可以編輯此檔案來自訂預設組態，或者如果您使用`workflow_dispatch`事件手動啟動部署，則可以從 GitHub Actions 主控台傳遞輸入值。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-and-push-docker-images-to-amazon-ecr-using-github-actions-and-terraform.html) | DevOps 工程師 | 
| 部署 Terraform 範本。 | 工作流程會根據您設定的 GitHub 事件，自動部署建立 Amazon ECR 儲存庫的 Terraform 範本。這些範本在 [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 CodePipeline 和 AWS Device Farm 建置和測試 iOS 應用程式
<a name="build-and-test-ios-apps-with-aws-codecommit-aws-codepipeline-and-aws-device-farm"></a>

*Abdullahi Olaoye，Amazon Web Services*

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

此模式概述了建立持續整合和持續交付 (CI/CD) 管道的步驟，該管道使用 AWS CodePipeline 在 AWS 上的實際裝置上建置和測試 iOS 應用程式。模式使用 AWS CodeCommit 來存放應用程式碼、Jenkins 開放原始碼工具來建置 iOS 應用程式，以及 AWS Device Farm 來測試實際裝置上建置的應用程式。這三個階段會使用 AWS CodePipeline 在管道中協調在一起。

此模式是以 [AWS DevOps 部落格上的使用 AWS DevOps 和行動服務建置和測試 iOS 和 iPadOS 應用程式](https://aws.amazon.com/blogs/devops/building-and-testing-ios-and-ipados-apps-with-aws-devops-and-mobile-services/)文章為基礎。 DevOps 如需詳細說明，請參閱部落格文章。

## 先決條件和限制
<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/)version 11.3 （在建置伺服器上安裝和設定）
+ 在工作站上安裝[https://docs.aws.amazon.com/cli/latest/userguide/install-cliv1.html](https://docs.aws.amazon.com/cli/latest/userguide/install-cliv1.html)和[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html) AWS Command Line Interface (AWS CLI)
+ [Git](https://git-scm.com/docs) 的基本知識

**限制**
+ 應用程式建置伺服器必須執行 macOS。
+ 建置伺服器必須具有公有 IP 地址，因此 CodePipeline 可以遠端連線到它以啟動建置。

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

**來源技術堆疊**
+ 內部部署 iOS 應用程式建置程序，涉及在實體裝置上使用模擬器或手動測試

**目標技術堆疊**
+ 用於儲存應用程式原始碼的 AWS CodeCommit 儲存庫
+ 使用 Xcode 建置應用程式的 Jenkins 伺服器
+ 用於在實際裝置上測試應用程式的 AWS Device Farm 裝置集區

**目標架構**

當使用者遞交變更至來源儲存庫時，管道 (AWS CodePipeline) 會從來源儲存庫擷取程式碼、啟動 Jenkins 組建，並將應用程式程式碼傳遞給 Jenkins。在建置之後，管道會擷取建置成品，並啟動 AWS Device Farm 任務，以針對裝置集區測試應用程式。

 

![\[CI/CD 管道使用 AWS CodePipeline 在實際裝置上建置和測試 iOS 應用程式。\]](http://docs.aws.amazon.com/zh_tw/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) 是一種應用程式測試服務，可讓您在各種桌面瀏覽器和真實行動裝置中測試 Web 和行動應用程式，藉此改善其品質，而無需佈建和管理任何測試基礎設施。
+ [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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在執行 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 伺服器上，Jenkins 才能與 AWS CodePipeline 服務互動。 | DevOps | 
| 建立 Jenkins 自由樣式專案。 | 在 Jenkins 中，建立自由樣式專案。設定專案以指定觸發條件和其他建置組態選項。 | DevOps | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Device Farm 專案。 | 開啟 AWS Device Farm 主控台。建立專案和裝置集區以進行測試。如需說明，請參閱部落格文章。 | 開發人員 | 

### 設定來源儲存庫
<a name="configure-the-source-repository"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 CodeCommit 儲存庫。 | 建立儲存來源碼的儲存庫。 | DevOps | 
| 將您的應用程式程式碼遞交至儲存庫。 | 連線至您建立的 CodeCommit 儲存庫。將程式碼從本機機器推送至儲存庫。 | DevOps | 

### 設定管道
<a name="configure-the-pipeline"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 AWS CodePipeline 中建立管道。 | 開啟 AWS CodePipeline 主控台，並建立管道。管道會協調 CI/CD 程序的所有階段。如需說明，請參閱 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 | 
| 將測試階段新增至管道。 | 若要新增測試階段並將其與 AWS Device Farm 整合，請編輯管道。 | DevOps | 
| 啟動管道。 | 若要啟動管道和 CI/CD 程序，請選擇**釋出變更**。 | DevOps | 

### 檢視應用程式測試結果
<a name="view-application-test-results"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢閱測試結果。 | 在 AWS Device Farm 主控台中，選取您建立的專案，並檢閱測試結果。主控台會顯示每個測試的詳細資訊。 | 開發人員 | 

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

**此模式的Step-by-step說明**
+ [使用 AWS DevOps 和行動服務建置和測試 iOS 和 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*

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

憑證型交互傳輸層安全 (TLS) 是選用的 TLS 元件，可在伺服器和用戶端之間提供雙向對等身分驗證。透過交互 TLS，用戶端必須在工作階段交涉過程中提供 X.509 憑證。伺服器使用此憑證來識別和驗證用戶端。

相互 TLS 是物聯網 (IoT) 應用程式的常見需求，可用於business-to-business應用程式或標準，例如 [Open Banking](https://docs.aws.amazon.com/wellarchitected/latest/financial-services-industry-lens/open-banking.html)。

此模式說明如何使用 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 Private Certificate Authority (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 叢集。
+ 在 macOS、Linux 或 Windows 上安裝和設定 AWS Command Line Interface (AWS CLI) 1.7 版或更新版本。
+ 安裝並設定為存取 Amazon EKS 叢集的 kubectl 命令列公用程式。如需詳細資訊，請參閱 Amazon EKS 文件中的[安裝 kubectl](https://docs.aws.amazon.com/eks/latest/userguide/install-kubectl.html)。
+ 用來測試應用程式的現有網域名稱系統 (DNS) 名稱。

**限制**
+ 此模式使用自我簽署憑證。我們建議您僅將此模式與測試叢集搭配使用，而不是在生產環境中。

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

![\[為在 Amazon EKS 上執行的應用程式設定交互 TLS 身分驗證\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
|  產生 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 Amazon EKS 叢集中部署 NGINX 輸入控制器。 | 使用下列命令部署 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>請確定服務地址欄位包含 Network Load Balancer 的網域名稱。 | DevOps 工程師 | 

### 在 Amazon EKS 叢集中建立命名空間，以測試相互 TLS
<a name="create-a-namespace-in-the-amazon-eks-cluster-to-test-mutual-tls"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立傳入資源的秘密。 | 執行 folllowing 命令，使用您先前建立的憑證，為 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立指向 NGINX 輸入控制器負載平衡器的 CNAME 記錄。 | 登入 AWS 管理主控台，開啟 Amazon Route 53 主控台，並建立正式名稱 (CNAME) 記錄，`mtls.<your_domain_name>`指向 NGINX 輸入控制器的負載平衡器。如需詳細資訊，請參閱 Route [ Route 53 文件中的使用 Route 53 主控台建立記錄](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-creating.html)。 Route 53  | DevOps 工程師 | 

### 測試應用程式。
<a name="test-the-application"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在沒有憑證的情況下測試交互 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 上使用 Network Load Balancer 搭配 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*

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

此模式提供程式碼範例和步驟， AWS 雲端 以使用 [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) 範本自動在 中建立 [Amazon WorkSpaces 應用程式](https://aws.amazon.com/workspaces/applications/)資源。模式說明如何使用 CloudFormation 堆疊自動建立 WorkSpaces 應用程式應用程式資源，包括映像建置器、映像、機群執行個體和堆疊。您可以使用桌面或應用程式交付模式，將 WorkSpaces 應用程式串流至 HTML5-compliant瀏覽器上的最終使用者。

## 先決條件和限制
<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))。

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

下圖說明如何使用 CloudFormation 範本自動建立 WorkSpaces 應用程式資源。

![\[自動建立 WorkSpaces 應用程式資源的工作流程。\]](http://docs.aws.amazon.com/zh_tw/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. 您可以將 WorkSpaces 應用程式資源部署至 HTML5-compliant瀏覽器上的最終使用者。

## 工具
<a name="automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation-tools"></a>
+ [Amazon WorkSpaces 應用程式](https://docs.aws.amazon.com/appstream2/latest/developerguide/what-is-appstream.html)是一項全受管應用程式串流服務，可讓您從任何地方立即存取桌面應用程式。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)。
+ **在機群部署之前，在映像建置器測試模式中測試應用程式** – 在建立映像和部署至機群之前，一律在映像建置器測試模式中驗證應用程式。測試模式模擬最終使用者在機群執行個體上擁有的有限許可。如需詳細資訊，請參閱 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝自訂軟體並建立映像。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 更新 CloudFormation 範本。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/automate-the-creation-of-appstream-2-0-resources-using-aws-cloudformation.html) | 應用程式擁有者、AWS 系統管理員、Windows Engineer | 

## 疑難排解
<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 應用程式遷移至 Amazon WorkSpaces 應用程式](https://www.youtube.com/watch?v=CIImtS2iVbg)
+ [AWS re：Invent 2018：使用 Amazon WorkSpaces 應用程式安全地交付桌面應用程式 (BAP201)](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*

## 總結
<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 路由到 Amazon CloudWatch 和其他目的地 （例如 [Splunk](https://www.splunk.com/) 或 [Sumo Logic](https://www.sumologic.com/))。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 日誌路由器搭配自訂剖析器，從在 Amazon ECS 上執行的範例 Spring Boot 應用程式將日誌推送至 CloudWatch。然後，您可以使用 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) 帳戶。
+ AWS Command Line Interface (AWS CLI)，安裝在本機機器上並進行設定。
+ 在本機電腦上安裝和設定 Docker。
+ Amazon Elastic Container Registry (Amazon ECR) 上現有的 Spring Boot 型容器化應用程式。 

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

![\[使用 Firelens 日誌路由器，從在 Amazon ECS 上執行的應用程式將日誌推送至 CloudWatch。\]](http://docs.aws.amazon.com/zh_tw/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 Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) – IAM 是一種 Web 服務，可安全地控制對 AWS 服務的存取。
+ [AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) – AWS Command Line Interface (AWS CLI) 是一種開放原始碼工具，可讓您使用命令列 shell 中的命令與 AWS 服務互動。
+ [Docker](https://www.docker.com/) – Docker 是開發、運送和執行應用程式的開放平台。

**Code**

下列檔案會附加至此模式：
+ `customFluentBit.zip` – 包含要新增自訂剖析和組態的檔案。
+ `firelens_policy.json` – 包含用來建立 IAM 政策的政策文件。
+ `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 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_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Amazon ECS 叢集 | 遵循 Amazon ECS 文件中建立叢集的*僅限聯網範本*[一節中的指示，建立 Amazon ECS 叢集](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/create_cluster.html)。請務必選擇**建立 VPC**，為您的 Amazon ECS 叢集建立新的虛擬私有雲端 (VPC)。 | 系統管理員、開發人員 | 

### 設定 Amazon ECS 任務
<a name="set-up-the-amazon-ecs-task"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
|  設定 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 Resource Name (ARN)。 | 系統管理員、開發人員 | 
|  將 IAM 政策連接至 Amazon ECS 任務執行 IAM 角色。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證日誌。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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*

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

此模式利用 GitHub Actions 工作流程，透過標準化 JSON 承載自動化資源佈建，無需手動設定。此自動化管道會管理完整的部署生命週期，並可無縫整合各種前端系統，從自訂 UI 元件到 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)，然後選擇服務的連結。

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

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

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


架構圖顯示下列動作：

1. 使用者向 GitHub 動作提交 JSON 承載，觸發自動化管道。

1. GitHub Actions 管道會根據承載規格，從 Terragrunt 和 Terraform 儲存庫擷取所需的資源程式碼。

1. 管道會使用指定的 AWS 帳戶 ID 擔任適當的 AWS Identity and Access Management (IAM) 角色。然後，管道會將資源部署到目標， AWS 帳戶 並使用帳戶特定的 Amazon S3 儲存貯體和 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 (Amazon VPC)](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html) 可協助您在已定義的虛擬網路中啟動 AWS 資源。此虛擬網路與您在自己的資料中心中操作的傳統網路相似，且具備使用 AWS可擴展基礎設施的優勢。

**其他工具**
+ [GitHub Actions](https://docs.github.com/en/actions) 是與 GitHub 儲存庫緊密整合的持續整合和持續交付 (CI/CD) 平台。您可以使用 GitHub 動作來自動化建置、測試和部署管道。
+ [Terraform](https://www.terraform.io/) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。
+ [Terragrunt](https://terragrunt.gruntwork.io/docs/getting-started/overview/) 是一種協同運作工具，可同時延伸 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 登入資料和敏感資料，以安全存取。
+ 設定 GitHub 動作的 OpenID Connect (OIDC) 提供者以擔任 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 初始化 GitHub 儲存庫。 | 若要初始化 GitHub 儲存庫，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 工程師 | 
| 設定 GitHub 秘密和變數。 | 如需如何在 GitHub 儲存庫中設定儲存庫秘密和變數的指示，請參閱 GitHub 文件中的[為儲存庫建立組態變數](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-variables#creating-configuration-variables-for-a-repository)。設定下列變數：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用 curl 執行管道。 | 若要使用 [curl](https://curl.se/) 執行管道，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 提交清除請求。 | 若要刪除不再需要的資源，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 CloudWatch Logs 監控 CloudTrail 日誌檔案](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 資源**
+ [建立儲存庫分派事件](https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#create-a-repository-dispatch-event)
+ [建立 Webhook](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 角色** - 驗證並擔任 AWS 操作所需的 IAM 角色

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` – 環境 （例如，dev 和 prod)
+ `Suffix` – 資源的其他識別符

`ResourceParameters` 包含資源特定的組態，對應至 Terraform 檔案中定義的變數。任何需要傳遞至 Terraform 模組的自訂變數都應包含在 中`ResourceParameters`。Amazon VPC `vpc_cidr`必須使用 參數。

# 使用 GitHub Actions 建立 Terraform 受管 AWS 基礎設施的自動提取請求
<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*

## 總結
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-summary"></a>

此模式提供自動化公用程式，旨在消除在多個 Terraform 儲存庫中管理變更時涉及的手動重複工作。許多組織使用 Terraform 儲存庫以程式碼 (IaC) 的形式管理其基礎設施，通常具有數百個代表不同環境、服務或團隊的個別儲存庫。大規模管理這些儲存庫會帶來重大的操作挑戰。更新參數、升級模組版本或套用組態變更等例行任務，通常需要每天多次跨許多儲存庫建立和管理提取請求 (PRs)。

即使是簡單的變更，這個重複的手動程序也非常耗時且容易出錯。工程師必須一致地在所有目標儲存庫中套用相同的變更，並製作有意義的 PR 標題和描述。此外，他們通常必須與 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 速率限制時。組織必須仔細平衡自動化與安全登入資料儲存和管理的需求，確保適當的存取控制，同時維持營運效率。
+ **驗證限制**構成另一個值得注意的限制，因為自動化系統驗證業務邏輯和環境特定需求的能力有限。複雜的相依性和跨服務互動通常需要人工監督，因為自動化驗證無法完全擷取所有情境細節和業務規則。
+ 處理大規模基礎設施變更時，會出現規模**和效能**問題。系統必須在 GitHub API 限制內操作，同時同時管理多個儲存庫。跨廣泛基礎設施的資源密集型操作可能會產生需要謹慎管理的效能瓶頸。
+ **整合界限**會限制系統的靈活性，因為它主要設計用於 GitHub 和 Slack 等特定工具。使用不同工具的組織可能需要自訂解決方案，且此模式的工作流程自訂選項僅限於支援的整合點。

## Architecture
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-architecture"></a>

下圖顯示此解決方案的工作流程和元件。

![\[使用 GitHub 動作建立自動提取請求的工作流程。\]](http://docs.aws.amazon.com/zh_tw/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 Actions](https://docs.github.com/en/actions) 是與 GitHub 儲存庫緊密整合的持續整合和持續交付 (CI/CD) 平台。您可以使用 GitHub 動作來自動化建置、測試和部署管道。
+ [HashiCorp Terraform](https://www.terraform.io/) 是一種基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。
+ [Slack](https://slack.com/help/articles/115004071768-What-is-Slack-) 是 Salesforce 產品，是一種採用 AI 技術的對話平台，可提供聊天和視訊協作、自動化沒有程式碼的程序，並支援資訊共用。

**程式碼儲存庫**

此模式的程式碼可在使用 GitHub [動作儲存庫的 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`執行。通訊協定也應該包含遞交前驗證檢查，以及針對重大變更的專用審核環境。這種多層測試方法有助於及早發現問題，並確保基礎設施的穩定性。
+ **監控策略**需要包含全面的提醒機制、詳細的成功/失敗指標追蹤，以及失敗操作的自動重試機制。此策略有助於確保營運可見性，並能夠快速回應任何出現的問題。
+ **組態標準**應強調所有組態的版本控制，維護模組化以實現可重複使用性和可擴展性。清楚的結構描述和範例文件，可協助團隊有效地了解和使用自動化系統。

## 史詩
<a name="create-automated-pull-requests-for-terraform-managed-aws-infrastructure-epics"></a>

### 設定和安裝
<a name="installation-and-setup"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定儲存庫。 | 若要設定儲存庫，請執行下列命令：<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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行飛行前測試。 | 在生產儲存庫上執行組態之前，請務必先測試組態。使用下列命令：<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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用 GitHub Actions UI 執行自動化公用程式。 | 若要使用 GitHub Actions UI 執行自動化公用程式，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-automated-pull-requests-for-terraform-managed-aws-infrastructure.html) | AWS DevOps | 
| （替代） 從命令列執行自動化公用程式。 | 如果您願意，您可以從命令列執行自動化公用程式，而不是使用 GitHub Actions UI。使用下列命令：<pre># Run actual automation<br />python3 main.py</pre> | AWS DevOps | 

### 驗證 PRs和變更
<a name="validate-prs-and-changes"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢閱建立的 PRs和變更。 | 若要監控 GitHub 工作流程執行的結果，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-automated-pull-requests-for-terraform-managed-aws-infrastructure.html) | AWS DevOps | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| （選用） 清除 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*

## 總結
<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 服務協調管道建立。如需有關此解決方案中使用的 AWS 服務的詳細資訊，請參閱此模式**的工具**一節。

## 先決條件和限制
<a name="create-dynamic-ci-pipelines-for-java-and-python-projects-automatically-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 正在部署此解決方案的相同 AWS 區域中的 Amazon S3 儲存貯體
+ 具有建立此解決方案所需資源所需的 AWS CloudFormation 許可的 AWS Identity and Access Management (IAM) [委託人](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_principal.html) 

**限制**
+ 此模式僅支援 Java 和 Python 專案。
+ 在此模式中佈建的 IAM 角色遵循最低權限原則。必須根據 CI 管道需要建立的特定資源更新 IAM 角色的許可。

## Architecture
<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_tw/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 文件中的 AWS CloudFormation 入門](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/GettingStarted.html)。 CloudFormation 

## 工具
<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 函數和其他 AWS 服務來建置業務關鍵應用程式。
+ [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 (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) 可協助您建立和控制密碼編譯金鑰，以協助保護您的資料。
+ [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 參數存放區](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)為組態資料管理和秘密管理提供安全的階層式儲存。

**Code**

此模式的程式碼可在 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 中的秘密。如需詳細資訊，請參閱 [ AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) Secrets Manager。
+ 為存放在 Amazon S3 中的 CodePipeline 成品設定伺服器端加密。如需詳細資訊，請參閱 [CodePipeline 文件中的為存放在 Amazon S3 for CodePipeline 中的成品設定伺服器端加密 CodePipeline](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 文件》中的設定 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)。 Amazon S3 
+ 設定 IAM 政策時使用 IAM Access Analyzer。此工具提供可行的建議，協助您撰寫安全且實用的 IAM 政策。如需詳細資訊，請參閱 IAM 文件中的[使用 AWS Identity and Access Management Access Analyzer](https://docs.aws.amazon.com/IAM/latest/UserGuide/what-is-access-analyzer.html)。
+ 盡可能在設定 IAM 政策時定義特定存取條件。
+ 啟用 Amazon CloudWatch 記錄以進行監控和稽核。如需詳細資訊，請參閱 [ CloudWatch 文件中的什麼是 Amazon CloudWatch Logs？](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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Amazon S3 儲存貯體。 | 建立 Amazon S3 儲存貯體 （或使用現有的儲存貯體），以存放解決方案所需的 CloudFormation 範本、原始程式碼和輸入檔案。如需詳細資訊，請參閱 [Amazon S3 文件中的步驟 1：建立您的第一個 S3 儲存貯](https://docs.aws.amazon.com/AmazonS3/latest/userguide/creating-bucket.html)體。 Amazon 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)。 Amazon S3 請務必僅上傳 **Solution-Templates** 資料夾的內容。您只能在 Amazon S3 儲存貯體的根層級上傳檔案。 | AWS DevOps | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在複製的 GitHub 儲存庫中使用 template.yml 檔案，建立 CloudFormation 堆疊來部署解決方案。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html)建立堆疊時，它會列在 **Stacks** 頁面上，狀態為 **CREATE\$1IN\$1PROGRESS**。在完成此模式中的剩餘步驟之前，請務必等待堆疊的狀態變更為 **CREATE\$1COMPLETE**。 | AWS 管理員、AWS DevOps | 

### 測試設定
<a name="test-the-setup"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行您建立的步驟函數。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/create-dynamic-ci-pipelines-for-java-and-python-projects-automatically.html) | AWS DevOps | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除 CloudFormation 中的資源堆疊。 | 在 CloudFormation 中刪除 CI 管道的資源堆疊。如需詳細資訊，請參閱 [ CloudFormation 文件中的刪除 AWS CloudFormation 主控台上的堆疊](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html)。 CloudFormation 請務必刪除名為 **<project\$1name>-stack** 的堆疊。 | AWS DevOps | 
| 在 Amazon S3 和 CloudFormation 中刪除 CI 管道的相依性。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 Functions WorkFlow Studio](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 文件）
+ [使用 AWS CodeCommit、AWS CodeBuild、AWS CodeDeploy 和 AWS CodePipeline 完成 CI/CD](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 文件）

# 使用 Terraform 部署 CloudWatch Synthetics Canary
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform"></a>

*Dhrubajyoti Mukherjee 和 Jean-Francois Landreau，Amazon Web Services*

## 總結
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-summary"></a>

請務必從客戶的角度驗證系統的運作狀態，並確認客戶能夠連線。當客戶不持續呼叫端點時，這會更困難。[Amazon CloudWatch Synthetics](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html) 支援建立 Canary，可測試公有和私有端點。透過使用 Canary，即使系統未使用，您也可以知道系統的狀態。這些 Canary 可以是 Node.js Puppeteer 指令碼或 Python Selenium 指令碼。

此模式說明如何使用 HashiCorp Terraform 部署測試私有端點的 Canary。它會嵌入 Puppeteer 指令碼，以測試 URL 是否傳回 `200-OK`。然後，Terraform 指令碼可以與部署私有端點的指令碼整合。您也可以修改解決方案來監控公有端點。

## 先決條件和限制
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-prereqs"></a>

**先決條件 **
+ 具有虛擬私有雲端 (VPC) 和私有子網路的作用中 Amazon Web Services (AWS) 帳戶
+ 可從私有子網路到達的端點 URL
+ 部署環境中安裝的 Terraform

**限制 **

目前的解決方案適用於下列 CloudWatch Synthetics 執行時間版本：
+ syn-nodejs-puppeteer-3.4
+ syn-nodejs-puppeteer-3.5
+ syn-nodejs-puppeteer-3.6
+ syn-nodejs-puppeteer-3.7

隨著新的執行時間版本發佈，您可能需要更新目前的解決方案。您也需要修改解決方案，以跟上安全性更新。

**產品版本**
+ Terraform 1.3.0

## Architecture
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-architecture"></a>

Amazon CloudWatch Synthetics 是以 CloudWatch、Lambda 和 Amazon Simple Storage Service (Amazon S3) 為基礎。Amazon CloudWatch 提供精靈來建立 Canary，以及顯示 Canary 執行狀態的儀表板。Lambda 函數會執行指令碼。Amazon S3 會存放 Canary 執行的日誌和螢幕擷取畫面。

此模式透過部署在目標子網路中的 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體來模擬私有端點。Lambda 函數需要部署私有端點之 VPC 中的彈性網路介面。

![\[描述遵循圖表。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/73ed0103-ec45-4653-bb29-f402a88f0c64/images/39aaed0f-f259-4f2a-98fb-8e3a340d0b02.png)


上圖顯示以下項目：

1. Synthetics Canary 會啟動 Canary Lambda 函數。

1. Canary Lambda 函數會連接至彈性網路界面。

1. Canary Lambda 函數會監控端點的狀態。

1. Synthetics Canary 會將執行資料推送至 S3 儲存貯體和 CloudWatch 指標。

1. CloudWatch 警示會根據指標啟動。

1. CloudWatch 警示會啟動 Amazon Simple Notification Service (Amazon SNS) 主題。

## 工具
<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 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) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。
+ [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 程式庫。CloudWatch Synthetics 執行時間使用 Puppeteer 架構。

**Code**

解決方案可在 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 收集監控私有 URL 的需求。 | 收集完整的 URL 定義：網域、參數和標頭。若要私下與 Amazon S3 和 Amazon CloudWatch 通訊，請使用 VPC 端點。請注意，端點如何存取 VPC 和子網路。考慮 Canary 執行的頻率。 | 雲端架構師、網路管理員 | 
| 修改現有的解決方案以監控私有 URL。 | 修改 `terraform.tfvars` 檔案：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/deploy-cloudwatch-synthetics-canaries-by-using-terraform.html) | 雲端架構師、DevOps 工程師 | 

## 疑難排解
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 刪除佈建的資源會卡住。 | 依該順序手動刪除 Canary Lambda 函數、對應的彈性網路介面和安全群組。 | 

## 相關資源
<a name="deploy-cloudwatch-synthetics-canaries-by-using-terraform-resources"></a>
+ [使用合成監控](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries.html)
+ [使用 Amazon CloudWatch Synthetics 監控 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 所需的基礎設施。
+ `canary` 部署 Canary。

解決方案的輸入參數位於 `terraform.tfvars` 檔案中。您可以使用下列程式碼範例來建立一個 Canary。

```
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
   ```

# 在聊天應用程式自訂動作和 中使用 Amazon Q Developer 部署 ChatOps 解決方案來管理 SAST 掃描結果 CloudFormation
<a name="deploy-chatops-solution-to-manage-sast-scan-results"></a>

*Anand Bukkapatnam Tirumala，Amazon Web Services*

## 總結
<a name="deploy-chatops-solution-to-manage-sast-scan-results-summary"></a>

此模式提供全方位的解決方案，可在聊天應用程式中使用 Amazon Q Developer，以簡化透過 SonarQube 回報的靜態應用程式安全測試 (SAST) 掃描失敗的管理。這種創新方法將自訂動作和通知整合到對話界面中，從而在開發團隊中實現高效的協作和決策過程。

在現今步調快速的軟體開發環境中，有效管理 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 Developer 已新增至必要的 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[user 權杖](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)，然後選擇服務的連結。

## Architecture
<a name="deploy-chatops-solution-to-manage-sast-scan-results-architecture"></a>

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

![\[使用 Amazon Q Developer 部署自動程式碼品質保證以進行發行管理的工作流程。\]](http://docs.aws.amazon.com/zh_tw/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 使用 SonarQube 協調 SAST 掃描。
   + 工作流程會監控 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 Developer，以進行 Slack 整合。

1. Slack 整合：
   + 聊天應用程式中的 Amazon Q Developer 會在指定的 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_tw/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 Developer](https://docs.aws.amazon.com/chatbot/latest/adminguide/what-is.html) 可讓您使用 Amazon Chime、Microsoft Teams 和 Slack 聊天頻道來監控和回應 AWS 應用程式中的操作事件。*終止支援通知：*在 2026 年 2 月 20 日， AWS 將終止對 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 服務 來建置業務關鍵型應用程式。

**其他工具**
+ [Slack](https://slack.com/help/articles/115004071768-What-is-Slack-) 是 Salesforce 產品，是一種採用 AI 技術的對話平台，可提供聊天和視訊協作、自動化沒有程式碼的程序，並支援資訊共用。
+ [SonarQube](https://docs.sonarsource.com/sonarqube/latest/user-guide/user-account/generating-and-using-tokens/) 是一種內部部署分析工具，旨在偵測超過 30 種語言、架構和 IaC 平台的編碼問題。

**程式碼儲存庫**

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

## 最佳實務
<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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要複製此模式的 [chatops-slack](https://github.com/aws-samples/chatops-slack) 儲存庫，請使用下列命令。`git clone "git@github.com:aws-samples/chatops-slack.git"` | AWS DevOps、建置主管、DevOps 工程師、雲端管理員 | 
| 建立包含 Lambda 程式碼的 .zip 檔案。 | 為 `CheckBuildStatus`和 AWS Lambda 功能的函數程式碼建立 .zip 檔案`ApprovalEmail`。若要建立 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行`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_tw/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html) | AWS 管理員、AWS DevOps、建置主管、DevOps 工程師 | 
| 將 .zip 檔案上傳至 Amazon S3 儲存貯體。 | 將您先前建立的 `notification.zip`和 `approval.zip` 檔案上傳至名為 的 Amazon S3 儲存貯體`S3LambdaBucket`。`app-security.yml` CloudFormation 堆疊檔案使用 `S3LambdaBucket` 來佈建 Lambda 函數。 | AWS DevOps、建置主管、DevOps 工程師、AWS 系統管理員 | 

### 執行 app-security.yml 堆疊檔案
<a name="execute-the-app-security-yml-stack-file"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行`app-security.yml`堆疊檔案。 | `app-security.yml` 堆疊檔案會部署通知和核准系統的剩餘基礎設施。若要執行 `app-security.yml` 檔案，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html)成功傳遞測試訊息後，您應該會在 Slack 頻道上看到通知。如需詳細資訊，請參閱《聊天應用程式管理員指南》中的從 [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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定自訂 Lambda 動作。 | 若要設定自訂 AWS Lambda 動作，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-chatops-solution-to-manage-sast-scan-results.html) | AWS 管理員、AWS DevOps、建置主管、DevOps 工程師、Slack Admin | 
| 驗證核准流程。 | 若要驗證核准流程是否如預期運作，請選擇 Slack 中的**核准**按鈕。Slackbot 應在訊息執行緒上傳送通知，並**成功傳送確認字串核准電子郵件**。 | AWS 管理員、AWS DevOps、DevOps 工程師、Slack Admin | 

## 疑難排解
<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_tw/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 Developer 用於版本管理的自訂動作。不過，您可以修改特定使用案例的 Lambda 程式碼，並在其上建置，以重複使用解決方案。

**CloudFormation 堆疊檔案的參數**

下表顯示 CloudFormation 堆疊檔案 的參數及其描述`pre-requisite.yml`。


| 
| 
| **索引鍵** | **Description** | 
| --- |--- |
| `StackName` | CloudFormation 堆疊的名稱。 | 
| `S3LambdaBucket` | 您上傳 Lambda 程式碼的 Amazon S3 儲存貯體名稱。名稱必須是全域唯一的。 | 
| `SonarToken` | SonarQube 使用者字符，如[先決條件](#deploy-chatops-solution-to-manage-sast-scan-results-prereqs)中所述。 | 

下表顯示 CloudFormation 堆疊檔案 的參數及其描述`app-security.yml`。


| 
| 
| **索引鍵** | **Description** | 
| --- |--- |
| `CKMSKeyArn` | 在此堆疊中建立的 AWS KMS key IAM 角色和 Lambda 函數中使用的 Amazon Resource Name (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` | Slack 工作區 ID，如[先決條件](#deploy-chatops-solution-to-manage-sast-scan-results-prereqs)中所述。若要尋找 Slack 工作區 ID，請登入 AWS 管理主控台，在聊天應用程式主控台中開啟 Amazon Q Developer，然後選擇**已設定的用戶端**、**Slack**、**WorkspaceID**。 | 
| `StackName` | CloudFormation 堆疊的名稱。 | 
| `SonarFileDirectory` | 包含 `sonar.project.<env>.properties` 檔案的目錄。 | 
| `SonarFileName` | `sonar.project.<env>properties` 檔案名稱。 | 
| `SourceCodeZip` | 包含 檔案和原始程式碼的 .zip `sonar.project.<env>properties` 檔案名稱。 | 

# 使用 Terraform 在 Amazon Bedrock 上部署代理程式系統，搭配CrewAI 架構
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework"></a>

*Vanitha Dontireddy，Amazon Web Services*

## 摘要
<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/) 架構來實作可擴展的多代理程式 AI 系統。解決方案可讓組織透過基礎設施即程式碼 (IaC) 來建立、部署和管理複雜的 AI 代理程式工作流程。在此模式中，CrewAI 多代理程式協同運作功能會結合 Amazon Bedrock 基礎模型和 Terraform 基礎設施自動化。因此，團隊可以建置生產就緒的 AI 系統，以最少的人工監督來處理複雜的任務。模式實作企業級安全性、可擴展性和操作最佳實務。

## 先決條件和限制
<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 架構

**限制**
+ 客服人員互動受限於模型內容視窗。
+ 大規模部署的分層狀態管理考量適用於此模式。
+ 有些 AWS 服務 不適用於所有 AWS 區域。如需區域可用性，請參閱[AWS 依區域的服務](https://aws.amazon.com/about-aws/global-infrastructure/regional-product-services/)。如需特定端點，請參閱[服務端點和配額](https://docs.aws.amazon.com/general/latest/gr/aws-service-information.html)，然後選擇服務的連結。

## Architecture
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-architecture"></a>

在此模式中，會發生下列互動：
+ Amazon Bedrock 透過其基礎模型 (FMs) 套件提供代理程式智慧的基礎。它可為 AI 代理器啟用自然語言處理 (NLP)、推理和決策功能，同時保持高可用性和可擴展性。
+ CrewAI 架構可做為核心協同運作層，用於建立和管理 AI 代理器。它在與 Amazon Bedrock 整合時處理代理程式通訊協定、任務委派和工作流程管理。
+ Terraform 透過程式碼管理整個基礎設施堆疊，包括運算資源、聯網、安全群組和 AWS Identity and Access Management (IAM) 角色。它可確保跨環境的一致、版本控制的部署。Terraform 部署會建立下列項目：
  + AWS Lambda 函數以執行CrewAI 應用程式
  + 適用於程式碼和報告的 Amazon Simple Storage Service (Amazon S3) 儲存貯體
  + 具有適當許可的 IAM 角色
  + Amazon CloudWatch 記錄
  + Amazon EventBridge 排定的執行

下圖說明使用 Amazon Bedrock 和 Terraform 來部署 CrewAI 多代理程式系統的架構。

![\[使用 Terraform 和 Amazon Bedrock 部署 CrewAI 多代理程式系統的工作流程。\]](http://docs.aws.amazon.com/zh_tw/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 模型組態包括指定基礎模型 (FM)，以用於設定CrewAI 代理程式。

1. 建立 EventBridge 規則，根據定義的排程觸發 Lambda 函數。

1. 觸發時 （透過排程或手動），Lambda 函數會初始化並擔任具有存取 AWS 服務 和 Amazon Bedrock 許可的 IAM 角色。

1. CrewAI 架構會從 YAML 檔案載入代理程式組態，並建立專門的 AI 代理程式 (*AWS 基礎設施安全稽核*人員）。Lambda 函數會依序執行這些代理程式，以掃描 AWS 資源、分析安全漏洞，並產生全面的稽核報告。

1. CloudWatch Logs 會擷取 Lambda 函數的詳細執行資訊，其中包含 365 天的保留期和 AWS Key Management Service (AWS KMS) 合規要求的加密。日誌提供客服人員活動、錯誤追蹤和效能指標的可見性，可有效監控和疑難排解安全稽核程序。

1. 安全性稽核報告會自動產生並存放在指定的 Amazon S3 儲存貯體中。自動化設定有助於維持一致的安全監控，並將營運開銷降至最低。

在初始部署之後，工作流程會為您的 AWS 基礎設施提供持續的安全稽核和報告，而無需手動介入。

**AI 代理器概觀**

此模式會建立多個 AI 代理器，每個代理器都有獨特的角色、目標和工具：
+ **安全分析師代理**程式會收集和分析 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 執行指標以進行監控。

**注意**  
的程式碼`aws-security-auditor-crew`來自 GitHub [3P-Agentic\$1frameworks](https://github.com/aws-samples/3P-Agentic-Frameworks/blob/main/crewai/aws-security-auditor-crew/README.md) 儲存庫，可在 AWS 範例集合中找到。

**可用性和擴展**

您可以將可用的客服人員擴展到四個以上的核心客服人員。若要使用其他專業客服人員進行擴展，請考慮下列新的客服人員類型：
+ *威脅情報專家*代理程式可以執行下列動作：
  + 監控外部威脅饋送並與內部調查結果建立關聯
  + 提供有關與基礎設施相關的新興威脅的內容
  + 根據萬用中的主動入侵來排定漏洞的優先順序
+ *合規架構*代理程式可以專注於特定法規領域，例如：
  + 支付卡產業資料安全標準 (PCI DSS) 合規代理程式
  + 1996 年健康保險流通與責任法案 (HIPAA) 合規代理程式
  + 系統和組織控制 2 (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) 是一種全受管 AI 服務，可透過統一 API 使用高效能的基礎模型 (FMs)。
+ [Amazon CloudWatch Logs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/WhatIsCloudWatchLogs.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 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) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。在此模式中，它會為代理程式成品和狀態管理提供物件儲存。

**其他工具**
+ 以 Python 為基礎的開放原始碼架構[CrewAI](https://www.crewai.com/open-source)可建置多代理程式 AI 系統。
+ [Terraform](https://www.terraform.io/) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。

**程式碼儲存庫**

此模式的程式碼可在 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 S3 後端搭配 Amazon DynamoDB 鎖定，為 Terraform 實作適當的狀態管理。如需詳細資訊，請參閱《使用 Terraform 提供者的最佳實務》中的[後端](https://docs.aws.amazon.com/prescriptive-guidance/latest/terraform-aws-provider-best-practices/backend.html)最佳實務。 * AWS *
+ 使用工作區來分隔開發、預備和生產環境。
+ 遵循最低權限原則，並授予執行任務所需的最低許可。如需詳細資訊，請參閱 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 Logs 啟用詳細記錄和監控。
+ 實作客服人員操作的重試機制和錯誤處理。

## 史詩
<a name="deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework-epics"></a>

### 部署CrewAI架構
<a name="deploy-crewai-framework"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 若要在本機電腦上複製此模式的儲存庫，請執行下列命令：<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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 存取代理程式。 |  AWS 基礎設施安全稽核和報告人員中的代理程式會部署為 Lambda 函數。若要存取代理程式，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-agentic-systems-on-amazon-bedrock-with-the-crewai-framework.html) | DevOps 工程師 | 
| （選用） 設定代理程式的手動執行。 | 代理程式設定為以每日排程 （午夜 UTC) 自動執行。不過，您可以使用下列步驟手動觸發它們：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 中存放報告的必要許可。輸出是 Markdown 報告，可提供 AWS 基礎設施的完整安全分析。若要協助詳細偵錯代理程式行為，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除建立的資源。 | 若要刪除此模式建立的所有基礎設施，請執行下列命令：<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 文件中的疑難排解](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot.html) IAM。 | 

## 相關資源
<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/)
+ [Amazon Bedrock 代理程式的運作方式](https://docs.aws.amazon.com/bedrock/latest/userguide/agents-how.html)
+ [AWS Well-Architected 架構](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` 檔案以包含新的客服人員特定任務。
   + 在任務之間建立相依性，以協助確保適當的資訊流程。
   + 適時實作平行任務執行。

**技術實作**

以下是提議的 Threat Intelligence Specialist 代理程式`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 任務 AWS CodePipeline
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline"></a>

*Bruno Klein 和 Luis Henrique Massao Yamada，Amazon Web Services*

## 總結
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-summary"></a>

此模式示範如何將 AWS CodeCommit 和 AWS CodePipeline 與 AWS Glue 整合，並在開發人員將其變更推送至遠端 AWS CodeCommit 儲存庫時，立即使用 AWS 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>

**先決條件**
+ 作用中的 AWS 帳戶
+ 安裝在本機電腦上的 [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 任務成功啟動，管道就會完成。它不會等待任務完成。
+ 附件中提供的程式碼僅供示範使用。

## Architecture
<a name="deploy-an-aws-glue-job-with-an-aws-codepipeline-ci-cd-pipeline-architecture"></a>

**目標技術堆疊**
+ AWS Glue
+ AWS Lambda
+ AWS CodePipeline
+ AWS CodeCommit

**目標架構**

![\[一旦開發人員將變更推送至 CodeCommit 儲存庫，即可使用 Lambda 啟動 Glue 任務。\]](http://docs.aws.amazon.com/zh_tw/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 整合。它提供一個基準範例，您可以自訂或擴展供自己使用。如需詳細資訊，請參閱 *Epics* 區段。

## 工具
<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/) – 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 AWS CLI。 | 將 AWS Command Line Interface (AWS CLI) 設定為目標，並使用您目前的 AWS 帳戶進行驗證。如需說明，請參閱 [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)
+ [在 CodePipeline 的管道中調用 AWS Lambda 函數](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 CodeCommit 和 AWS CodeBuild 在多個 AWS 區域中部署程式碼
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild"></a>

*Anand Krishna Varanasi，Amazon Web Services*

## 摘要
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-summary"></a>

此模式示範如何使用 AWS CloudFormation 跨多個 Amazon Web Services (AWS) 區域建置基礎設施或架構。它包含跨多個 AWS 區域的持續整合 (CI)/持續部署 (CD)，以加快部署速度。** **此模式中的步驟已針對建立 AWS CodePipeline 任務進行測試，以部署至三個 AWS 區域做為範例。您可以根據您的使用案例變更區域數量。

## 先決條件和限制
<a name="deploy-code-in-multiple-aws-regions-using-aws-codepipeline-aws-codecommit-and-aws-codebuild-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 
  + 具有 *AmazonS3FullAccess* 和 *CloudWatchFullAccess* 政策的 CodeBuild 角色。這些政策可讓 CodeBuild 透過 Amazon CloudWatch 監看 AWS CodeCommit 事件，並使用 Amazon Simple Storage Service (Amazon S3) 做為成品存放區。
  + 具有下列政策的 AWS CloudFormation 角色，可讓 AWS CloudFormation 在最終建置階段中建立或更新 AWS Lambda 函數、推送或監看 Amazon CloudWatch logs，以及建立和更新變更集。 
    + *AWSLambdaFullAccess*
    + *AWSCodeDeployFullAccess*
    + *CloudWatchFullAccess*
    + *AWSCloudFormationFullAccess*
    + *AWSCodePipelineFullAccess*
**注意**  
AWS CodeBuild 和 AWS CloudFormation 的兩個 AWS Identity and Access Management (IAM) 角色具有適當的政策，可讓 CodeBuild 執行 CI 任務，以平行測試、綁定、封裝成品和部署到多個 AWS 區域。  交叉檢查 CodePipeline 建立的政策，以確認 CodeBuild 和 AWS CloudFormation 在 CI 和 CD 階段具有適當的許可。

## Architecture
<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_tw/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 區域，因此 CodeBuild 會將 AWS CloudFormation 範本封裝成三個 S3 儲存貯體，每個指定區域中各一個。CodeBuild 只會使用 S3 儲存貯體做為成品儲存庫。

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) 是網際網路的儲存體。此服務旨在降低開發人員進行網路規模運算的難度。

**Code**

下列範例程式碼適用於 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 選取部署的主要 AWS 區域。 | 登入您的 AWS 帳戶，然後選擇部署的主要區域。CodeCommit 儲存庫將位於主要區域。 | DevOps | 
| 建立 CodeCommit 儲存庫。 | 建立 CodeCommit 儲存庫，並將所需的程式碼推送至其中。此程式碼通常包含 AWS CloudFormation 或 AWS SAM 範本、如果有 Lambda 程式碼，以及 CodeBuild `buildspec.yaml` 檔案做為 AWS CodePipeline 的輸入。 | DevOps | 
| 將程式碼推送至 CodeCommit 儲存庫。 | 在*附件*區段中，下載此範例的程式碼，然後將所需的程式碼推送至其中。一般而言，程式碼可以包含 AWS CloudFormation 或 AWS SAM 範本、Lambda 程式碼和 CodeBuild `buildspec.yaml` 檔案做為管道的輸入。 | DevOps | 

### 來源階段：建立管道
<a name="source-phase-create-the-pipeline"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 CodePipeline 任務。 | 在 CodePipeline 主控台上，選擇**建立管道**。 | DevOps | 
| 命名 CodePipeline 任務，然後選擇服務角色設定。 | 輸入任務的名稱，並保留預設服務角色設定，以便 CodePipeline 建立已連接必要政策的角色。 | DevOps | 
| 指定成品存放區的位置。 | 在**進階設定**下，保留預設選項，以便 CodePipeline 建立用於程式碼成品儲存的 S3 儲存貯體。如果您改用現有的 S3 儲存貯體，儲存貯體必須位於您在第一個特徵中指定的主要區域中。 | DevOps | 
| 指定加密金鑰。 | 保留預設選項、**預設 AWS 受管金鑰**，或選擇使用您自己的 AWS Key Management Service (AWS KMS) 客戶受管金鑰。 | DevOps | 
| 指定來源提供者。 | 在**來源提供者**下，選擇 **AWS CodeCommit**。 | DevOps | 
| 指定儲存庫。 | 選擇您在第一個 epic 中建立的 CodeCommit 儲存庫。如果您將程式碼放在分支中，請選擇分支。 | DevOps | 
| 指定程式碼變更的偵測方式。 | 保留預設值 **Amazon CloudWatch Events**，做為 CodeCommit 啟動 CodePipeline 任務的變更觸發條件。 | DevOps | 

### 建置階段：設定管道
<a name="build-phase-configure-the-pipeline"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 指定建置提供者。 | 針對建置提供者，選擇 **AWS CodeBuild**。 | DevOps | 
| 指定 AWS 區域。 | 選擇您在第一個史詩中指定的主要區域。 | DevOps | 

### 組建階段：建立和設定專案
<a name="build-phase-create-and-configure-the-project"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立專案 | 選擇**建立專案**，然後輸入專案的名稱。 | DevOps | 
| 指定環境映像。 | 針對此模式示範，請使用預設 CodeBuild 受管映像。如果您有自訂 Docker 映像，您也可以選擇使用自訂 Docker 映像。 | DevOps | 
| 指定作業系統。 | 選擇 Amazon Linux 2 或 Ubuntu。Amazon Linux 2 即將終止支援。如需詳細資訊，請參閱 [Amazon Linux 2 FAQs](https://aws.amazon.com/amazon-linux-2/faqs/)。 | DevOps | 
| 指定服務角色。 | 在開始建立 CodePipeline 任務之前，請選擇您為 CodeBuild 建立的角色。 CodePipeline （請參閱*先決條件*一節。) | DevOps | 
| 設定其他選項。 | 對於**逾時**和**佇列逾時**，請保留預設值。對於憑證，除非您有要使用的自訂憑證，否則請保留預設設定。 | DevOps | 
| 建立環境變數。 | 針對您要部署的每個 AWS 區域，提供 S3 儲存貯體名稱和區域名稱 （例如 us-east-1) 來建立環境變數。 | DevOps | 
| 如果不是 buildspec.yml，請提供 buildspec 檔案名稱。 | 如果檔案名稱為預設值 ，請將此欄位保留空白`buildspec.yaml`。如果您重新命名 buildspec 檔案，請在此處輸入名稱。請確定它符合 CodeCommit 儲存庫中的檔案名稱。 | DevOps | 
| 指定記錄。 | 若要查看 Amazon CloudWatch Events 的日誌，請保留預設設定。或者，您可以定義任何特定的群組或記錄器名稱。 | DevOps | 

### 略過部署階段
<a name="skip-the-deploy-phase"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 略過部署階段並完成管道的建立。 | 當您設定管道時，CodePipeline 只允許您在部署階段建立一個階段。若要部署到多個 AWS 區域，請略過此階段。建立管道之後，您可以新增多個部署階段。 | DevOps | 

### 部署階段：設定管道以部署到第一個區域
<a name="deploy-phase-configure-the-pipeline-for-deployment-to-the-first-region"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將階段新增至部署階段。 | 編輯管道，然後在部署階段中選擇**新增階段**。第一個階段適用於主要區域。 | 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將第二個階段新增至部署階段。 | 若要為第二個區域新增階段，請編輯管道，然後在部署階段中選擇**新增階段**。重要：建立第二個區域的程序與第一個區域的程序相同，但下列值除外。 | DevOps | 
| 提供第二個階段的動作名稱。 | 輸入反映第二個階段和第二個區域的唯一名稱。 | DevOps | 
| 設定第二個階段的區域。 | 選擇您要部署堆疊的第二個區域。 | DevOps | 
| 指定第二個區域的範本。 | 選取 CodeBuild 封裝並傾印至第二個區域的 S3 儲存貯體的區域特定套件名稱。 | DevOps | 

### 部署階段：設定管道以部署到第三個區域
<a name="deploy-phase-configure-the-pipeline-for-deployment-to-the-third-region"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將第三個階段新增至部署階段。 | 若要為第三個區域新增階段，請編輯管道，然後在部署階段中選擇**新增階段**。重要：建立第二個區域的程序與前兩個區域的相同，但下列值除外。 | DevOps | 
| 提供第三個階段的動作名稱。 | 輸入反映第三個階段和第三個區域的唯一名稱。 | DevOps | 
| 設定第三個階段的區域。 | 選擇您要部署堆疊的第三個區域。 | DevOps | 
| 指定第三個區域的範本。 | 選取 CodeBuild 封裝的區域特定套件名稱，並傾印到第三個區域的 S3 儲存貯體。 | DevOps | 

### 清除部署
<a name="clean-up-the-deployment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除 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 Serverless 應用程式模型](https://aws.amazon.com/serverless/sam/)
+ [AWS CloudFormation](https://aws.amazon.com/cloudformation/)
+ [AWS CodePipeline 的 AWS CloudFormation 架構結構參考 AWS 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*

## 摘要
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-summary"></a>

此模式示範如何實作從 Azure DevOps 管道到私有 Amazon Elastic Kubernetes Service (Amazon EKS) 叢集的持續整合和持續交付 (CI/CD)。它解決了組織透過轉換到 Amazon EKS 叢集的私有 API 伺服器端點來增強其安全狀態面臨的關鍵挑戰。

公有端點會將 Kubernetes API 伺服器直接公開至網際網路，進而建立惡意人士可能鎖定的更大攻擊面。透過切換到私有端點，對叢集控制平面的存取僅限於客戶虛擬私有雲端 (VPC) 內。

雖然將 Amazon EKS 叢集轉換為私有 API 端點可大幅增強安全性，但它為 Azure DevOps 等外部 CI/CD 平台帶來連線挑戰。私有端點只能從叢集的 VPC 或對等網路存取。因此，在 AWS 私有網路外操作的標準 Microsoft 託管 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://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 代理程式集區。
+ [已建立](https://github.com/signup) GitHub 帳戶。
+ 具有設定服務連線之存取權的 Azure DevOps 專案，這些連線是在 Azure Pipelines 與外部或遠端服務之間[建立](https://learn.microsoft.com/en-us/azure/devops/user-guide/sign-up-invite-teammates?view=azure-devops&tabs=microsoft-account)的驗證連線。
+ 針對前一點所述的 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)，然後選擇服務的連結。

## Architecture
<a name="deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters-architecture"></a>

此模式會建立下列項目：
+ **Amazon ECR 儲存庫** - Amazon Elastic Container Registry (Amazon ECR) 儲存庫會將 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_tw/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 代理程式會將範例應用程式部署在名為 的命名空間中的私有 Amazon EKS 叢集上`webapp`。

## 工具
<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) 是一種受管容器映像登錄服務，安全、可擴展且可靠。
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) 可協助您在 上執行 Kubernetes， AWS 而無需安裝或維護您自己的 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 尋找 Azure DevOps 組織 GUID。 | 登入您的 Azure DevOps 帳戶，然後使用下列 URL 來尋找組織 GUID：在 URL `https://dev.azure.com/{DevOps_Org_ID}/_apis/projectCollections?api-version=6.0` 中，將 取代`{DevOps_org_ID}`為您的 Azure DevOps 組織 ID。 | AWS DevOps | 
| 在 中設定 IdP AWS 帳戶。 | 若要在 中設定 Azure 服務連線 AWS 帳戶 的身分提供者 (IdP)，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)如需詳細資訊，請參閱[如何使用 OpenID Connect AWS 從 Azure DevOps 聯合到](https://aws.amazon.com/blogs/modernizing-with-aws/how-to-federate-into-aws-from-azure-devops-using-openid-connect/) 。 | AWS DevOps | 
| 在 中建立 IAM 政策 AWS 帳戶。 | 若要建立 IAM 政策，為 Azure DevOps 管道使用的 IAM 角色提供必要的許可，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | AWS DevOps | 
| 在 中建立 IAM 角色 AWS 帳戶。 | 若要在 中 AWS 帳戶 為 Azure 服務連線設定 IAM 角色，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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 帳戶 ID 取代 。如需詳細資訊，請參閱 [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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立自我託管代理程式集區。 | 若要在 Azure DevOps 帳戶中設定自我託管代理程式集區，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 代理程式映像並推送至 Amazon ECR
<a name="build-azure-devops-agent-image-and-push-to-ecr"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 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_tw/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_tw/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>`region` 以您的 AWS 帳戶 ID `aws_account_id`和 取代 和 AWS 區域。 | AWS DevOps | 

### 將 Azure DevOps 代理程式部署到私有 Amazon EKS 叢集
<a name="deploy-the-azure-devops-agent-to-a-private-eks-cluster"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 產生 Azure 個人存取字符。 | 在私有 Amazon EKS 叢集上執行的代理程式需要個人存取字符 (PAT)，以便可以向 Azure DevOps 帳戶進行身分驗證。若要產生 PAT，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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 帳戶 URL。 | 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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將範例應用程式儲存庫授與您的 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_tw/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_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html)例如，`20250501.1-image` 和 `20250501.1-helm`。若要驗證命名空間 中私有 Amazon EKS 叢集上的部署`webapp`，請使用下列命令：<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 儲存庫名稱符合 中的 `projectName: webapp` 參數`azure_pipeline.yml`。若要解決此問題，請將 Amazon ECR 儲存庫重新命名為 `webapp`，或更新下列項目：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/deploy-workloads-from-azure-devops-pipelines-to-private-amazon-eks-clusters.html) | 
| 錯誤：Kubernetes 叢集無法連線：伺服器已要求用戶端提供登入資料 | 如果您在 Azure 管道的「提取和部署 Helm Chart」步驟中遇到此錯誤，根本原因通常是來自 Amazon EKS 叢集 中的不正確 IAM 角色組態`aws-auth ConfigMap`。若要解決此問題，請檢查下列項目：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 部落格**
+ [如何使用 OpenID Connect AWS 從 Azure DevOps 聯合到](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)

**Microsoft 文件**
+ [什麼是 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*

## 總結
<a name="execute-redshift-sql-queries-using-terraform-summary"></a>

使用基礎設施做為程式碼 (IaC) 來部署和管理 Amazon Redshift 是 DevOps 中普遍的做法。IaC 可促進各種 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)
+ 使用 Amazon Redshift 讀取/寫入許可設定的[AWS CLI 設定檔](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html) 
+ [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) 儲存庫中使用。

## Architecture
<a name="execute-redshift-sql-queries-using-terraform-architecture"></a>

下圖說明 Terraform 如何透過處理不可重複和可重複的 SQL 查詢來管理 Amazon Redshift 資料庫資源。

![\[使用 SQL 查詢管理 Amazon Redshift 資料庫資源的 Terraform 程序。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/0f4467ac-761b-4b6b-a32f-e18a2ca2245d/images/3b6ff9e8-e3d1-48ed-9fa1-4b14f7d3d65b.png)


圖表顯示下列步驟：

1. Terraform 會在初始 Amazon Redshift 叢集部署期間套用不可重複的 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 Redshift [ExecuteStatement](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_ExecuteStatement.html) 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) 是 中全受管的 PB 級資料倉儲服務 AWS 雲端。

**其他工具**
+ [Terraform](https://www.terraform.io/) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。
+ [Python](https://www.python.org/) 是一種一般用途的程式設計語言，用於此模式來執行 SQL 查詢。

## 最佳實務
<a name="execute-redshift-sql-queries-using-terraform-best-practices"></a>
+ [Amazon Redshift 最佳實務](https://docs.aws.amazon.com/redshift/latest/dg/best-practices.html)
+ [使用 Amazon Redshift Data 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| **複製儲存庫。** | 若要複製包含 Terraform 程式碼的 Git 儲存庫來佈建 Amazon Redshift 叢集，請使用下列命令。<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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 監控 SQL 陳述式的部署。 | 您可以監控 Amazon Redshift 叢集的 SQL 執行結果。如需顯示失敗和成功 SQL 執行的輸出範例，請參閱[其他資訊](#execute-redshift-sql-queries-using-terraform-additional)中*的範例 SQL 陳述*式。 | DBA，DevOps 工程師 | 
| 清除資源。 | 若要刪除 Terraform 部署的所有資源，請執行下列命令。<pre>terraform destroy</pre> | DevOps 工程師 | 

### 驗證結果
<a name="validate-the-results"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證 Amazon Redshift 叢集中的資料。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 文件**
+ [Amazon Redshift 佈建叢集](https://docs.aws.amazon.com/redshift/latest/mgmt/working-with-clusters.html)
+ [對 Amazon Redshift Data 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`、`/view`、 `/table`和 `/stored-procedure`。這些子資料夾指出 Terraform 執行 SQL 查詢的順序。

執行 SQL 查詢的 Python 指令碼為 `sql-queries.py`。首先，指令碼會讀取特定來源目錄的所有檔案和子資料夾，例如 `sql_path_bootstrap` 參數。然後，指令碼會透過呼叫 Amazon Redshift [ExecuteStatement](https://docs.aws.amazon.com/redshift-data/latest/APIReference/API_ExecuteStatement.html) 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`、`/repeatable`、 `/nonrepeatable`和 `/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_repeatable`、 `sql_path_nonrepeatable`或 中執行查詢`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`再次執行。例如，下列命令會從 Terraform 狀態移除`run_bootstrap_queries`資源。

`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]
```

下列輸出顯示成功的 SQL 執行。

```
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 檔案 AWS Organizations
<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*

## 總結
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-summary"></a>

此模式說明如何將 AWS Backup 任務報告從 AWS Organizations 中的組織匯出為 CSV 檔案。解決方案使用 AWS Lambda 和 Amazon EventBridge，根據其狀態來分類 AWS Backup 任務報告，這有助於設定以狀態為基礎的自動化。

AWS Backup 可協助組織集中管理和自動化跨 AWS 服務、雲端和內部部署的資料保護。不過，對於在 AWS Organizations 中設定的 AWS Backup 任務，合併報告只能在每個組織的管理帳戶的 AWS 管理主控台中使用。 AWS Organizations 將此報告帶出管理帳戶，可以減少稽核所需的工作量，並提高自動化、通知和提醒的範圍。

## 先決條件和限制
<a name="export-aws-backup-reports-from-across-an-organization-in-aws-organizations-as-a-csv-file-prereqs"></a>

**先決條件 **
+ 作用中的 AWS 帳戶
+ AWS Organizations 中的作用中[組織](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_tutorials_basic.html)，至少包含管理帳戶和成員帳戶
+ 在 AWS Organizations 中的組織層級AWS Organizations Backup （如需詳細資訊，請參閱 [AWS 部落格上的使用 AWS Backup 跨 AWS 服務大規模自動化集中](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 Backup 資源。

## Architecture
<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 Backup 任務報告從 AWS Organizations 中的組織匯出為 CSV 檔案的範例工作流程。

![\[使用 EventBridge、Lambda、AWS STS 和 IAM 以 CSV 格式從整個組織匯出 AWS Backup 任務報告。\]](http://docs.aws.amazon.com/zh_tw/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) 是一項全受管服務，可協助您集中和自動化跨 AWS 服務、雲端和內部部署的資料保護。
+ [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 調用端點，或其他 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 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製 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 工程師 | 
| 在成員 （報告） AWS 帳戶中部署解決方案元件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 確定 EventBridge 規則在測試之前執行。 | 透過等待至少 24 小時，或增加 CloudFormation 範本的 **template-reporting.yml** 檔案中的報告頻率，確保 EventBridge 規則執行。**增加報告頻率**[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 從成員 （報告） 帳戶刪除解決方案元件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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 函數](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/scheduled-events-invoking-lambda-example.html) （適用於 JavaScript 的 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 服務大規模自動化集中AWS Backup](https://aws.amazon.com/blogs/storage/automate-centralized-backup-at-scale-across-aws-services-using-aws-backup/)(AWS 部落格文章）

# 將 Amazon 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*

## 總結
<a name="export-tags-for-a-list-of-amazon-ec2-instances-to-a-csv-file-summary"></a>

此模式說明如何以程式設計方式將 Amazon Elastic Compute Cloud (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 Command Line Interface (AWS CLI)

**限制**

此模式中提供的範例 Python 指令碼只能根據下列屬性搜尋 Amazon EC2 執行個體：
+ 執行個體 ID
+ 私有 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 Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您透過命令列 shell 中的命令與 AWS 服務互動。

**程式碼儲存庫**

此模式的範例 Python 指令碼可在 GitHub [search-ec2-instances-export-tags](https://github.com/aws-samples/search-ec2-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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製 GitHub 儲存庫。 | 如果您在執行 AWS CLI 命令時收到錯誤，[請確定您使用的是最新的 AWS CLI 版本](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-troubleshooting.html)。在終端機視窗中執行下列 Git 命令，複製 GitHub [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_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立輸入檔案。 | 建立輸入檔案，其中包含您要指令碼搜尋和匯出標籤的 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` 將 取代為您的 Amazon EC2 資源所在的 AWS 區域。如果您使用的是 AWS 具名設定檔，請將 `PROFILE`取代為您正在使用的具名設定檔。若要取得支援的參數清單及其說明，請執行下列命令：<pre>python search_instances.py -h</pre>如需詳細資訊並查看輸出檔案範例，請參閱 GitHub [search-ec2-instances-export-tags](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*

## 摘要
<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 Config受管規則的 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)。 AWS Config 

## 先決條件和限制
<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)。 AWS Config  
+ 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 更新範例 Excel 試算表。 | 下載範例 `excel_config_rules.xlsx` Excel 試算表 （已連接），並標記為您要使用的 `Implemented` AWS Config 受管規則。 標記為 的規則`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 ComplianceResourceTypes 更新 config\$1rules\$1params.json 檔案。 ComplianceResourceTypes | 根據預設，Python 指令碼`ComplianceResourceTypes`會從 AWS 定義的範本擷取 。如果您想要覆寫特定 AWS Config 受管規則的範圍，則需要使用 `--param-file`選項將其做為 JSON 檔案傳遞至 Python 指令碼。例如，下列範例程式碼顯示 `ComplianceResourceTypes`的 `ec2-volume-inuse-check` 如何設定為 `["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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 從 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_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動 AWS CloudFormation 堆疊。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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*

## 總結
<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 Access Management (IAM) 角色。然後，每個 AWS 帳戶中預先定義的 IAM 身分可以暫時擔任角色，以跨帳戶建立受控制的信任鏈。

**注意**  
您可以套用類似的程序，將 CodeCommit 儲存庫的跨帳戶存取權授予其他 IAM 身分。如需詳細資訊，請參閱《[AWS CodeCommit 使用者指南》中的使用角色設定 AWS CodeCommit 儲存庫的跨帳戶存取權](https://docs.aws.amazon.com/codecommit/latest/userguide/cross-account.html)。 *AWS CodeCommit *

## 先決條件和限制
<a name="give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account-prereqs"></a>

**先決條件**
+ 具有 CodeCommit 儲存庫的作用中 AWS 帳戶 (*帳戶 A*)
+ 具有 SageMaker 筆記本執行個體的第二個作用中 AWS 帳戶 (*帳戶 B*)
+ 具備足夠許可的 AWS 使用者，可在帳戶 A 中建立和修改 IAM 角色
+ 第二個 AWS 使用者具有足夠的許可，可在帳戶 B 中建立和修改 IAM 角色

## Architecture
<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_tw/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. CodeCommit 儲存庫在帳戶 A 中的 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 (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 可透過控制已驗證並獲授權使用的人員，協助您安全地管理對 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 政策設定許可時，請務必僅授予執行任務所需的許可。如需詳細資訊，請參閱 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 CodeCommit 存取角色和許可政策。 | 若要自動化此史詩中記錄的手動設定程序，****您可以使用 [AWS 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_tw/prescriptive-guidance/latest/patterns/give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.html)在將此設定移至生產環境之前，最佳實務是撰寫您自己的 IAM 政策，以套用[最低權限許可](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)。如需詳細資訊，請參閱此模式**的其他資訊**一節。 | 一般 AWS、AWS DevOps | 
| 授予帳戶 B 中的 SageMaker 筆記本執行個體角色許可，以在帳戶 A 中擔任 CodeCommit 存取角色。 | 在包含 SageMaker 筆記本執行個體 IAM 角色 (*帳戶 B)* 的帳戶中，執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/give-sagemaker-notebook-instances-temporary-access-to-a-codecommit-repository-in-another-aws-account.html)若要檢視儲存庫的 Amazon Resource Name (ARN)，請參閱《AWS [ CodeCommit 使用者指南》中的檢視 CodeCommit 儲存庫詳細資訊](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-view-repository-details.html)。 *AWS CodeCommit * | 一般 AWS、AWS DevOps | 

### 在帳戶 B 中設定 SageMaker 筆記本執行個體
<a name="set-up-your-sagemaker-notebook-instance-in-account-b"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 AWS SageMaker 筆記本執行個體上設定使用者設定檔，以擔任帳戶 A 中的角色。 | [請確定您已安裝最新版本的 AWS Command Line Interface (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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用 Git 命令或 SageMaker 存取 CodeCommit 儲存庫。 SageMaker | **使用 Git**帳戶 B 中擔任 SageMaker 筆記本執行個體角色的 IAM 主體現在可以執行 Git 命令來存取帳戶 A 中的 CodeCommit 儲存庫。例如，使用者可以執行 `git clone`、 `git pull`和 等命令`git push`。如需說明，請參閱《[AWS CodeCommit 使用者指南》中的連線至 AWS CodeCommit 儲存庫](https://docs.aws.amazon.com/codecommit/latest/userguide/how-to-connect.html)。 *AWS CodeCommit *如需如何搭配 CodeCommit 使用 Git 的詳細資訊，請參閱[AWS CodeCommit 使用者指南》中的 AWS CodeCommit 入門](https://docs.aws.amazon.com/codecommit/latest/userguide/getting-started-cc.html)。 *AWS CodeCommit ***使用 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)。 *AWS CodeCommit *

**注意**  
您也可以編輯 [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 流程分支策略
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments"></a>

*Mike Stephens 和 Abhilash Vinod，Amazon Web Services*

## 總結
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-summary"></a>

管理原始程式碼儲存庫時，不同的分支策略會影響開發團隊使用的軟體開發和發行程序。常見的分支策略範例包括主體、GitHub Flow 和 Gitflow。這些策略使用不同的分支，而且每個環境中執行的活動都不同。實作 DevOps 程序的組織將受益於視覺化指南，以協助他們了解這些分支策略之間的差異。在您的組織中使用此視覺效果有助於開發團隊協調工作並遵循組織標準。此模式提供此視覺化效果，並說明在您的組織中實作 GitHub Flow 分支策略的程序。

此模式是文件系列的一部分，旨在為具有多個 的組織選擇和實作 DevOps 分支策略 AWS 帳戶。此系列旨在協助您從一開始就套用正確的策略和最佳實務，以簡化雲端體驗。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 流程策略。建議您檢閱 [AWS Well-Architected DevOps 指南](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)。此應用程式用於檢視和編輯圖表。

## Architecture
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-architecture"></a>

**目標架構**

下圖可以像 [Punnett 方形](https://en.wikipedia.org/wiki/Punnett_square) （維基百科） 一樣使用。您可以將垂直軸上的分支與水平軸上的 AWS 環境對齊，以決定在每個案例中要執行的動作。這些數字表示工作流程中動作的序列。此範例會帶您從`feature`分支到生產環境中的部署。

![\[每個分支和環境中 GitHub Flow 活動的 Punnett 平方。\]](http://docs.aws.amazon.com/zh_tw/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) 是自動化軟體版本生命週期的程序。它會自動化傳統上需要的許多或所有手動程序，從初始遞交取得新的程式碼到生產環境。CI/CD 管道包含沙盒、開發、測試、預備和生產環境。在每個環境中，CI/CD 管道會佈建部署或測試程式碼所需的任何基礎設施。透過使用 CI/CD，開發團隊可以對程式碼進行變更，然後自動測試和部署。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 Elastic Compute Cloud (Amazon EC2) 或內部部署執行個體、 AWS Lambda 函數或 Amazon Elastic Container Service (Amazon ECS) 服務。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可協助您快速建模和設定軟體版本的不同階段，並自動化持續發行軟體變更所需的步驟。

**其他工具**
+ [Draw.io Desktop](https://github.com/jgraph/drawio-desktop/releases) 是製作流程圖和圖表的應用程式。程式碼儲存庫包含 Draw.io 的 .drawio 格式範本。
+ [Figma](https://www.figma.com/design-overview/) 是一種線上設計工具，專為協同合作而設計。程式碼儲存庫包含 Figma 的 .fig 格式範本。

**程式碼儲存庫**

此模式中圖表的這個來源檔案可在 GitHub [Flow 儲存庫的 GitHub Git 分支策略](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>

遵循 [AWS Well-Architected DevOps 指南](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)中的最佳實務和建議[，並為多帳戶 DevOps 環境選擇 Git 分支策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)。這些可協助您有效地實作 GitHub Flow 型開發、促進協作、改善程式碼品質，以及簡化開發程序。

## 史詩
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-epics"></a>

### 檢閱 GitHub 流程工作流程
<a name="reviewing-the-github-flow-workflows"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢閱標準 GitHub 流程。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/implement-a-github-flow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 工程師 | 
| 檢閱 Hotfix GitHub Flow 程序。 | GitHub Flow 旨在啟用持續交付，其中程式碼變更經常且可靠地部署到更高的環境。關鍵在於，每個`feature`分支都可以隨時部署。`Hotfix` 分支與 `feature`或 `bugfix` 分支類似，可以遵循與這些其他分支相同的程序。不過，考慮到其緊迫性，修正程式通常具有較高的優先順序。根據團隊的政策和情況的緊迫性，程序中的某些步驟可能會加快。例如，可能會快速追蹤 Hotfix 的程式碼檢閱。因此，當 Hotfix 程序平行處理特徵或錯誤修正程序時，圍繞 Hotfix 的緊迫性可能需要修改程序遵循。請務必建立有關管理 Hotfix 的準則，以確保有效且安全地處理它們。 | DevOps 工程師 | 

## 疑難排解
<a name="implement-a-github-flow-branching-strategy-for-multi-account-devops-environments-troubleshooting"></a>


| 問題 | 解決方案 | 
| --- | --- | 
| 分支衝突 | GitHub Flow 模型可能發生的常見問題是，Hotfix 需要發生在生產環境中`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 資源](https://aws.amazon.com/devops/resources/)

**GitHub 流程指引**
+ [GitHub 流程快速入門教學課程 ](https://docs.github.com/en/get-started/using-github/github-flow)(GitHub)
+ [為什麼選擇 GitHub 流程？](https://githubflow.github.io/)

**其他資源**
+ [十二因素應用程式方法 ](https://12factor.net/)(12factor.net：//)

# 為多帳戶 DevOps 環境實作 Gitflow 分支策略
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments"></a>

*Mike Stephens、Stephen DiCato、Abhilash Vinod 和 Tim Wondergem，Amazon Web Services*

## 總結
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-summary"></a>

管理原始程式碼儲存庫時，不同的分支策略會影響開發團隊使用的軟體開發和發行程序。常見的分支策略範例包括主體、Gitflow 和 GitHub Flow。這些策略使用不同的分支，而且每個環境中執行的活動都不同。實作 DevOps 程序的組織將受益於視覺化指南，以協助他們了解這些分支策略之間的差異。在您的組織中使用此視覺效果有助於開發團隊協調工作並遵循組織標準。此模式提供此視覺化效果，並說明在組織中實作 Gitflow 分支策略的程序。

此模式是文件系列的一部分，旨在為具有多個 的組織選擇和實作 DevOps 分支策略 AWS 帳戶。此系列旨在協助您從一開始就套用正確的策略和最佳實務，以簡化雲端體驗。Gitflow 只是您的組織可以使用的一個可能分支策略。此文件系列也涵蓋[了主體](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/implement-a-trunk-branching-strategy-for-multi-account-devops-environments.html)和 [GitHub 流程](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 策略。建議您檢閱 [AWS Well-Architected DevOps 指南](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)。

## Architecture
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-architecture"></a>

**目標架構**

下圖可以像 [Punnett 方形](https://en.wikipedia.org/wiki/Punnett_square) （維基百科） 一樣使用。您可以將垂直軸上的分支與水平軸上的 AWS 環境對齊，以決定在每個案例中要執行的動作。這些數字表示工作流程中動作的序列。此範例會帶您從功能分支到生產環境中的部署。

![\[每個分支和環境中 Gitflow 活動的 Punnett 平方。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/1dee2a06-cc54-4797-b9a9-78b6685edd33/images/d8be49bf-dca1-4892-ac4c-11996a7258c2.png)


如需 Gitflow 方法中 AWS 帳戶、 環境和分支的詳細資訊，請參閱[為多帳戶 DevOps 環境選擇 Git 分支策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)。

**自動化和擴展**

持續整合和持續交付 (CI/CD) 是自動化軟體版本生命週期的程序。它會自動化傳統上需要的許多或所有手動程序，以便從初始遞交取得新程式碼到生產環境。CI/CD 管道包含沙盒、開發、測試、預備和生產環境。在每個環境中，CI/CD 管道會佈建部署或測試程式碼所需的任何基礎設施。透過使用 CI/CD，開發團隊可以對程式碼進行變更，然後自動測試和部署。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 Elastic Compute Cloud (Amazon EC2) 或內部部署執行個體、 AWS Lambda 函數或 Amazon Elastic Container Service (Amazon ECS) 服務。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可協助您快速建模和設定軟體版本的不同階段，並自動化持續發行軟體變更所需的步驟。

**其他工具**
+ [Draw.io Desktop](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 分支模型提供高階儲存庫操作。

**程式碼儲存庫**

此模式中圖表的此來源檔案可在 GitHub [Git 分支策略的 GitFlow](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>

遵循 [AWS Well-Architected DevOps 指南](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)中的最佳實務和建議[，並為多帳戶 DevOps 環境選擇 Git 分支策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)。這些可協助您有效地實作 Gitflow 型開發、促進協作、改善程式碼品質，以及簡化開發程序。

## 史詩
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-epics"></a>

### 檢閱 Gitflow 工作流程
<a name="reviewing-the-gitflow-workflows"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢閱標準 Gitflow 程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 工程師 | 
| 檢閱 Hotfix Gitflow 程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/implement-a-gitflow-branching-strategy-for-multi-account-devops-environments.html) | DevOps 工程師 | 
| 檢閱 bugfix Gitflow 程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 模型可能發生的常見問題是，Hotfix 需要在生產環境中發生，但對應的變更需要在較低的環境中發生，其中另一個分支正在修改相同的資源。我們建議您一次只啟用一個發行分支。如果您一次有一個以上的作用中，環境中的變更可能會碰撞，而且可能無法將分支向前移至生產環境。 | 
| 合併 | 版本應合併回主要分支，並盡快開發，以將工作合併回主要分支。 | 
| Squash 合併 | 只有在從`feature`分支合併到`develop`分支時，才使用小隊合併。在較高分支中使用小隊合併會導致合併變更回到較低分支時遇到困難。 | 

## 相關資源
<a name="implement-a-gitflow-branching-strategy-for-multi-account-devops-environments-resources"></a>

本指南不包含 Git 的訓練；不過，如果您需要此訓練，網際網路上有許多可用的高品質資源。我們建議您從 [Git 文件](https://git-scm.com/doc)網站開始。

下列資源可協助您在 中完成 Gitflow 分支旅程 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 資源](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)
+ [GitHub 上的 Gitflow：如何使用 Git Flow 工作流程搭配 GitHub 型儲存庫](https://youtu.be/WQuxeEvaCxs) (YouTube 影片）
+ [Git 流程初始化範例](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*

## 總結
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-summary"></a>

管理原始程式碼儲存庫時，不同的分支策略會影響開發團隊使用的軟體開發和發行程序。常見的分支策略範例包括主體、GitHub Flow 和 Gitflow。這些策略使用不同的分支，而且每個環境中執行的活動都不同。實作 DevOps 程序的組織將受益於視覺化指南，以協助他們了解這些分支策略之間的差異。在您的組織中使用此視覺效果有助於開發團隊協調工作並遵循組織標準。此模式提供此視覺效果，並說明在組織中實作中繼線分支策略的程序。

此模式是文件系列的一部分，旨在為具有多個 的組織選擇和實作 DevOps 分支策略 AWS 帳戶。此系列旨在協助您從一開始就套用正確的策略和最佳實務，以簡化雲端體驗。中繼線只是您的組織可以使用的一個可能分支策略。此文件系列也涵蓋 [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/)。請使用盡職調查來為您的組織選擇正確的分支策略。

本指南提供圖表，說明組織如何實作主體策略。建議您檢閱正式的 [AWS Well-Architected DevOps 指南](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)。此應用程式用於檢視和編輯圖表。

## Architecture
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-architecture"></a>

**目標架構**

下圖可以像 [Punnett 方形](https://en.wikipedia.org/wiki/Punnett_square) （維基百科） 一樣使用。您可以將垂直軸上的分支與水平軸上的 AWS 環境對齊，以決定在每個案例中要執行的動作。這些數字表示工作流程中動作的序列。此範例會帶您從`feature`分支到生產環境中的部署。

![\[每個分支和環境中主體活動的 Punnett 平方\]](http://docs.aws.amazon.com/zh_tw/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) 是自動化軟體版本生命週期的程序。它會自動化傳統上所需的許多或所有手動程序，以便從初始遞交取得新程式碼到生產環境。CI/CD 管道包含沙盒、開發、測試、預備和生產環境。在每個環境中，CI/CD 管道會佈建部署或測試程式碼所需的任何基礎設施。透過使用 CI/CD，開發團隊可以對程式碼進行變更，然後自動測試和部署。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 Elastic Compute Cloud (Amazon EC2) 或內部部署執行個體、 AWS Lambda 函數或 Amazon Elastic Container Service (Amazon ECS) 服務。
+ [AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/welcome.html) 可協助您快速建模和設定軟體版本的不同階段，並自動化持續發行軟體變更所需的步驟。

**其他工具**
+ [Draw.io Desktop](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](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>

遵循 [AWS Well-Architected DevOps 指南](https://docs.aws.amazon.com/wellarchitected/latest/devops-guidance/devops-guidance.html)中的最佳實務和建議[，並為多帳戶 DevOps 環境選擇 Git 分支策略](https://docs.aws.amazon.com/prescriptive-guidance/latest/choosing-git-branch-approach/)。這些可協助您有效地實作以主體為基礎的開發、促進協作、改善程式碼品質，以及簡化開發程序。

## 史詩
<a name="implement-a-trunk-branching-strategy-for-multi-account-devops-environments-epics"></a>

### 檢閱中繼線工作流程
<a name="reviewing-the-trunk-workflow"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢閱標準中繼線程序。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 部署管道參考架構](https://pipelines.devops.aws.dev/)
+ [什麼是 DevOps？](https://aws.amazon.com/devops/what-is-devops/)
+ [DevOps 資源](https://aws.amazon.com/devops/resources/)

**中繼線指引**
+ [以中繼線為基礎的開發](https://trunkbaseddevelopment.com/)

**其他資源**
+ [十二因素應用程式方法 ](https://12factor.net/)(12factor.net：//)

# 實作集中式自訂 Checkov 掃描，以在部署 AWS 基礎設施之前強制執行政策
<a name="centralized-custom-checkov-scanning"></a>

*Benjamin Morris，Amazon Web Services*

## 總結
<a name="centralized-custom-checkov-scanning-summary"></a>

此模式提供 GitHub Actions 架構，可在一個儲存庫中撰寫自訂 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)，然後選擇服務的連結。

## Architecture
<a name="centralized-custom-checkov-scanning-architecture"></a>

此模式旨在部署為 GitHub 儲存庫，其中包含 GitHub 可重複使用的工作流程和自訂 Checkov 政策。可重複使用的工作流程可以將 Terraform 和 CloudFormation 基礎設施掃描為程式碼 (IaC) 儲存庫。

下圖以個別圖示顯示**可重複使用的 GitHub 工作流程儲存庫**和**自訂 Checkov 政策儲存庫**。不過，您可以將這些儲存庫實作為個別儲存庫或單一儲存庫。範例程式碼使用單一儲存庫，其中包含工作流程 (`.github/workflows`) 的檔案，以及相同儲存庫中自訂政策 `.checkov.yml` (`custom_policies` 資料夾和組態檔案） 的檔案。

![\[GitHub 動作使用可重複使用的 GitHub 工作流程和自訂 Checkov 政策來評估 IaC。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/6c0c941f-14f9-4569-92da-9f81ab3e525c/images/a1539ce5-0ee6-4af1-bd01-cafad0f71708.png)


該圖顯示以下工作流程：

1. 使用者在 GitHub 儲存庫中建立提取請求。

1. 管道工作流程從 GitHub 動作開始，包括對 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 Actions](https://github.com/features/actions) 已整合至 GitHub 平台，協助您在 GitHub 儲存庫中建立、共用和執行工作流程。您可以使用 GitHub 動作來自動化任務，例如建置、測試和部署程式碼。
+ [Terraform](https://www.terraform.io/) 是 HashiCorp 的 IaC 工具，可協助您建立和管理雲端和內部部署資源。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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立中央 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 新增可重複使用的 Checkov 工作流程。 | 在可重複使用的工作流程儲存庫中建立可重複使用的 Checkov GitHub 動作工作流程 (YAML 檔案）。您可以從此模式提供的工作流程檔案中調整此可重複使用的工作流程。您可能想要進行的變更範例是將可重複使用的工作流程變更為使用軟失敗選項。`soft-fail` 將 設定為 `true` 可讓任務順利完成，即使 Checkov 掃描失敗也一樣。如需說明，請參閱 Checkov 文件中的[硬性與軟性故障](https://www.checkov.io/2.Basics/Hard%20and%20soft%20fail.html)。 | DevOps 工程師 | 
| 新增工作流程範例。 | 新增參考工作流程的範例 Checkov `reusable`工作流程。這將提供範本，說明如何重複使用`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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 決定可使用 Checkov 強制執行的政策。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將 Checkov 可重複使用工作流程新增至所有儲存庫。 | 此時，您應該有一個參考可重複使用工作流程的範例 Checkov 工作流程。將參考可重複使用工作流程的範例 Checkov 工作流程複製到每個需要該工作流程的儲存庫。 | DevOps 工程師 | 
| 建立機制以確保 Checkov 在合併之前執行。 | 為了確保針對每個提取請求執行 Checkov 工作流程，請建立需要成功 Checkov 工作流程才能合併提取請求[的狀態檢查](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/collaborating-on-repositories-with-code-quality-features/about-status-checks)。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`如果儲存庫是圍繞分支建構的，您可以將目標`production`分支的名稱從 `main` 調整為 。

**保護 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 整合實作採用 AI 技術的 Kubernetes 診斷和故障診斷
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration"></a>

*Ishwar Chauthaiwale， Muskan . 和 Amazon Web Services Prafful Gupta*

## 總結
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-summary"></a>

此模式示範如何透過將 K8sGPT 與 Amazon Bedrock 上提供的 Anthropic Claude v2 模型整合，來實作 AI 支援的 Kubernetes 診斷和故障診斷。解決方案透過安全的堡壘主機架構，為 Kubernetes 叢集問題提供自然語言分析和修復步驟。透過將 K8sGPT Kubernetes 專業知識與 Amazon Bedrock 進階語言功能結合，DevOps 團隊可以快速識別和解決叢集問題。透過這些功能，可以將平均解析時間 (MTTR) 減少高達 50%。

這種雲端原生模式利用 Amazon Elastic Kubernetes Service (Amazon EKS) 進行 Kubernetes 管理。模式會透過適當的 AWS Identity and Access Management (IAM) 角色和網路隔離實作安全最佳實務。此解決方案對於想要簡化 Kubernetes 操作並在 AI 協助下增強故障診斷功能的組織特別有用。

## 先決條件和限制
<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 模型
+ 具有必要安全群組設定的堡壘主機
+ [已安裝](https://docs.k8sgpt.ai/getting-started/installation/) K8sGPT 

**限制**
+ 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 [0.4.2 版或更新版本](https://github.com/k8sgpt-ai/k8sgpt/releases)

## Architecture
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-architecture"></a>

下圖顯示使用與 Amazon Bedrock 整合之 K8sGPT 的 AI 型 Kubernetes 診斷架構 AWS 雲端。

![\[使用與 Amazon Bedrock 整合之 K8sGPT 的 Kubernetes 診斷工作流程。\]](http://docs.aws.amazon.com/zh_tw/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 控制平面和工作者節點，提供 K8sGPT 分析的目標環境。此服務會跨虛擬私有雲端 (VPC) 內的多個可用區域執行，這有助於提供高可用性和彈性。Amazon EKS 透過 Kubernetes API 提供操作資料，實現全面的叢集分析。

1. K8sGPT 會將分析資料傳送至 Amazon Bedrock，提供 Claude v2 基礎模型 (FM) 以進行自然語言處理。服務會處理 K8sGPT 分析，以產生人類可讀的說明，並根據已識別的問題提供詳細的修補建議。Amazon Bedrock 以無伺服器 AI 服務的形式運作，具有高可用性和可擴展性。

**注意**  
在此工作流程中，IAM 透過角色和政策控制元件之間的存取，管理堡壘主機、Amazon EKS 和 Amazon Bedrock 互動的身分驗證。IAM 實作最低權限原則，並在整個架構中啟用安全的跨服務通訊。

**自動化和擴展**

K8sGPT 操作可以透過各種 和 工具，自動化 AWS 服務 並跨多個 Amazon EKS 叢集進行擴展。此解決方案支援使用 [Jenkins](https://www.jenkins.io/)、[GitHub Actions](https://docs.github.com/en/actions/get-started/understand-github-actions) 或 [AWS CodeBuild](https://docs.aws.amazon.com/codebuild/latest/userguide/welcome.html) 進行排程分析的持續整合和持續部署 (CI/CD) 整合。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 中的命令與 互動。
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) 可協助您在 上執行 Kubernetes， AWS 而無需安裝或維護您自己的 Kubernetes 控制平面或節點。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。

**其他工具**
+ [K8sGPT](https://k8sgpt.ai/) 是一種開放原始碼 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://aws.amazon.com/solutions/guidance/data-anonymization-on-aws/)。 [https://docs.aws.amazon.com/awscloudtrail/latest/userguide/monitor-cloudtrail-log-files-with-cloudwatch-logs.html](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/monitor-cloudtrail-log-files-with-cloudwatch-logs.html)
+ 維護 K8sGPT 組態的定期備份，同時在離峰時間設定自動掃描排程，以將操作影響降至最低。

## 史詩
<a name="implement-ai-powered-kubernetes-diagnostics-and-troubleshooting-with-k8sgpt-and-amazon-bedrock-integration-epics"></a>

### 將 Amazon Bedrock 新增至 AI 後端供應商清單。
<a name="add-br-to-ai-backend-provider-list"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將 Amazon Bedrock 設定為 K8sGPT 的 AI 後端提供者。 | 若要將 Amazon Bedrock 設定為 AI [後端為 K8sGPT 提供](https://docs.k8sgpt.ai/reference/providers/backend/) r，請使用下列 AWS CLI 命令： K8sGPT<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` 是否已新增至 AI 後端提供者清單且處於 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 檢視可用的篩選條件清單。 | 若要查看所有可用篩選條件的清單，請使用下列 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 取得詳細輸出。 |  若要取得詳細輸出，請使用下列 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_tw/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 部落格**
+ [使用 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 命令：[create-cluster](https://docs.aws.amazon.com/cli/latest/reference/eks/create-cluster.html) 和 [describe-cluster](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/eks/describe-cluster.html)
+ [開始使用 Amazon EKS](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html) (Amazon EKS 文件）
+ [IAM 中的安全最佳實務 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)(IAM 文件）

**其他資源**
+ [K8sGPT](https://k8sgpt.ai/)

# 在 CodeCommit 中自動偵測變更並啟動單一儲存庫的不同 CodePipeline 管道 CodeCommit
<a name="automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit"></a>

*Helton Ribeiro、Petrus Batalha 和 Amazon Web Services Ricardo Morais*

## 總結
<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/)

此模式可協助您在 中自動偵測單一儲存庫型應用程式的原始碼變更， AWS CodeCommit 然後在 中啟動管道 AWS CodePipeline ，以針對每個微服務執行持續整合和持續交付 (CI/CD) 自動化。此方法表示單一儲存庫型應用程式中的每個微服務都可以有專用的 CI/CD 管道，以確保更佳的可見性、更輕鬆地共用程式碼，並改善協同合作、標準化和可探索性。

此模式中描述的解決方案不會在 monorepo 內的微服務之間執行任何相依性分析。它只會偵測原始程式碼中的變更，並啟動相符的 CI/CD 管道。

模式使用 AWS Cloud9 做為整合式開發環境 (IDE) AWS Cloud Development Kit (AWS CDK) ，並使用兩個 CloudFormation 堆疊定義基礎設施： `MonoRepoStack`和 `PipelinesStack`。`MonoRepoStack` 堆疊會在 中建立單儲存庫， AWS CodeCommit 以及啟動 CI/CD 管道的 AWS Lambda 函數。`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 Cloud9](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/build-a-loosely-coupled-architecture-with-microservices-using-devops-practices-and-aws-cloud9.html)。 AWS  

## Architecture
<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_tw/prescriptive-guidance/latest/patterns/images/pattern-img/a3397158-a208-4033-844e-969af13ae8b6/images/b0bb1094-b598-4b3d-ab8b-ad9b0eb45f38.png)


該圖顯示以下工作流程：

1. 引導程序會使用 AWS CDK 來建立 AWS CloudFormation 堆疊 `MonoRepoStack`和 `PipelinesStack`。

1. `MonoRepoStack` 堆疊會為您的應用程式建立 CodeCommit 儲存庫，以及在每次遞交後啟動的 `monorepo-event-handler` Lambda 函數。

1. `PipelinesStack` 堆疊會在 CodePipeline 中建立由 Lambda 函數啟動的管道。每個微服務都必須有定義的基礎設施管道。

1. 的管道由 Lambda 函數`microservice-n`啟動，並啟動以 CodeCommit 中的原始程式碼為基礎的隔離 CI/CD 階段。

1. 的管道由 Lambda 函數`microservice-1`啟動，並啟動以 CodeCommit 中的原始程式碼為基礎的隔離 CI/CD 階段。

下圖顯示 `PipelinesStack`帳戶中 AWS CloudFormation 堆疊 `MonoRepoStack`和 的部署。

![\[在 AWS 帳戶中部署 CloudFormation 堆疊 MonoRepoStack 和 PipelinesStack。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/a3397158-a208-4033-844e-969af13ae8b6/images/39e60e49-dea2-486d-8a2c-6cae438f69b4.png)


1. 使用者變更其中一個應用程式的微服務中的程式碼。

1. 使用者會將變更從本機儲存庫推送到 CodeCommit 儲存庫。

1. 推送活動會啟動接收所有推送至 CodeCommit 儲存庫的 Lambda 函數。

1. Lambda 函數會讀取 參數存放區中的參數，這是 的一項功能 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/) 是一種程式設計語言，可讓您快速工作並更有效地整合系統。

**Code**

此模式的原始程式碼和範本可在 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) 文件》中的[使用 CloudWatch Application Insights 監控無伺服器應用程式](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-nag](https://github.com/cdklabs/cdk-nag) 公用程式來檢查 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 修訂版 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立虛擬 Python 環境。 | 在您的 AWS Cloud9 IDE 中，透過執行下列命令，建立虛擬 Python 環境並安裝所需的相依性：`make install` | 開發人員 | 
|  AWS 區域 為 引導 AWS 帳戶 和 AWS CDK。 | 執行下列命令來引導所需的 AWS 帳戶 和 區域：`make bootstrap account-id=<your-AWS-account-ID> region=<required-region>` | 開發人員 | 

### 新增微服務的新管道
<a name="add-a-new-pipeline-for-a-microservice"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
|  將範例程式碼新增至應用程式目錄。 | 將包含範例應用程式程式碼的目錄新增至複製的 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 AWS CloudFormation 堆疊。 | 執行 AWS CloudFormation `MonoRepoStack``make deploy-core`命令，在複製儲存庫的根目錄中部署具有預設參數值的堆疊。您可以執行 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除您的 AWS CloudFormation 堆疊。 | 執行 `make destroy` 命令。 | 開發人員 | 
| 刪除管道的 S3 儲存貯體。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html) | 
| 我需要重新部署所有微服務。 | 強制重新部署所有微服務的方法有兩種。選擇符合您需求的選項。**方法 1：刪除參數存放區中的參數**此方法涉及在 Systems Manager 參數存放區中刪除特定參數，以追蹤用於部署的最後一個遞交 ID。當您移除此參數時，系統會強制在下一次觸發時重新部署所有微服務，因為它會將其視為全新狀態。步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/automatically-detect-changes-and-initiate-different-codepipeline-pipelines-for-a-monorepo-in-codecommit.html)**方法 2：在每個 monorepo 子資料夾中推送遞交**此方法涉及進行次要變更，並在單一儲存庫中的每個微服務子資料夾中推送，以啟動其個別管道。步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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 管道的持續整合和交付 (CI/CD)](https://docs.aws.amazon.com/cdk/latest/guide/cdk_pipeline.html) (AWS CDK 文件）
+ [aws-cdk/pipelines 模組](https://docs.aws.amazon.com/cdk/api/latest/docs/pipelines-readme.html) (AWS CDK API 參考）

# 使用 AWS CloudFormation 將 Bitbucket 儲存庫與 AWS Amplify 整合
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation"></a>

*Alwin Abraham，Amazon Web Services*

## 總結
<a name="integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation-summary"></a>

AWS Amplify 可協助您快速部署和測試靜態網站，而無需設定通常需要的基礎設施。如果您的組織想要使用 Bitbucket 進行來源控制，無論是遷移現有的應用程式程式碼還是建立新的應用程式，都可以部署此模式的方法。透過使用 AWS CloudFormation 自動設定 Amplify，您可以查看所使用的組態。

此模式說明如何使用 AWS CloudFormation 將 Bitbucket 儲存庫與 AWS Amplify 整合，以建立前端持續整合和持續部署 (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 格式的檔案

## Architecture
<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_tw/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 可協助開發人員開發和部署雲端驅動的行動和 Web 應用程式。
+ [AWS CloudFormation](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html) – AWS CloudFormation 是一項服務，可協助您建立和設定 AWS 資源的模型，以減少管理這些資源的時間，並有更多時間專注於在 AWS 中執行的應用程式。
+ [Bitbucket](https://bitbucket.org/) – Bitbucket 是專為專業團隊設計的 Git 儲存庫管理解決方案。它可讓您集中管理 Git 儲存庫、協作您的原始程式碼，並引導您完成開發流程。

 

**Code**

`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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| （選用） 建立 Bitbucket 儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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_tw/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 ``SECRET` 將 `KEY`和 取代為您先前記錄的金鑰和秘密。 2. 不使用引號記錄存取字符。字符僅在有限時間內有效，預設時間為兩小時。您必須在此時間範圍內執行 AWS CloudFormation 範本。 | DevOps 工程師 | 

### 建立和部署 AWS CloudFormation 堆疊
<a name="create-and-deploy-the-aws-cloudformation-stack"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
|  下載 AWS CloudFormation 範本。 | 下載 `bitbucket-amplify.yml` AWS CloudFormation 範本 （已連接）。除了 Amplify 專案和分支之外，此範本還會在 Amplify 中建立 CI/CD 管道。 |  | 
| 建立和部署 AWS CloudFormation 堆疊。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將程式碼部署到儲存庫中的分支。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/integrate-a-bitbucket-repository-with-aws-amplify-using-aws-cloudformation.html)如需詳細資訊，請參閱 Bitbucket 文件中的[基本 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*

## 總結
<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 專案。 AWS Step Functions AWS Lambda 您可以使用模式的範例 Step Functions 狀態機器來測試 CodeBuild 專案的成功。

CodeBuild 可協助您從全受管執行期環境使用 AWS Command Line Interface (AWS CLI) 啟動操作任務。您可以透過覆寫環境變數，在執行時間變更 CodeBuild 專案的行為。此外，您可以使用 CodeBuild 來管理工作流程。如需詳細資訊，請參閱 AWS 研討會網站上的 [Service Catalog 工具](https://service-catalog-tools-workshop.com/tools.html)，以及 AWS 資料庫部落格[中的使用 AWS CodeBuild 和 Amazon EventBridge 在 Amazon RDS for PostgreSQL 中排程任務](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)。

## Architecture
<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_tw/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_tw/prescriptive-guidance/latest/patterns/images/pattern-img/809a5716-56e5-477c-aac6-02243675a2f2/images/4729bbfc-79ad-455d-a85a-b96cce00f432.png)


**技術堆疊**
+ AWS CloudFormation
+ CodeBuild：
+ IAM
+ Lambda
+ 步驟函數
+ 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 設計](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 (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 服務來建置業務關鍵應用程式。
+ [AWS X-Ray](https://docs.aws.amazon.com/xray/latest/devguide/aws-xray.html) 可協助您收集應用程式提供的請求相關資料，並提供可用來檢視、篩選和深入了解該資料的工具，以識別問題和最佳化的機會。

**Code**

此模式的範例程式碼可在 GitHub[Cross Account CodeBuild Proxy](https://github.com/aws-samples/cross-account-codebuild-proxy) 儲存庫中使用。此模式使用適用於 Python 的 AWS Lambda Powertools 程式庫來提供記錄和追蹤功能。如需此程式庫及其公用程式的詳細資訊，請參閱 [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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 記錄 AWS IDs。 | 需要 AWS 帳戶 IDs才能跨帳戶設定存取權。記錄來源和目標帳戶的 AWS 帳戶 ID。如需詳細資訊，請參閱 IAM 文件中的[尋找您的 AWS 帳戶 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_tw/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_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立和部署 AWS CloudFormation 堆疊。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動狀態機器。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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*

## 摘要
<a name="multi-az-failover-spark-emr-clusters-arc-summary"></a>

此模式為 Amazon EMR 工作負載提供有效的災難復原策略，以協助確保單一區域內多個可用區域的高可用性和資料一致性 AWS 區域。此設計使用 [Amazon Application Recovery Controller](https://docs.aws.amazon.com/r53recovery/latest/dg/what-is-route53-recovery.html) 和 [Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html) 來管理 Apache Spark 型 EMR 叢集的容錯移轉操作和流量分佈。

在標準條件下，主要可用區域會託管具有完整讀取/寫入功能的作用中 EMR 叢集和應用程式。如果可用區域意外故障，流量會自動重新導向至次要可用區域，其中會啟動新的 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/)
+ [Amazon Elastic Compute Cloud (Amazon EC2) 上的 Amazon EMR](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-what-is-emr.html) Amazon 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)

## Architecture
<a name="multi-az-failover-spark-emr-clusters-arc-architecture"></a>

**目標技術堆疊**
+ Amazon EMR 叢集
+ Amazon 應用程式復原控制器說明
+ Application Load Balancer
+ Amazon S3 儲存貯體
+ Amazon S3 閘道端點

**目標架構**

![\[使用 Application Recovery Cotnroller 的自動化復原機制架構。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/e5ecdb66-0eef-4a6a-8367-982a55104748/images/e982d580-13db-4bdd-9f6b-6400d7c31c01.png)


此架構使用多個可用區域並透過應用程式復原控制器實作自動化復原機制，以提供應用程式彈性。

1. Application Load Balancer 會將流量路由到作用中的 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 Application Recovery Controller](https://docs.aws.amazon.com/r53recovery/latest/dg/what-is-route53-recovery.html)** **可協助您管理和協調跨 和 AWS 區域 可用區域的應用程式復原。此服務透過減少傳統工具和程序所需的手動步驟，簡化程序並改善應用程式復原的可靠性。
+ [Application Load Balancer](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/introduction.html) 在應用程式層操作，這是開放系統互連 (OSI) 模型的第七層。它將傳入的應用程式流量分散到多個可用區域中的多個目標，例如 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 Access Grants 來管理從 Spark 型 EMR 叢集到 Amazon S3 的存取權。如需詳細資訊，請參閱部落格文章[使用 Amazon EMR 搭配 S3 存取授權擴展 Amazon S3 的 Spark 存取](https://aws.amazon.com/blogs/big-data/use-amazon-emr-with-s3-access-grants-to-scale-spark-access-to-amazon-s3/)。
+ [使用 Amazon 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 登入 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 S3 儲存貯體。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/multi-az-failover-spark-emr-clusters-arc.html) | AWS DevOps | 

### 將流量轉移到另一個可用區域
<a name="shift-traffic-to-another-availability-zone"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 Application Load Balancer。 | 設定目標群組，在 內跨兩個可用區域部署的 Amazon EMR 主節點之間路由流量 AWS 區域。如需說明，請參閱 Elastic Load Balancing [ Load Balancing 文件中的為 Application Load Balancer 建立目標群組](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_tw/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_tw/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)
+ [設定 Spot 執行個體的 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 多區域金鑰，管理將微服務部署至多個帳戶和區域的藍/綠部署
<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*

## 摘要
<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 帳戶部署到多個工作負載帳戶和區域。模式支援下列項目：
+ 軟體是在中央帳戶中開發，而工作負載和應用程式則分散在多個帳戶和 AWS 區域。
+ 單一 AWS Key Management System (AWS KMS) 多區域金鑰用於加密和解密，以涵蓋災難復原。
+ KMS 金鑰是區域特定的，必須在管道成品的三個不同區域中維護或建立。KMS 多區域金鑰有助於跨區域保留相同的金鑰 ID。
+ Git 工作流程分支模型使用兩個分支 （開發和主要） 實作，並使用提取請求 (PRs) 合併程式碼。從此堆疊部署的 AWS Lambda 函數會建立從開發分支到主分支的 PR。合併到主分支的 PR 會啟動 AWS CodePipeline 管道，協調持續整合和持續交付 (CI/CD) 流程，並在帳戶之間部署堆疊。

此模式 透過 AWS CloudFormation 堆疊提供做為程式碼 (IaC) 設定的範例基礎設施，以示範此使用案例。使用 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>

**先決條件**
+ 四個作用中的 AWS 帳戶：
  + 用於管理程式碼管道和維護 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 和其他組態檔案來部署範例微服務。如果您有不同的工作負載類型 （例如無伺服器），您必須更新所有相關組態。

## Architecture
<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_tw/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 Elastic Compute Cloud (Amazon EC2) 或內部部署執行個體、AWS Lambda 函數或 Amazon Elastic Container Service (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 全域藍/綠部署中使用。 [https://github.com/aws-samples/ecs-blue-green-global-deployment-with-multiregion-cmk-codepipeline](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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 匯出 CloudFormation 堆疊部署的環境變數。 | 定義稍後在此模式中將用作 CloudFormation 堆疊輸入的環境變數。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 | 

### 封裝和部署基礎設施的 CloudFormation 堆疊
<a name="package-and-deploy-the-cloudformation-stacks-for-the-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製儲存庫。 | 將[範例儲存庫](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 Virtual Private Cloud (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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將範例映像推送至 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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在工具帳戶中建立 CodeCommit 儲存庫。 | 使用位於 GitHub 儲存庫`code`資料夾的 `codecommit.yaml` 範本，在工具帳戶中建立 CodeCommit 儲存庫。您只能在計劃開發程式碼的單一區域中建立此儲存庫。<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 產生的成品。 | 使用位於 GitHub 儲存庫 `code` 資料夾中的 `pre-reqs-bucket.yaml` 範本，建立 S3 儲存貯體來管理 CodePipeline 產生的成品。堆疊必須部署在所有三個工作負載 （測試） 和工具帳戶和區域中。<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_tw/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_tw/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 叢集的 Amazon Resource Name (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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在工具帳戶中建立程式碼管道。 | 在工具帳戶中，執行 命令：<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 金鑰政策和 S3 儲存貯體政策中提供 CodePipeline 和 CodeBuild 角色的存取權。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將變更推送至 CodeCommit 儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除所有已部署的資源。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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 CloudFormation 和 AWS Config 監控 Amazon 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*

## 總結
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-summary"></a>

在 Amazon Web Services (AWS) 雲端上，Amazon Elastic Container Registry (Amazon ECR) 是一種受管容器映像登錄服務，使用 AWS Identity and Access Management (IAM) 支援具有資源型許可的私有儲存庫。

IAM 在資源和動作屬性中都支援「`*`」萬用字元，這可讓您更輕鬆地自動選擇多個相符項目。在您的測試環境中，您可以在儲存庫政策陳述式的主體元素中使用`ecr:*`[萬用字元許可](https://docs.aws.amazon.com/lambda/latest/operatorguide/wildcard-permissions-iam.html)，允許所有已驗證的 AWS 使用者存取 Amazon ECR 儲存庫。 [https://docs.aws.amazon.com/AmazonECR/latest/userguide/set-repository-policy.html](https://docs.aws.amazon.com/AmazonECR/latest/userguide/set-repository-policy.html)萬`ecr:*`用字元許可在無法存取生產資料的開發帳戶中開發和測試時非常有用。

不過，您必須確定您的生產環境中未使用`ecr:*`萬用字元許可，因為它可能會導致嚴重的安全漏洞。此模式的方法可協助您識別儲存庫政策陳述式中包含`ecr:*`萬用字元許可的 Amazon ECR 儲存庫。  模式提供步驟和 AWS CloudFormation 範本，以在 AWS Config 中建立自訂規則。然後AWS Lambda 函數會監控您的 Amazon ECR 儲存庫政策陳述式是否有`ecr:*`萬用字元許可。如果找到不合規的儲存庫政策陳述式，Lambda 會通知 AWS Config 將事件傳送至 Amazon EventBridge，然後 EventBridge 會啟動 Amazon Simple Notification Service (Amazon SNS) 主題。SNS 主題會透過電子郵件通知您不合規的儲存庫政策陳述式。

## 先決條件和限制
<a name="monitor-amazon-ecr-repositories-for-wildcard-permissions-using-aws-cloudformation-and-aws-config-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 安裝並設定 AWS Command Line Interface (AWS CLI)。如需詳細資訊，請參閱 [AWS CLI 文件中的安裝、更新和解除安裝](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html) AWS CLI。
+ 具有附加政策陳述式的現有 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 
+ `aws-config-cloudformation.template` 檔案 （已連接），下載到您的本機電腦。

 

**限制**
+ 此模式的解決方案為區域性，您的資源必須在相同的區域中建立。 

## Architecture
<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_tw/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 資源、快速一致地佈建資源，以及在整個生命週期中管理資源。您可以使用範本來描述資源及其相依性，並將它們一起啟動和設定為堆疊，而不是個別管理資源。您可以管理和佈建跨多個 AWS 帳戶和 AWS 區域的堆疊。
+ [AWS Config](https://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html) – AWS Config 提供 AWS 帳戶中 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 的資源型許可。                                
+ [Amazon EventBridge](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-what-is.html) – 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 Notification Service (Amazon SNS) 會協調和管理發佈者和用戶端之間的訊息傳遞或傳送，包括 Web 伺服器和電子郵件地址。訂閱者會收到發佈到所訂閱主題的所有訊息，且某一主題的所有訂閱者均會收到相同訊息。 

**Code**

此模式的程式碼可在 `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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 測試 AWS Config 自訂規則。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 Actions 工作流程最佳化多帳戶無伺服器部署
<a name="optimize-multi-account-serverless-deployments"></a>

*Sarat Chandra Pothula 和 VAMSI KRISHNA SUNKAVALLI，Amazon Web Services*

## 總結
<a name="optimize-multi-account-serverless-deployments-summary"></a>

跨多個 AWS 帳戶 和環境部署無伺服器基礎設施的組織，通常會遇到重複程式碼、手動程序和不一致實務等挑戰。此模式的解決方案說明如何使用 Go 和 GitHub Actions 可重複使用工作流程 AWS Cloud Development Kit (AWS CDK) 中的 ，以簡化多帳戶無伺服器基礎設施管理。此解決方案示範如何將雲端資源定義為程式碼、實作標準化持續整合/持續部署 (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 Elastic Container Registry (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)。
+ Go 1.22 或更新版本，[已安裝](https://go.dev/doc/install)。
+ 已安裝 Docker 24.0.6 或更新版本。 [https://docs.docker.com/engine/install/](https://docs.docker.com/engine/install/)

**限制**
+ **語言相容性 **– Go 是無伺服器應用程式的熱門語言。不過，除了 Go 之外， 還 AWS CDK 支援其他程式設計語言，包括 C\$1、Java、Python 和 TypeScript。如果您的組織有現有的程式碼庫或其他語言的專業知識，您可能需要調整或學習 Go 以充分利用模式中描述的解決方案。
+ **學習曲線 **– 採用 AWS CDK、Go （如果是組織的新手） 和 GitHub 可重複使用的工作流程，可能涉及開發人員和 DevOps 團隊的學習曲線。可能需要訓練和文件，以確保這些技術的順利採用和有效使用。

## Architecture
<a name="optimize-multi-account-serverless-deployments-architecture"></a>

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

![\[多帳戶無伺服器基礎設施管理的 AWS CDK 和 GitHub Actions 工作流程架構。\]](http://docs.aws.amazon.com/zh_tw/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 工作流程使用 central AWS 帳戶 GitHub OIDC 角色 AWS 向 進行驗證。針對 CI 工作流程，Central AWS 帳戶 GitHub OIDC 角色會使用 AWS Security Token Service (AWS STS) 來取得臨時登入資料。這些登入資料可讓角色建置 Docker 映像並將其推送至中央的 Amazon ECR 儲存庫 AWS 帳戶。

1. CI 工作流程會將建置的 Docker 映像推送至 Amazon ECR。

1. CI 工作流程會將映像標籤儲存到 Systems Manager 參數存放區。

1. CI 工作流程成功完成後，系統會輸出 Docker 映像標籤。

1. 觸發 CD 工作流程時，開發人員會手動輸入要部署之 Docker 映像的映像標籤。此映像標籤對應於 CI 工作流程期間產生並推送至 Amazon ECR 的標籤。

1. 開發人員會手動觸發使用 CD 可重複使用工作流程的 CD 工作流程。

1. CD 工作流程 AWS 使用 central AWS 帳戶 GitHub OIDC 角色向 進行驗證。對於 CD 工作流程， AWS STS 會先用來擔任 central AWS 帳戶 GitHub OIDC 角色。然後，此角色會擔任目標帳戶部署的 CDK 引導角色。

1. CD 工作流程使用 AWS CDK 來合成 AWS CloudFormation 範本。

1. CD 工作流程 AWS 帳戶 會使用 CDK 部署，使用 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 參數存放區](https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-parameter-store.html)為組態資料管理和秘密管理提供安全的階層式儲存。

**其他工具**
+ [Docker](https://www.docker.com/) 是一組平台即服務 (PaaS) 產品，可在作業系統層級使用虛擬化在容器中交付軟體。
+ [GitHub Actions](https://docs.github.com/en/actions/writing-workflows/quickstart) 是與 GitHub 儲存庫緊密整合的持續整合和持續交付 (CI/CD) 平台。您可以使用 GitHub 動作來自動化建置、測試和部署管道。
+ [Go](https://go.dev/doc/install) 是 Google 支援的開放原始碼程式設計語言。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [aws-cdk-golang-serverless-cicd-github-actions](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 Budgets 和 等 AWS 成本最佳化服務 AWS Cost Explorer。
+ **災難復原和備份** – 透過實作無伺服器應用程式和基礎設施資源的備份和還原機制，規劃災難復原案例。
+ **持續改進** – 定期檢閱並更新您的實務、工具和程序，以符合無伺服器生態系統的最新最佳實務、安全建議和技術進展。
+ **改善安全狀態** – 透過為 Amazon ECR 和 AWS Systems Manager 參數存放區設定介面 VPC 端點 AWS Lambda，使用 [AWS PrivateLink](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html)來改善虛擬私有雲端 (VPC) 的安全狀態。

## 史詩
<a name="optimize-multi-account-serverless-deployments-epics"></a>

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在中央建立 Amazon ECR 儲存庫 AWS 帳戶。 | 若要跨多個 共用容器映像 AWS 帳戶，您必須設定 Amazon ECR 的跨帳戶存取。首先，在中央建立 Amazon ECR 儲存庫 AWS 帳戶。若要建立 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_tw/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html) | AWS DevOps | 
| 引導目標中的 AWS 環境 AWS 帳戶。 | 在特定 中設定 CDK 環境 AWS 區域 ， 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 引導會建立下列 IAM 角色，這些角色旨在由中央在 CDK 部署程序的各個階段 AWS 帳戶 中擔任：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製專案儲存庫。 | 若要複製此模式的 [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_Account_ID` 使用您的資訊修訂預留位置 `AWS_REGION`和 。 | AWS DevOps | 
| 建置 Docker 影像。 | 若要建置 Docker 映像，請執行下列命令：<pre>docker build --platform linux/arm64 -t sample-app .</pre> | AWS DevOps | 
| 標記並推送 Docker Image。 | 若要標記 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>使用`DOCKER_TAG`您的資訊修訂預留位置 `AWS_Account_ID`、`ECR_REPOSITORY`、 `AWS_REGION`和 。 | AWS DevOps | 

### 部署 AWS CDK 應用程式
<a name="deploy-the-cdk-app"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用環境特定變數來合成 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_tw/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 | 

### 使用 GitHub 動作工作流程自動化 CI/CD
<a name="automate-ci-cd-using-github-actions-workflows"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立功能分支，並新增您的變更。 | 使用您先前建立的複製儲存庫、建立功能分支，然後將您的變更新增至應用程式程式碼。使用下列命令：<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_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/optimize-multi-account-serverless-deployments.html) | 
| 例如，`Error: No such file or directory`由於不正確的 YAML 組態或受保護`Permission denied`的分支，CI/CD 管道失敗。 | 為了協助解決 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 雲端開發套件程式庫](https://pkg.go.dev/github.com/aws/aws-cdk-go/awscdk/v2)
+ [使用容器映像建立 Lambda 函數](https://docs.aws.amazon.com/lambda/latest/dg/images-create.html)
+ [Amazon Elastic Container Registry 的 Identity and Access Management](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)

**其他資源**
+ 在 [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 文件）
+ [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*

## 摘要
<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 雲端。此模式也會使用 [GitHub 動作](https://github.com/features/actions)，將基礎設施即程式碼 (IaC) 整合到自動化開發工作流程中，藉此提升 DevOps 實務。

AWS Service Catalog 可讓組織在 上建立和管理核准的 IT 服務 AWS，提供標準化、集中式控制、自助式佈建和成本管理等優勢。透過 GitHub Actions 自動化 Service Catalog 產品組合和產品的部署，公司可以執行下列動作：
+ 實現一致且可重複的部署。
+ 使用 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
+ 用於託管 CloudFormation 範本的 Amazon Simple Storage Service (Amazon S3) 儲存貯體
+ 名為 `github-actions`的 AWS Identity and Access Management (IAM) 角色，用於 GitHub 和 之間的連線 AWS

**限制 **
+ 此模式的可重複使用程式碼已僅使用 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`

## Architecture
<a name="provision-aws-service-catalog-products-using-github-actions-architecture"></a>

下圖顯示此解決方案的架構。

![\[使用 GitHub 動作根據 CloudFormation 範本佈建 Service Catalog 產品。\]](http://docs.aws.amazon.com/zh_tw/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 動作會使用 OpenID Connect (OIDC) 供應商來佈建 Service Catalog 來觸發連線至 AWS 雲端 的工作流程。

1. Service Catalog 包含開發人員可以直接用來佈建標準化 AWS 資源的產品組合和產品。此模式會綁定 AWS 資源，例如虛擬私有雲端 (VPCs)、子網路、NAT 和網際網路閘道，以及路由表。

1. 開發人員建立 Service Catalog 產品後，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 Actions](https://docs.github.com/en/actions) 是與 GitHub 儲存庫緊密整合的持續整合和持續交付 (CI/CD) 平台。您可以使用 GitHub 動作來自動化建置、測試和部署管道。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [service-catalog-with-github-actions](https://github.com/aws-samples/service-catalog-with-github-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 產品組合和 Service Catalog 產品的資源。範本包含一組參數，用於佈建 Service Catalog 產品組合和產品。一個參數接受`vpc.yaml`範本上傳所在的 Amazon S3 檔案 URL。雖然此模式包含用來佈建 AWS 資源`vpc.yaml`的檔案，但您也可以使用參數 S3 檔案 URL 進行組態。
  + `vpc.yaml` – 此 CloudFormation 範本包含要在 Service Catalog product. AWS resources 中新增 AWS 的資源，包括 VPCs、子網路、網際網路閘道、NAT 閘道和路由表。`vpc.yaml` 範本是如何使用任何 CloudFormation 範本搭配 Service Catalog 產品和產品組合範本的範例。

## 最佳實務
<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)。 GitHub 

## 史詩
<a name="provision-aws-service-catalog-products-using-github-actions-epics"></a>

### 設定本機工作站
<a name="set-up-local-workstation"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在您的本機工作站設定 Git。 | 若要在本機工作站上安裝和設定 Git，請使用 [Git 文件中的入門 – 安裝](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git) Git 說明。 | 應用程式開發人員 | 
| 複製 GitHub 專案儲存庫。 | 若要複製 GitHub 專案儲存庫，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | DevOps 工程師 | 

### 設定 OIDC 提供者
<a name="set-up-the-oidc-provider"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定 OIDC 提供者。 | 建立 OpenID Connect (OIDC) 提供者，允許 GitHub 動作工作流程存取其中的資源 AWS，而不需要將 AWS 登入資料存放為長期的 GitHub 秘密。如需說明，請參閱 GitHub 文件[中的在 Amazon Web Services 中設定 OpenID Connect](https://docs.github.com/en/actions/deployment/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services)。設定 OIDC 供應商後，先前[在先決條件](#provision-aws-service-catalog-products-using-github-actions-prereqs)中`github-actions`提到的 IAM 角色 的信任政策將會更新。 | AWS 管理員、AWS DevOps、一般 AWS | 

### 觸發 GitHub 動作管道以部署 Service Catalog 產品組合和產品
<a name="trigger-github-actions-pipeline-to-deploy-sc-portfolio-and-products"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 更新 `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_tw/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | DevOps 工程師 | 

### 驗證部署
<a name="validate-deployment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證 Service Catalog 資源。 | 若要驗證 Service Catalog 資源，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/provision-aws-service-catalog-products-using-github-actions.html) | AWS DevOps | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除 CloudFormation 堆疊。 | 若要刪除 CloudFormation 堆疊，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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) CloudFormation  | 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_tw/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) 相關的螢幕擷取畫面，請前往此模式 GitHub 儲存庫中的**映像**資料夾。可用的螢幕擷取畫面如下：
+ [AWS Service Catalog 產品組合，管理區段](https://github.com/aws-samples/service-catalog-with-github-actions/blob/main/images/SC_portfolio.png)
+ [AWS Service Catalog product， 管理區段](https://github.com/aws-samples/service-catalog-with-github-actions/blob/main/images/SC_Product.png)
+ [AWS Service Catalog product、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*

## 總結
<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的許可。角色是透過 AWS Control Tower Account Factory 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 組織，用於透過 GitHub 動作將基礎設施部署為程式碼 (IaC)。(*不需要*** **GitHub Enterprise/Premium/Ultimate。)
+ 多帳戶 AWS 環境。此環境不需要是 的一部分 AWS Organizations。
+ 在 all 中部署 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)並[設定](https://developer.hashicorp.com/terraform/language/providers/configuration) Terraform AWS Provider 第 4 版或更新版本。

**限制**
+ 此模式的程式碼專屬於 GitHub Actions 和 Terraform。不過，模式的一般概念可以在其他持續整合和交付 (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)，然後選擇服務的連結。

## Architecture
<a name="provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution-architecture"></a>

下圖說明此模式的工作流程。

![\[使用 GitHub 動作自動化 IAM 角色建立和部署的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/215c590e-0c84-411d-be6e-b1739f1e19d2/images/82fcdc9f-9576-4e7c-b7fe-b45046ba79d2.png)


角色自動販賣機的典型使用工作流程包含下列步驟：

1. 開發人員將包含新請求 IAM 角色 Terraform 程式碼的程式碼推送至 RVM GitHub 儲存庫。此動作會觸發 RVM GitHub 動作管道。

1. 管道使用 OpenID Connect (OIDC) 信任政策來擔任 RVM 角色擔任角色。

1. 當 RVM 管道執行時，它會在佈建開發人員新 IAM 角色的帳戶中擔任 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 Actions](https://docs.github.com/en/actions/writing-workflows/quickstart) 是與 GitHub 儲存庫緊密整合的持續整合和持續交付 (CI/CD) 平台。您可以使用 GitHub 動作來自動化建置、測試和部署管道。
+ [Terraform](https://www.terraform.io/) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。

**程式碼儲存庫**

此模式的程式碼可在 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將範例儲存庫複製到您的 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_tw/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html) | DevOps 工程師 | 
| 判斷 RVM AWS 帳戶 的 。 | 決定 AWS 帳戶 要用於 RVM 的基礎設施部署。請勿使用 管理或根帳戶。 | 雲端架構師 | 
| （選用） 允許組織的管道建立 PRs。 | 只有在您想要允許`generate_providers_and_account_vars`工作流程建立 PRs時，才需要此步驟。若要允許組織的管道建立 PRs，請使用下列步驟：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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)。 GitHub  | DevOps 工程師 | 
| 將唯讀許可授予 RVM 帳戶。 | 在管理帳戶中建立授予 RVM 帳戶唯讀許可的委派政策。這可讓您的 RVM GitHub 工作流程在`generate_providers_and_account_vars.py`指令碼執行時動態提取 AWS 組織的帳戶清單。使用下列程式碼，並以您在步驟 2 中選取`<YOUR RVM Account ID>`的 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_tw/prescriptive-guidance/latest/patterns/provision-least-privilege-iam-roles-by-deploying-a-role-vending-machine-solution.html) | DevOps 工程師 | 

### 初始化基礎設施
<a name="initialize-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 引導 RVM 儲存庫。 | 此步驟是建立 RVM 管道本身使用的 OIDC 信任和 IAM 角色的必要步驟，因此可以開始操作和販賣其他角色。在您的 RVM 帳戶內容中，從 `scripts/bootstrap`目錄手動執行`terraform apply`命令。根據變數文件提供任何必要的值。 | DevOps 工程師 | 

### 設定操作
<a name="configure-operations"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將 `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_tw/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_tw/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) 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 信任政策中其他條件的語法範例。此語法指定只有在 GitHub 動作在`Production`環境中執行時，才能使用角色。

```
"StringLike": {
    "token.actions.githubusercontent.com:sub": "repo:octo-org/octo-repo:environment:Production"
}
```

範例語法使用下列預留位置值：
+ `octo-org` 是 GitHub 組織名稱。
+ `octo-repo` 是儲存庫名稱。
+ `Production` 是特定的 GitHub 環境名稱。

# 將 Amazon CloudWatch 指標發佈至 CSV 檔案
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file"></a>

*Abdullahi Olaoye，Amazon Web Services*

## 總結
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-summary"></a>

此模式使用 Python 指令碼擷取 Amazon CloudWatch 指標，並將指標資訊轉換為逗號分隔值 (CSV) 檔案，以提高可讀性。指令碼採用 AWS 服務，其指標應擷取為必要的引數。您可以將 AWS 區域和 AWS 登入資料設定檔指定為選用引數。如果您未指定這些引數，則指令碼會使用為執行指令碼的工作站設定的預設區域和設定檔。指令碼執行後，它會在相同的目錄中產生並儲存 CSV 檔案。

如需此模式提供的指令碼和相關檔案，請參閱*附件*一節。

## 先決條件和限制
<a name="publish-amazon-cloudwatch-metrics-to-a-csv-file-prereqs"></a>

**先決條件**
+ Python 3.x
+ AWS 命令列界面 (AWS CLI)

**限制**

指令碼目前支援下列 AWS 服務：
+ AWS Lambda
+ Amazon Elastic Compute Cloud (Amazon EC2)
  + 根據預設，指令碼不會收集 Amazon Elastic Block Store (Amazon EBS) 磁碟區指標。若要收集 Amazon EBS 指標，您必須修改連接的`metrics.yaml`檔案。
+ Amazon Relational Database Service (Amazon RDS)
  + 不過，指令碼不支援 Amazon Aurora。
+ Application Load Balancer
+ Network Load Balancer
+ 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝先決條件。 | 執行以下命令：<pre>$ pip3 install -r requirements.txt</pre> | 開發人員 | 
| 設定 AWS CLI。 | 執行以下命令： <pre>$ aws configure</pre> | 開發人員 | 

### 設定 Python 指令碼
<a name="configure-the-python-script"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 開啟指令碼。 | 若要變更指令碼的預設組態，請開啟 `metrics.yaml`。 | 開發人員 | 
| 設定指令碼的期間。 | 這是要擷取的期間。預設期間為 5 分鐘 (300 秒）。您可以變更期間，但請注意下列限制： [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行指令碼。 | 使用下列命令： <pre>$ python3 cwreport.py <service> </pre>若要查看服務值和選用 `region `和 `profile `參數的清單，請執行下列命令：<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)
+ [使用 Amazon CloudWatch 指標](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/working_with_metrics.html)
+ [Amazon CloudWatch 文件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/WhatIsCloudWatch.html)
+ [EC2 CloudWatch 指標](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)
+ [Application Load Balancer 指標](https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-cloudwatch-metrics.html)
+ [Network Load Balancer 指標](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 EC2、Amazon RDS、Application Load Balancer、Network Load Balancer 和 API Gateway。
+ **region （選用）** ‒ 要從中擷取指標的 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 設定檔並擷取 Amazon 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*

## 總結
<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 自動化，以快速尋找和移除非作用中的帳戶。

如果下列案例適用於您的組織，此模式可協助您：
+ **集中式 AD 管理** – 如果您的組織有多個 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](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)和設定 Git。
+ 在本機工作站上安裝[https://learn.hashicorp.com/tutorials/terraform/install-cli](https://learn.hashicorp.com/tutorials/terraform/install-cli)和設定 Terraform。
+ AWS Managed Microsoft AD 在父帳戶中設定並共用給所有子帳戶的 目錄。如需詳細資訊，請參閱《 *AWS Directory Service 管理指南*》中的[教學課程：共用您的 AWS Managed Microsoft AD 目錄以實現無縫 EC2 網域加入](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/ms_ad_tutorial_directory_sharing.html)。
+ 虛擬私有雲端 (VPC) 對等互連或 AWS Directory Service （父帳戶） 的 VPC 與 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體 （子帳戶） 的 VPC 之間可用的 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)。
+ 在所有父帳戶和子帳戶上設定`EC2WindowsUserdata`指令碼的 Windows 機器。指令碼檔案可在此模式[程式碼儲存庫](https://github.com/aws-samples/aws-lambda-ad-cleanup-terraform-samples/tree/main/multiple-account-cleanup)的根目錄中使用。
+ 每個子帳戶上可用的跨帳戶 AWS Identity and Access Management (IAM) 角色，這些子帳戶已設定信任政策，以允許使用父帳戶中的 AWS Lambda 函數。如需詳細資訊，請參閱《[Amazon EventBridge 使用者指南 AWS 帳戶 》中的在 Amazon EventBridge 中於 之間傳送和接收事件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/CloudWatchEvents-CrossAccountEventDelivery.html)。 * EventBridge *
+ 下列秘密值可在父帳戶的 AWS Systems Manager 參數存放區中使用：
  + `domainJoinUser` – 目錄服務的使用者名稱
  + `domainJoinPassword` – 目錄服務的密碼

  如需秘密的詳細資訊，請參閱*AWS Secrets Manager 《 使用者指南*》中的[建立 AWS Secrets Manager 秘密](https://docs.aws.amazon.com/secretsmanager/latest/userguide/create_secret.html)。

**限制**
+ 在子帳戶中建立資源不會使用 Terraform 自動化。您必須使用 手動建立下列資源 AWS 管理主控台：
  + 將 Amazon EC2 終止事件傳送至父帳戶的 Amazon EventBridge 規則
  + 使用信任政策在子帳戶中建立 Amazon 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 AWS Provider 3.0 版或更新版本](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/version-3-upgrade)

## Architecture
<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_tw/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 EC2 Auto Scaling 群組，並取得隨機執行個體 ID。執行個體 ID 用於執行 Systems Manager 命令。

1. Lambda 函數會使用 boto 模組對 Amazon 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 Parameter Store。 AWS Lambda Systems Manager 會呼叫 Parameter Store，並取得用來連線至 AD 的使用者名稱和密碼值。

1. 使用 Systems Manager 文件，PowerShell 指令碼會使用步驟 4 稍早取得的執行個體 ID 在 Amazon EC2 Windows 伺服器上執行。

1. Amazon EC2 AWS Directory Service 會使用 PowerShell 命令連線至 ，並移除未使用或非作用中的電腦。

## 工具
<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) 提供多種搭配其他 使用 Microsoft Active Directory (AD) 的方式， AWS 服務 例如 Amazon Elastic Compute Cloud (Amazon EC2)、適用於 SQL Server 的 Amazon Relational Database Service (Amazon RDS) 和適用於 Windows File Server 的 Amazon FSx。
+ [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 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 資源的存取。使用 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 參數存放區](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 上執行的 Microsoft 自動化和組態管理程式。
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [aws-lambda-ad-cleanup-terraform-samples](https://github.com/aws-samples/aws-lambda-ad-cleanup-terraform-samples/tree/main/multiple-account-cleanup) 儲存庫中使用。

## 最佳實務
<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 Active Directory](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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在子帳戶中建立跨帳戶角色。 | 若要在子帳戶中建立跨帳戶角色，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html)如需詳細資訊，請參閱《[Amazon EventBridge 使用者指南》中的在 Amazon EventBridge 中建立對事件做出反應的規則](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-create-rule.html)。* EventBridge * | DevOps 工程師 | 
| 建立 EC2 執行個體並加入 AD。 | 若要為 Windows 建立 EC2 執行個體，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立專案資料夾並新增檔案。 | 若要複製儲存庫並建立專案資料夾，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 提供 Terraform 變數的值。 | 對於子帳戶，請在 `terraform.tfvars` 檔案中以字串類型提供下列`arn`變數的值：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/remove-amazon-ec2-entries-across-aws-accounts-from-aws-managed-microsoft-ad.html) | DevOps 工程師 | 

### 驗證部署
<a name="verify-the-deployment"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行並測試 Lambda 函數。 | 若要驗證部署是否成功執行，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除基礎設施。 | 若要清除您建立的基礎設施，請使用下列命令：`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 Active Directory](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/join_windows_instance.html)
+ [使用 AWS Lambda 自動化 AWS 帳戶 從 移除相同 中的 Amazon EC2 AWS Managed Microsoft AD 項目](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 帳戶 從 移除相同 中的 Amazon EC2 AWS Managed Microsoft AD 項目
<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*

## 總結
<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](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)和設定 Git。
+ 在本機工作站上安裝[https://learn.hashicorp.com/tutorials/terraform/install-cli](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 具有[工具](#remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-tools)中 AWS 服務 所列 許可的 (IAM) 角色*。*如需 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 提供者 3.0 版或更新版本](https://registry.terraform.io/providers/hashicorp/aws/latest/docs/guides/version-3-upgrade)

## Architecture
<a name="remove-amazon-ec2-entries-in-the-same-aws-account-from-aws-managed-microsoft-ad-architecture"></a>

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

![\[使用 Lambda 自動化從 Managed Microsoft AD 移除 EC2 項目的程序。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/6b50dcc5-4f4b-4eea-85a7-04cebc9f7454/images/b7fc5962-bfb8-4f5a-968e-7487b1d48c4f.png)


該圖顯示以下工作流程：

1. Amazon EventBridge 會根據 Cron 表達式觸發 AWS Lambda 函數。（對於此模式，cron 表達式排程是每天一次。)

1. 必要的 IAM 角色和政策會透過 AWS Lambda Terraform 建立並連接至 。

1.  AWS Lambda 函數會執行，並使用 Python boto 模組呼叫 Amazon Elastic Compute Cloud (Amazon EC2) Auto Scaling 群組。Lambda 函數會取得隨機執行個體 ID。執行個體 ID 用於執行 AWS Systems Manager 命令。

1. AWS Lambda 使用 boto 模組對 Amazon EC2 進行另一個呼叫，並取得執行中 Windows 伺服器的私有 IP 地址，並將地址存放在暫時變數中。

1. AWS Lambda 會再次呼叫 Systems Manager，以取得連線的電腦資訊 Directory Service。

1.  AWS Systems Manager 文件有助於在 Amazon EC2 Windows 伺服器上執行 PowerShell 指令碼，以取得與 AD 連線之電腦的私有 IP 地址。

1. AD 網域使用者名稱和密碼存放在 AWS Systems Manager Parameter Store。 AWS Lambda Systems Manager 會呼叫 Parameter Store，並取得用於連接 AD 的使用者名稱和密碼值。

1. 使用 Systems Manager 文件，PowerShell 指令碼會使用步驟 3 稍早取得的執行個體 ID 在 Amazon EC2 Windows 伺服器上執行。

1. Amazon EC2 Directory Service 會使用 PowerShell 命令進行連線，並移除未使用或非作用中的電腦。

## 工具
<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) 提供多種搭配其他 使用 Microsoft Active Directory (AD) 的方式， AWS 服務 例如 Amazon Elastic Compute Cloud (Amazon EC2)、適用於 SQL Server 的 Amazon Relational Database Service (Amazon RDS) 和適用於 Windows File Server 的 Amazon FSx。
+ [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 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資源的存取。使用 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 參數存放區](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 上執行的 Microsoft 自動化和組態管理程式。
+ [Python](https://www.python.org/) 是一種一般用途的電腦程式設計語言。

**C****ode 儲存庫**

此模式的程式碼可在 GitHub [Custom AD Cleanup Automation 解決方案](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 Active Directory](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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立專案資料夾，並新增檔案。 | 若要複製儲存庫並建立專案資料夾，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 初始化 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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 執行和測試 Lambda 函數。 | 若要驗證部署是否成功執行，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除基礎設施。 | 若要清除您建立的基礎設施，請使用下列命令。`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 電腦，因為依預設， 動作會嘗試移除做為 AD 服務一部分連線的兩個私有 IP 地址。 | 為避免此錯誤，當您列出 AD 電腦輸出與執行 Windows 之機器輸出之間的差異時，請使用下列 Python 操作忽略前兩部電腦。<pre>Difference = Difference[2:]</pre> | 
| 當 Lambda 在 Windows 伺服器上執行 PowerShell 指令碼時，預期 Active Directory 模組預設為可用。如果模組無法使用，Lambda 函數會建立錯誤，指出「執行個體上未安裝 Get-AdComputer」。 | 若要避免此錯誤，請使用 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 文件**
+ [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)
+ [手動將 Amazon EC2 Windows 執行個體加入您的 AWS Managed Microsoft AD Active Directory](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*

## 總結
<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 程式庫的 Amazon Elastic Container Registry (Amazon ECR) 映像 URI，從 [Amazon ECR Public Gallery](https://gallery.ecr.aws/glue/aws-glue-libs) 下載
+ 具有目標 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 服務

## Architecture
<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_tw/prescriptive-guidance/latest/patterns/images/pattern-img/82781ca8-4da0-4df0-bf23-32992fece231/images/6286dafc-f1e0-4967-beed-4dedc6047c10.png)


該圖顯示以下工作流程：

1. 在來源階段中， AWS CodePipeline 會使用版本控制的 Amazon Simple Storage Service (Amazon S3) 儲存貯體來存放和管理原始程式碼資產。這些資產包括範例 Python ETL 任務 (`sample.py`)、單元測試檔案 (`test_sample.py`) 和 AWS CloudFormation 範本。然後，CodePipeline 會將最新的程式碼從主要分支傳輸到 AWS CodeBuild 專案，以供進一步處理。

1. 在建置和發佈階段，上一個來源階段的最新程式碼會在 AWS Glue 公有 Amazon ECR 映像的協助下進行單元測試。然後，測試報告會發佈至 CodeBuild 報告群組。適用於 AWS Glue 程式庫的公有 Amazon ECR 儲存庫中的容器映像包含在 AWS Glue 本機執行和單位測試 [PySpark 型](https://spark.apache.org/docs/latest/api/python/) ETL 任務所需的所有二進位檔。公有容器儲存庫有三個映像標籤，每個 支援的版本各一個 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-testing](https://github.com/aws-samples/aws-glue-jobs-unit-testing) 儲存庫中使用。儲存庫包含下列資源：
+ `src` 資料夾中以 Python 為基礎的 AWS Glue 任務範例
+ `tests` 資料夾中相關聯的單元測試案例 （使用 pytest 架構建置）
+ `deploy` 資料夾中的 CloudFormation 範本 （以 YAML 撰寫）

## 最佳實務
<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 CloudWatch Events 中使用。您可以使用 CloudTrail 記錄 AWS API 呼叫，以及由 發出或代表您的 發出的相關事件 AWS 帳戶。如需詳細資訊，請參閱 [ CodePipeline 文件中的使用 記錄 CodePipeline API 呼叫 AWS CloudTrail](https://docs.aws.amazon.com/codepipeline/latest/userguide/monitoring-cloudtrail-logs.html)。 CodePipeline 

您可以使用 CloudWatch Events 來監控在 上執行 AWS 雲端 的資源和應用程式 AWS。您也可以在 CloudWatch Events 中建立提醒。如需詳細資訊，請參閱 [ CodePipeline 文件中的監控 CodePipeline 事件](https://docs.aws.amazon.com/codepipeline/latest/userguide/detect-state-changes-cloudwatch-events.html)。 CodePipeline 

## 史詩
<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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 準備程式碼封存以進行部署。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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-pipeline**。 | AWS DevOps，DevOps 工程師 | 

### 執行單元測試
<a name="run-the-unit-tests"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在管道中執行單元測試。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除環境中的資源。 | 為了避免額外的基礎設施成本，請務必在實驗此模式中提供的範例之後刪除堆疊。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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 CloudFormation 範本AWS CLI。如需詳細資訊，請參閱 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、Yasa 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) 自動化您的軟體建置和發行程序，支援可重複的建置並快速交付新功能給您的使用者。您可以快速輕鬆地測試每個程式碼變更，而且可以在發行軟體之前攔截和修正錯誤。透過預備和發行程序執行每項變更，您可以驗證應用程式或基礎設施程式碼的品質。CI/CD 體現了一種文化、一組操作原則和[一系列實務](https://aws.amazon.com/devops/#cicd)，可協助應用程式開發團隊更頻繁、更可靠地交付程式碼變更。實作也稱為 *CI/CD 管道*。

此模式定義了 Amazon Web Services (AWS) 上與 AWS CodeCommit 儲存庫的可重複使用持續整合和持續交付 (CI/CD) 管道。AWS CodePipeline 管道使用 [AWS 雲端開發套件 (AWS CDK) v2](https://aws.amazon.com/cdk/) 撰寫。

使用 CodePipeline，您可以透過 AWS 管理主控台界面、AWS 命令列界面 (AWS CLI)、AWS CloudFormation 或 AWS SDKs，建立軟體版本程序的不同階段模型。此模式示範使用 AWS CDK 實作 CodePipeline 及其元件。除了建構程式庫之外，AWS CDK 還包含工具組 (CLI 命令 `cdk`)，這是與您的 AWS CDK 應用程式互動的主要工具。在其他函數中，工具組可讓您將一或多個堆疊轉換為 CloudFormation 範本，並將其部署至 AWS 帳戶。

管道包含驗證第三方程式庫安全性的測試，有助於確保指定環境中的快速自動發行。您可以透過進行驗證程序來提高應用程式的整體安全性。

此模式的目的是加速您使用 CI/CD 管道來部署程式碼，同時確保您部署的資源遵守 DevOps 最佳實務。實作[範例程式碼](https://github.com/aws-samples/aws-codepipeline-cicd)之後，您會擁有 [AWS CodePipeline](https://aws.amazon.com/codepipeline/)，其中包含固定、測試、安全檢查、部署和部署後程序。此模式也包含 Makefile 的步驟。使用 Makefile，開發人員可以在本機重現 CI/CD 步驟，並提高開發程序的速度。

## 先決條件和限制
<a name="set-up-a-ci-cd-pipeline-by-using-aws-codepipeline-and-aws-cdk-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 對以下內容的基本了解：
  + 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

## Architecture
<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 環境。

下圖顯示從 CodeCommit 儲存庫到 CodePipeline 執行的建置和更新程序的工作流程、三個開發環境步驟，以及三個環境中每個環境的後續部署和驗證。

![\[開發環境包括 linting、安全性和單元測試，全部都包括部署和驗證。\]](http://docs.aws.amazon.com/zh_tw/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>

**AWS 服務**
+ [AWS 雲端開發套件 (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 儲存庫和 CodePipeline CI/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 Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您透過命令列 shell 中的命令與 AWS 服務互動。

**其他工具**
+ [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 執行期環境，旨在建置可擴展的網路應用程式。

**Code**

此模式的程式碼可在 GitHub [AWS CodePipeline 搭配 CI/CD 實務](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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 下載或複製程式碼。 | 若要取得此模式使用的程式碼，請執行下列其中一項操作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 工程師 | 
| 連線至 AWS 帳戶。 | 您可以使用臨時安全字符或登陸區域身分驗證來連線。若要確認您使用的是正確的帳戶和 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 遞交變更以啟用管道。 | 成功初始部署後，您應該擁有完整的 CI/CD 管道，並將 `main`的分支`SampleRepository`做為來源分支。一旦您將變更遞交至`main`分支，管道就會啟動並執行下列動作序列：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用 Makefile 執行開發程序。 | 您可以使用 `make`命令在本機執行整個管道，也可以執行個別步驟 （例如 `make linting`)。若要使用 進行測試`make`，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 刪除 AWS CDK 應用程式資源。 | 若要清除您的 AWS CDK 應用程式，請執行下列命令。<pre>cdk destroy --all</pre>請注意，在引導期間建立的 Amazon Simple Storage Service (Amazon S3) 儲存貯體不會自動刪除。他們需要允許刪除的保留政策，或者您需要在 AWS 帳戶中手動刪除。 | 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_tw/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*

## 總結
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-summary"></a>

集中式記錄對於組織的雲端基礎設施至關重要，因為它提供對其操作、安全性和合規性的可見性。隨著您的組織將其 AWS 環境擴展到多個帳戶，結構化日誌管理策略成為執行安全操作、滿足稽核要求和實現卓越營運的基礎。

此模式提供可擴展且安全的架構，用於集中來自多個 AWS 帳戶 和 服務的日誌，以跨複雜 AWS 部署啟用企業規模的記錄管理。該解決方案使用 Terraform 自動化，Terraform 是一種來自 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可確保一致且可重複的部署，並將手動組態降至最低。透過結合 Amazon CloudWatch Logs、Amazon Data Firehose 和 Amazon Simple Storage Service (Amazon S3)，您可以實作強大的日誌彙總和分析管道，提供：
+ 中整個組織的集中式日誌管理 AWS Organizations
+ 使用內建安全控制自動收集日誌
+ 可擴展的日誌處理和耐用的儲存
+ 簡化的合規報告和稽核追蹤
+ 即時營運洞察和監控

解決方案會透過 CloudWatch Logs 從 Amazon Elastic Kubernetes Service (Amazon EKS) 容器、 AWS Lambda 函數和 Amazon Relational Database Service (Amazon RDS) 資料庫執行個體收集日誌。它會使用 CloudWatch 訂閱篩選條件，自動將這些日誌轉送至專用記錄帳戶。Firehose 會管理 Amazon S3 的高輸送量日誌串流管道，以進行長期儲存。Amazon Simple Queue Service (Amazon SQS) 設定為在物件建立時接收 Amazon S3 事件通知。這可讓 與 分析服務整合，包括：
+ Amazon OpenSearch Service 用於日誌搜尋、視覺化和即時分析
+ 適用於 SQL 型查詢的 Amazon Athena 
+ 適用於大規模處理的 Amazon EMR
+ 用於自訂轉換的 Lambda
+ Amazon Quick Sight for 儀表板

所有資料都是使用 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)
+ [適用於 Terraform 的 Account Factory (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) 執行和產生日誌
+ **Log Archive 帳戶** – 用於集中式日誌儲存和管理的專用帳戶

**產品版本**
+ [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)或更新版本

## Architecture
<a name="set-up-centralized-logging-at-enterprise-scale-by-using-terraform-architecture"></a>

下圖說明 AWS 集中式記錄架構，提供可擴展的解決方案，用於從多個應用程式帳戶收集、處理和儲存日誌至專用 Log Archive 帳戶。此架構可有效率地處理來自 的日誌 AWS 服務，包括 Amazon RDS、Amazon EKS 和 Lambda，並透過簡化程序將日誌路由至 Log Archive 帳戶中的區域 S3 儲存貯體。

![\[AWS 集中式記錄架構，用於從多個應用程式帳戶收集日誌。\]](http://docs.aws.amazon.com/zh_tw/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. **跨帳戶日誌傳輸**
   + 日誌會移至 Log Archive 帳戶。CloudWatch 訂閱篩選條件可促進跨帳戶轉移並保留區域內容。
   + 架構會建立多個平行串流，以有效率地處理不同的日誌來源，以確保最佳效能和可擴展性。

1. **Log Archive 帳戶中的日誌處理**
   + 在日誌封存帳戶中，Firehose 會處理傳入的日誌串流。
   + 每個區域都會維護專用的 Firehose 交付串流，可視需要轉換、轉換或擴充日誌。
   + 這些 Firehose 串流會將處理過的日誌交付至 Log Archive 帳戶中的 S3 儲存貯體，該帳戶與來源應用程式帳戶 （圖表中的區域 A) 位於相同的區域，以維護資料主權需求。

1. **通知和其他工作流程**
   + 當日誌到達其目的地 S3 儲存貯體時，架構會使用 Amazon SQS 實作通知系統。
   + 區域 SQS 佇列可啟用非同步處理，並根據儲存的日誌觸發其他工作流程、分析或提醒系統。

1. **AWS KMS 確保安全**

   架構整合 AWS KMS 用於 security。 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 Logs 訂閱篩選條件](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/SubscriptionFilters.html)是符合傳入日誌事件中模式的表達式，並將相符的日誌事件交付給指定的 AWS 資源，以進行進一步的處理或分析。
+ [AWS Control Tower Account Factory for Terraform (AFT)](https://docs.aws.amazon.com/controltower/latest/userguide/aft-overview.html) 會設定 Terraform 管道，協助您在其中佈建和自訂帳戶 AWS Control Tower。AFT 提供以 Terraform 為基礎的帳戶佈建，同時允許您使用 管理帳戶 AWS Control Tower。
+ [Amazon Data Firehose](https://docs.aws.amazon.com/firehose/latest/dev/what-is-this-service.html) 會將即時串流資料交付至目的地，例如 Amazon S3、Amazon Redshift 和 Amazon OpenSearch Service。它會自動擴展以符合資料的輸送量，而且不需要持續管理。
+ [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/) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。

**Code**

此模式的程式碼可在 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 帳戶 單一組織中使用多個 AWS Organizations](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_accounts.html) 。此實務可啟用跨帳戶的集中式管理和標準化記錄。
+ [使用版本控制、生命週期政策和跨區域複寫來設定 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用 AFT 設定 AWS Control Tower 環境。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將`Application_account`資料夾內容複製到`aft-account-customizations`儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程師 | 

### 設定 Log Archive 帳戶的組態檔案
<a name="set-up-configuration-files-for-the-log-archive-account"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將`Log_archive_account`資料夾內容複製到`aft-account-customizations`儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程師 | 
| 檢閱和編輯用於設定 Log Archive 帳戶的輸入參數。 | 在此步驟中，您會設定組態檔案以在 Log Archive 帳戶中建立資源，包括 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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 選項 1 - 從 AFT 部署 Terraform 組態檔案。 | 在 AFT 中，當您將具有組態變更的程式碼推送至 GitHub `aft-account-customizations`儲存庫後，即會觸發 AFT 管道。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_tw/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程師 | 

### 驗證資源
<a name="validate-resources"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證訂閱篩選條件。 | 若要驗證訂閱篩選條件是否正確地將日誌從應用程式帳戶日誌群組轉送至日誌封存帳戶：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/set-up-centralized-logging-at-enterprise-scale-by-using-terraform.html) | DevOps 工程師 | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 選項 1 - 從 AFT 停用 Terraform 組態檔案。 | 當您移除 Terraform 組態檔案並推送變更時，AFT 會自動啟動資源移除程序。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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 Logs 目的地未建立或處於非作用中狀態。 | 驗證下列項目：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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 (AFT) AWS Control Tower 的帳戶工廠](https://docs.aws.amazon.com/controltower/latest/userguide/aft-getting-started.html) (AWS Control Tower 文件）
+ [IAM 教學課程： AWS 帳戶 使用 IAM 角色將存取權委派給 ](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_cross-account-with-roles.html)(IAMdocumentation)

# 使用 cert-manager 和 Let's Encrypt 為 Amazon EKS 上的應用程式設定end-to-end加密
<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*

## 總結
<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加密可能很複雜，您需要管理微服務架構中每個資產的憑證。雖然您可以使用 Network Load Balancer 或 Amazon API Gateway 在 Amazon Web Services (AWS) 網路的邊緣終止 Transport Layer Security (TLS) 連線，但某些組織需要end-to-end加密。

此模式使用 NGINX 傳入控制器進行傳入。這是因為當您建立 Kubernetes 輸入時，輸入資源會使用 Network Load Balancer。Network Load Balancer 不允許上傳用戶端憑證。因此，您無法透過 Kubernetes 輸入實現交互 TLS。

此模式適用於在其應用程式中的所有微服務之間需要交互身分驗證的組織。相互 TLS 可減少維護使用者名稱或密碼的負擔，也可以使用統包安全架構。如果您的組織有大量連線裝置，或必須符合嚴格的安全準則，則此模式的方法是相容的。

此模式透過為在 Amazon Elastic Kubernetes Service (Amazon EKS) 上執行的應用程式實作end-to-end加密，協助提高組織的安全狀態。此模式在 Amazon EKS 儲存庫上的 GitHub 端對端加密中提供範例應用程式和程式碼，以顯示微服務如何在 Amazon EKS 上使用end-to-end加密來執行。 [End-to-end ](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme) 模式的方法使用 [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>

**先決條件**
+ 作用中的 AWS 帳戶
+ 現有 Amazon EKS 叢集。
+ 在 macOS、Linux 或 Windows 上安裝和設定 AWS Command Line Interface (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)。 Amazon Route 53  
+ 安裝在本機電腦上的最新 [Helm](https://docs.aws.amazon.com/eks/latest/userguide/helm.html) 版本。如需詳細資訊，請參閱 [Amazon EKS 文件和 GitHub Helm 儲存庫](https://docs.aws.amazon.com/eks/latest/userguide/helm.html)中的搭配使用 [Helm](https://github.com/helm/helm) 與 Amazon EKS。 GitHub  
+ Amazon EKS 儲存庫上的 GitHub 端對端加密，複製到您的本機電腦。 [End-to-end ](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme)  
+ 從 Amazon EKS 儲存庫上複製的 GitHub 端對端加密取代 `policy.json`和 `trustpolicy.json` 檔案中的下列值： [End-to-end ](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme) 
  + `<account number>` – 將 取代為您要部署解決方案之帳戶的 AWS 帳戶 ID。 
  + `<zone id>` – 將 取代為網域名稱的 Route 53 區域 ID。 
  + `<node_group_role>` – 將 取代為與 Amazon EKS 節點相關聯的 AWS Identity and Access Management (IAM) 角色名稱。
  + `<namespace>` – 將 取代為您部署 NGINX 傳入控制器和範例應用程式的 Kubernetes 命名空間。
  + `<application-domain-name>` – 將 取代為來自 Route 53 的 DNS 網域名稱。

**限制**
+ 此模式不會描述如何輪換憑證，只會示範如何在 Amazon EKS 上使用微服務憑證。 

## Architecture
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-architecture"></a>

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

![\[使用 cert-manager 和 Let's Encrypt 在 Amazon EKS 上設定應用程式加密的工作流程。\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/9aa3ee9e-73db-41f5-a467-b5c47fef496e/images/40692ede-6fb3-474e-8c9e-85c51529e8ad.png)


該圖顯示以下工作流程：

1. 用戶端傳送存取應用程式至 DNS 名稱的請求。

1. Route 53 記錄是 Network Load Balancer 的 CNAME。

1. Network Load Balancer 會將請求轉送至使用 TLS 接聽程式設定的 NGINX 傳入控制器。NGINX 傳入控制器與 Network Load Balancer 之間的通訊遵循 HTTPS 通訊協定。

1. NGINX 傳入控制器會根據用戶端對應用程式服務的請求，執行以路徑為基礎的路由。

1. 應用程式服務會將請求轉送至應用程式 Pod。應用程式旨在透過呼叫秘密來使用相同的憑證。

1. Pod 會使用 cert-manager 憑證執行範例應用程式。NGINX 傳入控制器與 Pod 之間的通訊使用 HTTPS。


| 
| 
| 注意：Cert-manager 會在自己的命名空間中執行。它使用 Kubernetes 叢集角色將憑證佈建為特定命名空間中的秘密。您可以將這些命名空間連接至應用程式 Pod 和 NGINX 傳入控制器。 | 
| --- |

## 工具
<a name="set-up-end-to-end-encryption-for-applications-on-amazon-eks-using-cert-manager-and-let-s-encrypt-tools"></a>

**AWS 服務**
+ [Amazon Elastic Kubernetes Service (Amazon EKS)](https://docs.aws.amazon.com/eks/latest/userguide/what-is-eks.html) 是一種受管服務，可用來在 AWS 上執行 Kubernetes，而不需要安裝、操作和維護您自己的 Kubernetes 控制平面或節點。
+ [Elastic Load Balancing](https://docs.aws.amazon.com/elasticloadbalancing/latest/userguide/what-is-load-balancing.html) 會自動將您的傳入流量分配到多個目標、容器和 IP 地址。
+ [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) 可透過控制已驗證並獲授權使用的人員，協助您安全地管理對 AWS 資源的存取。
+ [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/Welcome.html) 是一種可用性高、可擴展性強的 DNS Web 服務。

**其他工具**
+ [cert-manager](https://cert-manager.io/docs/installation/supported-releases/) 是 Kubernetes 的附加元件，可請求憑證、將憑證分發至 Kubernetes 容器，以及自動化憑證續約。
+ [NGINX 輸入控制器](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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 在 Route 53 中建立公有託管區域。 | 登入 AWS 管理主控台，開啟 Amazon Route 53 主控台，選擇**託管區域**，然後選擇**建立託管區域**。建立公有託管區域並記錄區域 ID。如需詳細資訊，請參閱 Amazon Route 53 文件中的[建立公有託管區域](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/CreatingHostedZone.html)。ACME DNS01 使用 DNS 提供者發佈挑戰，讓 cert-manager 發行憑證。此挑戰要求您證明控制網域名稱的 DNS，方法是將特定值放在該網域名稱下的 TXT 記錄中。在 Let's Encrypt 為您的 ACME 用戶端提供字符之後，您的用戶端會建立衍生自該字符和您帳戶金鑰的 TXT 記錄，並將該記錄放在 `_acme-challenge.<YOURDOMAIN>`。然後，讓我們加密查詢該記錄的 DNS。如果找到相符項目，您可以繼續發出憑證。 | AWS DevOps | 

### 設定 IAM 角色以允許 cert-manager 存取公有託管區域
<a name="configure-an-iam-role-to-allow-cert-manager-to-access-the-public-hosted-zone"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 cert-manager 的 IAM 政策。 | 需要 IAM 政策才能為 cert-manager 提供許可，以驗證您擁有 Route 53 網域。`policy.json` 範例 IAM 政策會在 Amazon EKS 儲存庫上複製的 GitHub 端對端加密的 `1-IAMRole`目錄中提供。 [End-to-end ](https://github.com/aws-samples/end-to-end-encryption-on-amazon-eks#readme) 在 AWS CLI 中輸入下列命令來建立 IAM 政策。<pre>aws iam create-policy \<br />  --policy-name PolicyForCertManager \<br />  --policy-document file://policy.json</pre> | AWS DevOps | 
| 建立 cert-manager 的 IAM 角色。 | 建立 IAM 政策後，您必須建立 IAM 角色。`trustpolicy.json` 範例 IAM 角色在 `1-IAMRole`目錄中提供。在 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 政策連接至 IAM 角色。`AWS_ACCOUNT_ID` 將 取代為您 AWS 帳戶的 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 傳入控制器
<a name="set-up-the-nginx-ingress-controller-in-amazon-eks"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 NGINX 傳入控制器。 | `nginx-ingress` 使用 Helm 安裝最新版本的 。您可以在部署組態之前，根據您的需求修改`nginx-ingress`組態。此模式使用註釋且面向內部的 Network Load Balancer，該模式可在 `5-Nginx-Ingress-Controller`目錄中使用。 從 `5-Nginx-Ingress-Controller`目錄執行下列 Helm 命令來安裝 NGINX 傳入控制器。`helm install test-nginx nginx-stable/nginx-ingress  -f  5-Nginx-Ingress-Controller/values_internal_nlb.yaml` | AWS DevOps | 
| 確認已安裝 NGINX 傳入控制器。 | 輸入 `helm list` 命令。輸出應會顯示已安裝 NGINX 傳入控制器。 | AWS DevOps | 
| 建立 Route 53 A 記錄。 | A 記錄指向 NGINX 傳入控制器建立的 Network Load Balancer。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 | 

### 在 Amazon EKS 上設定 NGINX VirtualServer
<a name="set-up-nginx-virtualserver-on-amazon-eks"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 部署 NGINX VirtualServer。 | NGINX VirtualServer 資源是一種負載平衡組態，是輸入資源的替代方案。建立 NGINX VirtualServer 資源的組態可在 `6-Nginx-Virtual-Server`目錄中的 `nginx_virtualserver.yaml` 檔案中取得。在 中輸入下列命令`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_tw/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_tw/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 上使用 Network Load Balancer 搭配 NGINX 輸入控制器 ](https://aws.amazon.com/blogs/opensource/network-load-balancer-nginx-ingress-controller-eks/)(AWS 部落格文章）

**其他資源**
+ [Route 53](https://cert-manager.io/docs/configuration/acme/dns01/route53/) (cert-manager 文件）
+ [設定 DNS01 挑戰提供者](https://cert-manager.io/docs/configuration/acme/dns01/) （憑證管理員文件）
+ [讓我們加密 DNS 挑戰](https://letsencrypt.org/docs/challenge-types/#dns-01-challenge) （讓我們的加密文件）

# 使用 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*

## 總結
<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 服務帳戶 (IRSA) 的 (IAM) 角色

此外，在您部署應用程式時，此解決方案會使用 Flux 來保持租戶組態不變。您可以在組態中指定包含 Flux `kustomization.yaml` 檔案的租用戶儲存庫，以部署租用戶應用程式。

此模式實作下列項目：
+ 透過手動部署 Terraform 指令碼建立的 AWS CodeCommit 儲存庫、 AWS CodeBuild 專案和 AWS CodePipeline 管道。
+ 託管租用戶所需的網路和運算元件。這些是使用 Terraform 透過 CodePipeline 和 CodeBuild 建立。
+ 透過 Helm Chart 設定的租戶命名空間、網路政策和資源配額。
+ 屬於不同租用戶的應用程式，使用 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 提供者](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 提供者](https://registry.terraform.io/providers/gavinbunney/kubectl/latest/docs) 1.14 版或更新版本

**限制**
+ **相依於 Terraform 手動部署：**工作流程的初始設定，包括建立 CodeCommit 儲存庫、CodeBuild 專案和 CodePipeline 管道，依賴手動 Terraform 部署。這在自動化和可擴展性方面引入了潛在的限制，因為它需要手動介入基礎設施變更。
+ **CodeCommit 儲存庫相依性：**工作流程依賴 CodeCommit 儲存庫做為原始碼管理解決方案，並與 緊密結合 AWS 服務。

## Architecture
<a name="simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux-architecture"></a>

**目標架構 **

此模式部署三個模組來建置資料平台的管道、網路和運算基礎設施，如下圖所示。

*管道架構：*

![\[Amazon EKS 多租戶架構的管道基礎設施\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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) 可協助您快速建模和設定軟體版本的不同階段，並自動化持續發行軟體變更所需的步驟。
+ [Amazon Elastic Kubernetes Service (Amazon EKS) ](https://docs.aws.amazon.com/eks/latest/userguide/getting-started.html)可協助您在 上執行 Kubernetes， AWS 而無需安裝或維護您自己的 Kubernetes 控制平面或節點。
+ [AWS Transit Gateway](https://docs.aws.amazon.com/vpc/latest/tgw/what-is-transit-gateway.html) 是連接虛擬私有雲端 (VPC) 和內部部署網路的中央中樞。
+ [Amazon Virtual Private Cloud (Amazon 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/) 是 HashiCorp 的基礎設施即程式碼 (IaC) 工具，可協助您建立和管理雲端和內部部署資源。

**程式碼儲存庫**

此模式的程式碼可在 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製專案儲存庫。 | 在終端機視窗中執行下列命令，複製 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_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 啟動管道。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/simplify-amazon-eks-multi-tenant-application-deployment-by-using-flux.html) | AWS DevOps | 

### 建立運算基礎設施
<a name="create-the-compute-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 更新`locals.tf`以啟用 CodeBuild 專案對 VPC 的存取。 | 若要部署 Amazon EKS 私有叢集的附加元件，CodeBuild 專案必須連接至 Amazon EKS VPC。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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 Chart `values`的檔案。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證 Kubernetes 中的租戶管理資源。 | 執行下列命令，以檢查在 Helm 的協助下已成功建立租用戶管理資源。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/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 和 Amazon Web Services 的 James O'Hara*

## 總結
<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](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.124.0](https://docs.aws.amazon.com/cdk/api/versions.html) 或更新版本
+ [適用於 Python (Boto3) 的 AWS SDK](https://docs.aws.amazon.com/pythonsdk/)1.28 或更新版本

## Architecture
<a name="streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow-architecture"></a>

下圖顯示解決方案的高階架構和關鍵元件。

![\[自動化 Amazon Lex 機器人開發和部署的工作流程。\]](http://docs.aws.amazon.com/zh_tw/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 管道和開發和部署程序的相關資源。
+ **管道** – 自動化機器人開發和部署生命週期各種階段的 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) - Toolkit 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) 是一種開放原始碼分散式版本控制系統。

**程式碼儲存庫**

此模式的程式碼可在 GitHub [management-framework-sample-for-amazon-lex](https://github.com/aws-samples/management-framework-sample-for-amazon-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 主控台或自動測試架構來驗證機器人組態和功能，然後再提升到更高的環境。
  + 考慮為部署到生產環境或關鍵環境實作手動核准閘道。
+ **監控和記錄 **
  + 設定管道、部署和機器人互動的監控和記錄機制。
  + 監控管道事件、部署狀態和機器人效能指標，以快速識別和解決問題。
  + 使用 Amazon CloudWatch 等 AWS 服務 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定本機 CDK 環境。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 定義主要機器人的初始版本。 | 若要定義主要機器人的初始版本，請[觸發](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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立票證機器人以開發和測試功能。 | `TicketBot` 是從功能分支中現有主要機器人定義匯入的新機器人執行個體。此方法可確保新機器人具有主機器人的所有目前功能和組態。若要定義票證機器人的初始版本，請觸發`CreateTicketBotPipeline`管道。管道會在版本控制系統中建立新的功能分支，並根據主要機器人建立新的票證機器人執行個體。 | Lex Bot 開發人員 | 
| 開發和測試票證機器人功能。 | 若要開發和測試此功能，請登入 AWS 管理主控台 並開啟位於 https：//[https://console.aws.amazon.com/lex/](https://console.aws.amazon.com/lex/) 的 Amazon 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 Bot 開發人員 | 
| 匯出票證機器人定義。 | 匯出的機器人定義基本上是以 JSON 格式呈現機器人的組態和功能。若要匯出票證機器人定義，請觸發`ExportTicketBotPipeline`管道。管道會將票證機器人定義匯出為 .json 檔案，並將票證機器人程式碼存放在版本控制系統中的功能分支中。 | Lex Bot 開發人員 | 
| 從最新的主分支重新建立特徵分支的基礎。 | 在開發新功能期間，主要分支可能已收到來自不同開發人員或團隊的其他變更。若要將這些變更納入功能分支，請執行 Git `rebase`操作。此操作基本上會在來自主分支的最新遞交之上，從特徵分支重播遞交，以確保特徵分支包含所有最新的變更 | Lex Bot 開發人員 | 
| 匯入和驗證以重新為基礎的票證機器人。 | 重新建立特徵分支的基礎之後，您必須將其匯入票證機器人執行個體。此匯入會使用重新為基礎的分支的最新變更來更新現有的票證機器人。若要匯入以重新為基礎的票證機器人，請觸發`ImportTicketBotPipeline`管道。管道會將版本控制系統中特徵分支中的票證機器人定義 .json 檔案匯入`TicketBot`執行個體。 | Lex Bot 開發人員 | 
| 驗證重新型機器人定義。 | 在您匯入重新型機器人定義之後，驗證其功能至關重要。您想要確保新功能如預期般運作，且不會與現有功能衝突。此驗證通常涉及使用各種輸入案例測試機器人、檢查回應，以及驗證機器人的行為是否如預期。您可以透過下列其中一種方式執行驗證：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.html) | Lex Bot 開發人員 | 
| 將功能分支合併到主分支。 | 在隔離的`TicketBot`執行個體中開發和測試新功能之後，請執行下列動作：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/streamline-amazon-lex-bot-development-and-deployment-using-an-automated-workflow.html) | Lex Bot Developer，儲存庫管理員 | 
| 刪除功能分支和票證機器人。 | 將功能分支成功合併至主分支後，請從原始碼儲存庫刪除功能分支和票證機器人。若要刪除功能分支和票證機器人，請觸發`DeleteTicketBotPipeline`管道。管道會移除開發過程中建立的臨時機器人資源 （例如票證機器人）。此動作有助於維護乾淨的儲存庫，並防止與未來的特徵分支混淆或衝突。 | Lex Bot 開發人員 | 

### 維護主要機器人
<a name="maintain-the-main-bot"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將最新的主要機器人定義匯入`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*

## 摘要
<a name="use-the-aws-fargate-waitcondition-hook-construct-summary"></a>

此模式描述 WaitCondition hook (`waitcondition-hook-for-aws-fargate-task`) npm 套件，這是雲端原生解決方案，專為在 Amazon Elastic Container Service (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 掛鉤提供下列關鍵功能：
+ 做為等待條件機制，暫停 CloudFormation 堆疊執行，直到指定的 Fargate 任務完成，這有助於有序的部署和資源佈建。
+ 支援 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 和](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) 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)，然後選擇服務的連結。

## Architecture
<a name="use-the-aws-fargate-waitcondition-hook-construct-architecture"></a>

下圖顯示建構架構。

![\[waitcondition-hook-for-aws-fargate-task 建構的 AWS Step Functions 工作流程。\]](http://docs.aws.amazon.com/zh_tw/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. 根據任務的結果， `CallbackFunction`或 `ErrorHandlerFunction`是由 Fargate 任務的完成所觸發。

1. Lambda 函數會將 SUCCEED 或 FAILURE 訊號傳送至 `WaitConditionHandler`。

1. `WaitConditionHandler` 如果 Fargate 任務的執行結果成功， 會繼續佈建資源，或在任務失敗時轉返堆疊。

下圖顯示執行資料庫遷移的工作流程範例。

![\[使用 WaitCondition hook 建構的 Amazon RDS 資料庫遷移工作流程。\]](http://docs.aws.amazon.com/zh_tw/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 傳送成功訊號。否則，它會將失敗訊號傳送至 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 (Amazon 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-task](https://github.com/aws-samples/waitcondition-hook-for-aws-fargate-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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 安裝 AWS CDK。 | 若要 AWS CDK 在本機電腦或其他環境上安裝 ，請執行下列命令：<pre>npm install -g aws-cdk@latest</pre> | 雲端架構師、應用程式開發人員 | 
| 引導 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 CDK 專案。 | 使用您偏好的語言建立 CDK 專案。此模式使用 TypeScript。若要使用 TypeScript 建立 CDK 專案，請執行下列命令：`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_tw/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)建構執行 Fargate `waitcondition-hook-for-aws-fargate-task` 任務。 | 雲端架構師 | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除資源。 | 若要清除上一個步驟佈建的資源，請執行下列命令：<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_tw/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)如需詳細資訊，請參閱 AWS Step Functions 文件[中的 Step Functions 中的疑難排解問題](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_tw/prescriptive-guidance/latest/patterns/use-the-aws-fargate-waitcondition-hook-construct.html)如需詳細資訊，請參閱 AWS Lambda 文件中的[對 Lambda 中的問題進行故障診斷](https://docs.aws.amazon.com/lambda/latest/dg/lambda-troubleshooting.html)。 | 

## 相關資源
<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 1.0.6](https://pypi.org/project/waitcondition-hook-for-aws-fargate-task/) (pypi.org：//)

# 在 AWS CodePipeline 中使用第三方 Git 來源儲存庫
<a name="use-third-party-git-source-repositories-in-aws-codepipeline"></a>

*Kirankumar Chandrashekar，Amazon Web Services*

## 總結
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-summary"></a>

此模式說明如何搭配第三方 Git 來源儲存庫使用 AWS CodePipeline。

[AWS CodePipeline](https://docs.aws.amazon.com/codepipeline/latest/userguide/concepts-continuous-delivery-integration.html) 是一種持續交付服務，可自動化建置、測試和部署軟體的任務。此服務目前支援 GitHub 儲存庫。 [AWS CodeCommit](https://aws.amazon.com/codecommit) 不過，有些企業使用與單一登入 (SSO) 服務和 Microsoft Active Directory 整合的第三方 Git 儲存庫進行身分驗證。您可以透過建立自訂動作和 Webhook，使用這些第三方 Git 儲存庫做為 CodePipeline 的來源。

Webhook 是一種 HTTP 通知，能在另一個工具中 (例如 GitHub 儲存庫) 偵測事件，並連接這些外部事件至管道。當您在 CodePipeline 中建立 Webhook 時，服務會傳回您可以在 Git 儲存庫 Webhook 中使用的 URL。如果您將程式碼推送至 Git 儲存庫的特定分支，Git Webhook 會透過此 URL 啟動 CodePipeline Webhook，並將管道的來源階段設定為**進行中**。當管道處於此狀態時，任務工作者會輪詢自訂任務的 CodePipeline、執行任務，並將成功或失敗狀態傳送至 CodePipeline。在此情況下，由於管道位於來源階段，任務工作者會使用輪詢任務提供的物件金鑰，取得 Git 儲存庫的內容、壓縮內容，並將其上傳至存放管道成品的 Amazon Simple Storage Service (Amazon S3) 儲存貯體。您也可以將自訂動作的轉換與 Amazon CloudWatch 中的事件建立關聯，並根據事件啟動任務工作者。此設定可讓您使用服務原生不支援作為 CodePipeline 來源的第三方 Git 儲存庫。

## 先決條件和限制
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-prereqs"></a>

**先決條件**
+ 作用中的 AWS 帳戶
+ 支援 Webhook 並可透過網際網路連線至 CodePipeline Webhook URL 的 Git 儲存庫 
+ [已安裝](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 Command Line Interface (AWS CLI) 以使用 AWS 帳戶

## Architecture
<a name="use-third-party-git-source-repositories-in-aws-codepipeline-architecture"></a>

模式涉及以下步驟：

1. 使用者將程式碼遞交至 Git 儲存庫。

1. Git Webhook 稱為 。

1. CodePipeline Webhook 稱為 。

1. 管道設定為**進行中**，而來源階段設定為**進行中**狀態。

1. 來源階段動作會啟動 CloudWatch Events 規則，指出已啟動。

1. CloudWatch 事件會啟動 Lambda 函數。

1. Lambda 函數會取得自訂動作任務的詳細資訊。

1. Lambda 函數會啟動 AWS CodeBuild 並傳遞所有與任務相關的資訊。

1. CodeBuild 會從 Secrets Manager 取得 HTTPS Git 存取的公有 SSH 金鑰或使用者憑證。

1. CodeBuild 會複製特定分支的 Git 儲存庫。

1. CodeBuild 會壓縮封存檔，並將其上傳至做為 CodePipeline 成品存放區的 S3 儲存貯體。

![\[使用第三方 Git 來源儲存庫做為 AWS CodePipeline 來源的工作流程。\]](http://docs.aws.amazon.com/zh_tw/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 會處理執行和擴展程式碼所需的一切，並提供高可用性。您可以設定程式碼以自動從其他 AWS 服務啟動，或直接從任何 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 雲端、第三方服務和內部部署環境中的資源集中稽核秘密輪換。
+ [Amazon CloudWatch](https://aws.amazon.com/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 使用 AWS CLI 或 AWS CloudFormation 建立自訂動作。 | 此步驟涉及建立自訂來源動作，可用於特定區域中 AWS 帳戶中管道的來源階段。您必須使用 AWS CLI 或 AWS CloudFormation （而非主控台） 來建立自訂來源動作。如需此和其他 epics 中所述命令和步驟的詳細資訊，請參閱此模式結尾的「相關資源」一節。在 AWS CLI 中，使用 create-custom-action-type 命令。使用 --configuration-properties 提供任務工作者在輪詢任務的 CodePipeline 時需要處理的所有參數。請務必記下提供給 --provider 和 --action-version 選項的值，以便在使用此自訂來源階段建立管道時使用相同的值。您也可以使用資源類型 AWS：：CodePipeline：：CustomActionType，在 AWS CloudFormation 中建立自訂來源動作。 AWS::CodePipeline::CustomActionType | 一般 AWS | 

### 設定身分驗證
<a name="set-up-authentication"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 SSH 金鑰對。 | 建立 Secure Shell (SSH) 金鑰對。如需說明，請參閱 GitHub 文件。 | 系統/DevOps 工程師 | 
| 在 AWS Secrets Manager 中建立秘密。 | 從 SSH 金鑰對複製私有金鑰的內容，並在 AWS Secrets Manager 中建立秘密。存取 Git 儲存庫時，此秘密會用於身分驗證。 | 一般 AWS | 
| 將公有金鑰新增至 Git 儲存庫。 | 將公有金鑰從 SSH 金鑰對新增至 Git 儲存庫帳戶設定，以針對私有金鑰進行身分驗證。 | 系統/DevOps 工程師 | 

### 建立管道和 Webhook
<a name="create-a-pipeline-and-webhook"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立包含自訂來源動作的管道。 | 在 CodePipeline 中建立管道。當您設定來源階段時，請選擇您先前建立的自訂來源動作。您可以在 AWS CodePipeline 主控台或 AWS CLI 中執行此操作。CodePipeline 會提示您輸入您在自訂動作上設定的組態屬性。需要此資訊，任務工作者才能處理自訂動作的任務。遵循精靈並建立管道的下一個階段。 | 一般 AWS | 
| 建立 CodePipeline Webhook。 | 為您使用自訂來源動作建立的管道建立 Webhook。您必須使用 AWS CLI 或 AWS CloudFormation （而非主控台） 來建立 Webhook。在 AWS CLI 中，執行 put-webhook 命令，並提供 Webhook 選項的適當值。請記下 命令傳回的 Webhook URL。如果您使用 AWS CloudFormation 建立 Webhook，請使用資源類型 AWS::CodePipeline::Webhook。請務必從建立的資源輸出 Webhook URL，並將其記下。 | 一般 AWS | 
| 建立 Lambda 函數和 CodeBuild 專案。 | 在此步驟中，您可以使用 Lambda 和 CodeBuild 建立任務工作者，以輪詢 CodePipeline 以取得自訂動作的任務請求、執行任務，並將狀態結果傳回 CodePipeline。當管道的自訂來源動作階段轉換為「進行中」時，建立由 Amazon CloudWatch Events 規則啟動的 Lambda 函數。啟動 Lambda 函數時，它應該透過輪詢任務來取得自訂動作任務詳細資訊。您可以使用 PollForJobs API 傳回此資訊。取得輪詢的任務資訊後，Lambda 函數應傳回確認，然後使用其從自訂動作的組態屬性取得的資料來處理資訊。當工作者準備好與 Git 儲存庫交談時，您可以啟動 CodeBuild 專案，因為使用 SSH 用戶端處理 Git 任務非常方便。 | General AWS，程式碼開發人員 | 

### 在 CloudWatch 中建立事件
<a name="create-an-event-in-cloudwatch"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 建立 CloudWatch Events 規則。 | 建立 CloudWatch Events 規則，每當管道的自訂動作階段轉換為「進行中」時，就會啟動 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)

**建立管道和 Webhook**
+ [在 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 CodePipeline 建立 CI/CD 管道來驗證 Terraform 組態
<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*

## 總結
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-summary"></a>

此模式示範如何使用 AWS CodePipeline 部署的持續整合和持續交付 (CI/CD) 管道來測試 HashiCorp Terraform 組態。

Terraform 是一種命令列界面應用程式，可協助您使用程式碼來佈建和管理雲端基礎設施和資源。此模式中提供的解決方案會建立 CI/CD 管道，協助您執行五個 [CodePipeline 階段](https://docs.aws.amazon.com/codepipeline/latest/userguide/concepts.html#concepts-stages)來驗證 Terraform 組態的完整性：

1. `"checkout"` 會從 AWS CodeCommit 儲存庫提取您正在測試的 Terraform 組態。

1. `"validate"` 會以程式碼 (IaC) 驗證工具的形式執行基礎設施，包括 [tfsec](https://github.com/aquasecurity/tfsec)、[TFLint](https://github.com/terraform-linters/tflint) 和 [checkov](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>

**先決條件**
+ 作用中的 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)
+ 在本機電腦上安裝和設定的 [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)

**限制**
+ 此模式的方法只會將 AWS CodePipeline 部署到一個 AWS 帳戶和 AWS 區域。多帳戶和多區域部署需要變更組態。
+ 此模式佈建的 AWS Identity and Access Management (IAM) 角色 (**codepipeline\$1iam\$1role**) 遵循最低權限原則。此 IAM 角色的許可必須根據管道需要建立的特定資源進行更新。****

**產品版本**
+ AWS CLI 2.9.15 版或更新版本
+ Terraform 1.3.7 版或更新版本

## Architecture
<a name="create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline-architecture"></a>

**目標技術堆疊**
+ AWS CodePipeline
+ AWS CodeBuild
+ AWS CodeCommit
+ AWS IAM
+ Amazon Simple Storage Service (Amazon S3)
+ AWS Key Management Service (AWS KMS)
+ Terraform

**目標架構**

下圖顯示在 CodePipeline 中測試 Terraform 組態的範例 CI/CD 管道工作流程。

![\[使用 AWS CI/CD 管道測試 Terraform 組態的架構。\]](http://docs.aws.amazon.com/zh_tw/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. AWS CodePipeline 擔任 IAM 服務角色，其中包含存取 CodeCommit、CodeBuild、AWS KMS 和 Amazon S3 所需的政策。

1. CodePipeline 會執行`"checkout"`管道階段，從 AWS CodeCommit 儲存庫提取 Terraform 組態以供測試。

1. CodePipeline 會在 CodeBuild 專案中執行 IaC 驗證工具和執行 Terraform IaC 驗證命令，以執行`"validate"`階段來測試 Terraform 組態。

1. CodePipeline 會執行 `"plan"`階段，根據 Terraform 組態在 CodeBuild 專案中建立計畫。AWS 使用者可以在將變更套用至測試環境之前檢閱此計畫。

1. Code Pipeline 會執行`"apply"`階段來實作計畫，方法是使用 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 (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) 可協助您建立和控制密碼編譯金鑰，以協助保護您的資料。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) 是一種雲端型物件儲存服務，可協助您儲存、保護和擷取任何數量的資料。

*其他服務*
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一種命令列界面應用程式，可協助您使用程式碼來佈建和管理雲端基礎設施和資源。

**Code**

此模式的程式碼可在 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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 複製 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_tw/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_tw/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 計劃，並確認它在您的目標 AWS 帳戶中設定所需的架構。 | DevOps 工程師 | 
| 部署解決方案。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定原始程式碼儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/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_tw/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_tw/prescriptive-guidance/latest/patterns/create-a-ci-cd-pipeline-to-validate-terraform-configurations-by-using-aws-codepipeline.html)`<project_name>-validate` CodeBuild 專案會在`"validate"`階段期間為您的程式碼產生漏洞報告。 | DevOps 工程師 | 

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


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 清除管道和相關聯的資源。 | 若要從您的 AWS 帳戶刪除測試資源，請在複製的儲存庫根資料夾中執行下列命令：<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_tw/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 for 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 檔案使用以下變數來啟用不同的組建特定設定：


| 
| 
| 變數 | 預設值 | Description | 
| --- |--- |--- |
| `CODE_SRC_DIR` | "." | 定義來源 CodeCommit 目錄 | 
| `TF_VERSION` | "1.3.7" | 定義建置環境的 Terraform 版本 | 

`buildspec_validate.yml` 檔案也支援下列變數，以啟用不同的建置特定設定：


| 
| 
| 變數 | 預設值 | Description | 
| --- |--- |--- |
| `SCRIPT_DIR` | "./templates/scripts" | 定義指令碼目錄 | 
| `ENVIRONMENT` | 「開發」 | 定義環境名稱 | 
| `SKIPVALIDATIONFAILURE` | 「Y」 | 略過失敗的驗證 | 
| `ENABLE_TFVALIDATE` | 「Y」 | 啟用 Terraform 驗證  | 
| `ENABLE_TFFORMAT` | 「Y」 | 啟用 Terraform 格式 | 
| `ENABLE_TFCHECKOV` | 「Y」 | 啟用檢查掃描 | 
| `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 SageMaker AI 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 組態 Amazon MQ](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 函數 DynamoDB](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 EC2 Auto Scaling 和 Systems Manager 建置 Micro Focus Enterprise Server PAC](build-a-micro-focus-enterprise-server-pac-with-amazon-ec2-auto-scaling-and-systems-manager.md)
+ [使用 EC2 Image Builder 和 Terraform 建置強化容器映像的管道](build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform.md)
+ [使用 Amazon SageMaker AI 和 Azure DevOps 建置 MLOps 工作流程](build-an-mlops-workflow-by-using-amazon-sagemaker-and-azure-devops.md)
+ [使用 AWS Managed Microsoft AD 和內部部署 Microsoft Active Directory 集中 DNS 解析](centralize-dns-resolution-by-using-aws-managed-microsoft-ad-and-on-premises-microsoft-active-directory.md)
+ [在狀態檔案遺失後，安全地清除 AWS Account Factory for Terraform (AFT) 資源](clean-up-aft-resources-safely-after-state-file-loss.md)
+ [使用 NLog 在 Amazon CloudWatch Logs 中設定 .NET 應用程式的記錄](configure-logging-for-net-applications-in-amazon-cloudwatch-logs-by-using-nlog.md)
+ [跨 AWS 帳戶 和 複製 Amazon ECR 容器映像 AWS 區域](copy-ecr-container-images-across-accounts-regions.md)
+ [為 SageMaker 建立自訂 Docker 容器映像，並將其用於 AWS Step Functions 中的模型訓練](create-a-custom-docker-container-image-for-sagemaker-and-use-it-for-model-training-in-aws-step-functions.md)
+ [在不支援 AWS CodePipeline 的 AWS 區域中建立管道](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)
+ [使用基礎設施做為程式碼，在 AWS 雲端上部署和管理無伺服器資料湖](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 S3 中使用 Amazon EKS 和 Helm Chart 儲存庫部署 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 在 Amazon EC2 和 Amazon 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 和 ReAct 提示，開發進階生成式 AI 聊天式助理](develop-advanced-generative-ai-chat-based-assistants-by-using-rag-and-react-prompting.md)
+ [使用 AWS CloudFormation 範本有條件地啟用 Amazon GuardDuty](enable-amazon-guardduty-conditionally-by-using-aws-cloudformation-templates.md)
+ [使用 Amazon EKS Pod Identity 和 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 CDK 跨多個 AWS 區域、帳戶和 OUs 啟用 Amazon DevOps Guru，以改善營運效能](improve-operational-performance-by-enabling-amazon-devops-guru-across-multiple-aws-regions-accounts-and-ous-with-the-aws-cdk.md)
+ [使用 Kubernetes DaemonSet 在 Amazon EKS 工作者節點上安裝 SSM Agent](install-ssm-agent-on-amazon-eks-worker-nodes-by-using-kubernetes-daemonset.md)
+ [將stonebranch 通用控制器與 AWS Mainframe Modernization 整合](integrate-stonebranch-universal-controller-with-aws-mainframe-modernization.md)
+ [大型主機現代化：DevOps on AWS with Rocket Software Enterprise Suite](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 託管應用程式遷移至 Amazon EC2](migrate-iis-hosted-applications-to-amazon-ec2-by-using-appcmd.md)
+ [跨多個 監控共用 Amazon Machine Image 的使用 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 原則自動化 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 自動化任務 AWS Step Functions](run-aws-systems-manager-automation-tasks-synchronously-from-aws-step-functions.md)
+ [使用 AWS CDK 和 GitLab 在 Amazon ECS Anywhere 上設定混合工作負載的 CI/CD 管道](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 FSx 設定 SQL Server Always On FCI 的異地同步備份基礎設施](set-up-multi-az-infrastructure-for-a-sql-server-always-on-fci-by-using-amazon-fsx.md)
+ [使用 AWS CloudFormation 在 Amazon EC2 上自動設定 UiPath RPA 機器人](set-up-uipath-rpa-bots-automatically-on-amazon-ec2-by-using-aws-cloudformation.md)
+ [使用 Application Load Balancer 在 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 自動為組織啟用 Amazon 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)
+ [在本機驗證帳戶工廠的 Terraform (AFT) 程式碼](validate-account-factory-for-terraform-aft-code-locally.md)
+ [使用 Flask 和 AWS Elastic Beanstalk 視覺化 AI/ML 模型結果](visualize-ai-ml-model-results-using-flask-and-aws-elastic-beanstalk.md)