

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

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