

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

# 使用 EC2 Image Builder 和 Terraform 建置強化容器映像的管道
<a name="build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform"></a>

*Mike Saintcross 和 Andrew Ranes，Amazon Web Services*

## 總結
<a name="build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform-summary"></a>

此模式會建置 [EC2 Image Builder 管道](https://docs.aws.amazon.com/imagebuilder/latest/userguide/start-build-image-pipeline.html)，產生強化的 [Amazon Linux 2 ](https://aws.amazon.com/amazon-linux-2/)基礎容器映像。Terraform 用作基礎設施即程式碼 (IaC) 工具，用於設定和佈建用於建立強化容器映像的基礎設施。配方可協助您部署已根據 Red Hat Enterprise Linux (RHEL) 7 STIG 第 3 版第 7 版 ‒ 媒體強化的 Docker 型 Amazon Linux 2 容器映像。（請參閱 EC2 Image Builder 文件的 *Linux* [STIG 元件一節中的 STIG-Build-Linux-Medium 2022.2.1 版](https://docs.aws.amazon.com/imagebuilder/latest/userguide/toe-stig.html#linux-os-stig)。) 這稱為*黃金*容器映像。

組建包含兩個[ Amazon EventBridge 規則](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-rules.html)。當 [Amazon Inspector 調查結果](https://docs.aws.amazon.com/inspector/latest/user/findings-managing.html)為**高**或**嚴重**時，一個規則會啟動容器映像管道，以便取代不安全映像。此規則需要同時啟用 Amazon Inspector 和 Amazon Elastic Container Registry (Amazon ECR) [增強型掃描](https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning-enhanced.html)。另一個規則會在成功將映像推送至 Amazon ECR 儲存庫後，將通知傳送至 Amazon Simple Queue Service (Amazon SQS) [佇列](https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-queue-types.html)，以協助您使用最新的容器映像。

**注意**  
Amazon Linux 2 即將結束支援。如需詳細資訊，請參閱 [Amazon Linux 2 FAQs](https://aws.amazon.com/amazon-linux-2/faqs/)。

## 先決條件和限制
<a name="build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform-prereqs"></a>

**先決條件**
+ 您可以在其中部署基礎設施的 [AWS 帳戶](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)。
+ [安裝 AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) 以設定本機部署的 AWS 登入資料。
+ 遵循 Terraform 文件中[的指示](https://developer.hashicorp.com/terraform/tutorials/aws-get-started)[下載](https://developer.hashicorp.com/terraform/downloads)和設定 Terraform。
+ [Git](https://git-scm.com/) （如果您是從本機電腦佈建）。
+ AWS 帳戶中[的角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)，可用來建立 AWS 資源。
+ [.tfvars](https://developer.hashicorp.com/terraform/tutorials/configuration-language/variables) 檔案中定義的所有變數。 或者，您可以在套用 Terraform 組態時定義所有變數。

**限制**
+ 此解決方案會建立 Amazon Virtual Private Cloud (Amazon VPC) 基礎設施，其中包含 [NAT 閘道](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html)和[網際網路閘道](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html)，以便從其私有子網路進行網際網路連線。您無法使用 [VPC 端點](https://docs.aws.amazon.com/whitepapers/latest/aws-privatelink/what-are-vpc-endpoints.html)，因為 [AWS Task Orchestrator 和 Executor (AWSTOE) 的引導程序](https://aws.amazon.com/premiumsupport/knowledge-center/image-builder-pipeline-execution-error/)會從網際網路安裝 AWS CLI 第 2 版。

**產品版本**
+ Amazon Linux 2
+ AWS CLI 1.1 版或更新版本

## Architecture
<a name="build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform-architecture"></a>

**目標技術堆疊**

此模式會建立 43 個資源，包括：
+ 兩個 Amazon Simple Storage Service (Amazon S3) 儲存[貯](https://docs.aws.amazon.com/AmazonS3/latest/userguide/UsingBucket.html)體：一個用於管道元件檔案，另一個用於伺服器存取和 Amazon VPC 流程日誌
+ [Amazon ECR 儲存庫](https://docs.aws.amazon.com/AmazonECR/latest/userguide/repository-create.html)
+ 虛擬私有雲端 (VPC)，其中包含公有子網路、私有子網路、路由表、NAT 閘道和網際網路閘道
+ EC2 Image Builder 管道、配方和元件
+ 容器映像
+ 用於映像加密的 AWS Key Management Service (AWS KMS) [金鑰](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#kms_keys) 
+ SQS 佇列
+ 三個角色：一個用於執行 EC2 Image Builder 管道、一個用於 EC2 Image Builder 的執行個體描述檔，以及一個用於 EventBridge 規則
+ 兩個 EventBridge 規則

**Terraform 模組結構**

如需原始程式碼，請參閱 GitHub 儲存庫 [Terraform EC2 Image Builder Container Hardening Pipeline](https://github.com/aws-samples/terraform-ec2-image-builder-container-hardening-pipeline)。

```
├── components.tf
├── config.tf
├── dist-config.tf
├── files
│   └──assumption-policy.json
├── hardening-pipeline.tfvars
├── image.tf
├── infr-config.tf
├── infra-network-config.tf
├── kms-key.tf
├── main.tf
├── outputs.tf
├── pipeline.tf
├── recipes.tf
├── roles.tf
├── sec-groups.tf
├── trigger-build.tf
└── variables.tf
```

**模組詳細資訊**
+ `components.tf` 包含上傳`/files`目錄內容的 Amazon S3 上傳資源。您也可以在這裡以模組化方式新增自訂元件 YAML 檔案。
+ `/files` 包含定義 中所用元件`.yml`的檔案`components.tf`。
+ `image.tf` 包含基礎映像作業系統的定義。您可以在此修改不同基礎映像管道的定義。
+ `infr-config.tf` 和 `dist-config.tf`包含啟動和分配映像所需的最低 AWS 基礎設施的資源。
+ `infra-network-config.tf` 包含要部署容器映像的最小 VPC 基礎設施。
+ `hardening-pipeline.tfvars` 包含要在套用時間使用的 Terraform 變數。
+ `pipeline.tf` 在 Terraform 中建立和管理 EC2 Image Builder 管道。
+ `recipes.tf` 您可以在其中指定不同的元件混合，以建立容器配方。
+ `roles.tf` 包含 Amazon Elastic Compute Cloud (Amazon EC2) 執行個體描述檔和管道部署角色的 AWS Identity and Access Management (IAM) 政策定義。
+ `trigger-build.tf` 包含 EventBridge 規則和 SQS 佇列資源。

**目標架構**

![\[為強化容器映像建置管道的架構和工作流程\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/images/pattern-img/4b16bdfa-4f34-41e9-a69a-d023253c8585/images/23443eca-132f-46ac-98bd-32a9e9359a77.png)


圖表說明下列工作流程：

1. EC2 Image Builder 會使用定義的配方來建置容器映像，這會安裝作業系統更新，並將 RHEL Medium STIG 套用至 Amazon Linux 2 基礎映像。

1. 強化的映像會發佈至私有 Amazon ECR 登錄檔，而 EventBridge 規則會在映像成功發佈時傳送訊息至 SQS 佇列。

1. 如果 Amazon Inspector 設定為增強型掃描，則會掃描 Amazon ECR 登錄檔。

1. 如果 Amazon Inspector 為映像產生**嚴重**或**高**嚴重性問題清單，EventBridge 規則會觸發 EC2 Image Builder 管道再次執行，並發佈新強化的映像。

**自動化和擴展**
+ 此模式說明如何在您的電腦上佈建基礎設施和建置管道。不過，它旨在大規模使用。您可以在多帳戶環境中使用它們，例如 [AWS Control Tower](https://docs.aws.amazon.com/controltower/latest/userguide/what-is-control-tower.html) with [Account Factory for Terraform environment，而不是在本機部署 Terraform](https://aws.amazon.com/blogs/aws/new-aws-control-tower-account-factory-for-terraform/) 模組。在這種情況下，您應該使用[後端狀態 S3 儲存貯](https://developer.hashicorp.com/terraform/language/settings/backends/s3)體來管理 Terraform 狀態檔案，而不是在本機管理組態狀態。
+ 針對擴展用途，請從 Control Tower 或登陸區域帳戶模型將解決方案部署至一個中央帳戶，例如共用服務或通用服務帳戶，並授予取用者帳戶存取 Amazon ECR 儲存庫和 AWS KMS 金鑰的許可。如需設定的詳細資訊，請參閱 re：Post 文章[如何允許次要帳戶在 Amazon ECR 映像儲存庫中推送或提取映像？](https://repost.aws/knowledge-center/secondary-account-access-ecr) 例如，在[帳戶販賣機](https://www.hashicorp.com/resources/terraform-landing-zones-for-self-service-multi-aws-at-eventbrite)或 Account Factory for Terraform 中，為每個帳戶基準或帳戶自訂基準新增許可，以提供對該 Amazon ECR 儲存庫和加密金鑰的存取權。
+ 部署容器映像管道之後，您可以使用 [元件](https://docs.aws.amazon.com/imagebuilder/latest/userguide/manage-components.html)等 EC2 Image Builder 功能進行修改，這可協助您將更多元件封裝到 Docker 建置中。
+ 用於加密容器映像的 AWS KMS 金鑰應該在映像要使用的帳戶之間共用。
+ 您可以複製整個 Terraform 模組並修改下列`recipes.tf`屬性，以新增對其他映像的支援：
  + 修改`parent_image = "amazonlinux:latest"`為另一個影像類型。
  + 修改 `repository_name` 以指向現有的 Amazon ECR 儲存庫。這會建立另一個管道，將不同的父系映像類型部署到現有的 Amazon ECR 儲存庫。

## 工具
<a name="build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform-tools"></a>

**工具**
+ Terraform (IaC 佈建）
+ Git （如果在本機佈建）
+ AWS CLI 第 1 版或第 2 版 （如果在本機佈建）

**程式碼 **

此模式的程式碼位於 GitHub 儲存庫 [Terraform EC2 Image Builder Container Hardening Pipeline](https://github.com/aws-samples/terraform-ec2-image-builder-container-hardening-pipeline) 中。若要使用範例程式碼，請依照下一節中的指示進行。

## 史詩
<a name="build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform-epics"></a>

### 佈建 基礎設施
<a name="provision-the-infrastructure"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 設定本機登入資料。 | 設定您的 AWS 臨時登入資料。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform.html) | AWS DevOps | 
| 複製儲存庫。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform.html) | AWS DevOps | 
| 更新變數。 | 更新 `hardening-pipeline.tfvars` 檔案中的變數，以符合您的環境和所需的組態。您必須提供自己的 `account_id`。不過，您也應該修改其餘的變數，以符合所需的部署。所有變數都是必要的。<pre>account_id     = "<DEPLOYMENT-ACCOUNT-ID>"<br />aws_region     = "us-east-1"<br />vpc_name       = "example-hardening-pipeline-vpc"<br />kms_key_alias = "image-builder-container-key"<br />ec2_iam_role_name = "example-hardening-instance-role"<br />hardening_pipeline_role_name = "example-hardening-pipeline-role"<br />aws_s3_ami_resources_bucket = "example-hardening-ami-resources-bucket-0123"<br />image_name = "example-hardening-al2-container-image"<br />ecr_name = "example-hardening-container-repo"<br />recipe_version = "1.0.0" <br />ebs_root_vol_size = 10</pre>以下是每個變數的描述：[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform.html) | AWS DevOps | 
| 初始化 Terraform。 | 更新變數值後，您可以初始化 Terraform 組態目錄。初始化組態目錄會下載並安裝組態中定義的 AWS 提供者。<pre>terraform init</pre>您應該會看到一則訊息，指出 Terraform 已成功初始化，並識別已安裝的提供者版本。 | AWS DevOps | 
| 部署基礎設施並建立容器映像。 | 使用以下命令，使用 `.tfvars` 檔案中定義的變數來初始化、驗證 Terraform 模組，並將模組套用至環境：<pre>terraform init && terraform validate && terraform apply -var-file *.tfvars -auto-approve</pre> | AWS DevOps | 
| 自訂容器。 | 您可以在 EC2 Image Builder 部署管道和初始配方之後，建立新的容器配方版本。您可以在 EC2 Image Builder 中新增任何可用的 31\$1 個元件，以自訂容器建置。如需詳細資訊，請參閱 EC2 Image Builder 文件中[建立新版本容器配方](https://docs.aws.amazon.com/imagebuilder/latest/userguide/create-container-recipes.html)的*元件*一節。 | AWS 管理員 | 

### 驗證資源
<a name="validate-resources"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 驗證 AWS 基礎設施佈建。 | 成功完成第一個 Terraform `apply`命令後，如果您要在本機佈建，您應該會在本機機器的終端機中看到此程式碼片段：<pre>Apply complete! Resources: 43 added, 0 changed, 0 destroyed.</pre> | AWS DevOps | 
| 驗證個別 AWS 基礎設施資源。 | 若要驗證已部署的個別資源，如果您在本機佈建，您可以執行下列命令：<pre>terraform state list</pre>此命令會傳回 43 個資源的清單。 | AWS DevOps | 

### 移除資源
<a name="remove-resources"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 移除基礎設施和容器映像。 | 使用完 Terraform 組態後，您可以執行下列命令來移除資源：<pre>terraform init && terraform validate && terraform destroy -var-file *.tfvars -auto-approve</pre> | AWS DevOps | 

## 疑難排解
<a name="build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform-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 CLI 文件中的[設定和檢視組態設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-methods)。 | 

## 相關資源
<a name="build-a-pipeline-for-hardened-container-images-using-ec2-image-builder-and-terraform-resources"></a>
+ [Terraform EC2 映像建置器容器強化管道 ](https://github.com/aws-samples/terraform-ec2-image-builder-container-hardening-pipeline)(GitHub 儲存庫）
+ [EC2 Image Builder 文件](https://docs.aws.amazon.com/imagebuilder/latest/userguide/what-is-image-builder.html)
+ 適用於 [Terraform 的 AWS Control Tower 帳戶工廠](https://aws.amazon.com/blogs/aws/new-aws-control-tower-account-factory-for-terraform/) (AWS 部落格文章）
+ [後端狀態 S3 儲存貯](https://developer.hashicorp.com/terraform/language/settings/backends/s3)體 (Terraform 文件）
+ [安裝或更新最新版本的 AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) (AWS CLI 文件）
+ [下載 Terraform](https://developer.hashicorp.com/terraform/downloads)