

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

# 在本機驗證帳戶工廠的 Terraform (AFT) 程式碼
<a name="validate-account-factory-for-terraform-aft-code-locally"></a>

*Alexandru Pop 和 Michal Gorniak，Amazon Web Services*

## 總結
<a name="validate-account-factory-for-terraform-aft-code-locally-summary"></a>

此模式說明如何在本機測試由 AWS Control Tower Account Factory for Terraform (AFT) 管理的 HashiCorp Terraform 程式碼。Terraform 是一種基礎設施即程式碼 (IaC) 工具，可協助您使用程式碼來佈建和管理雲端基礎設施和資源。AFT 會設定 Terraform 管道，協助您 AWS 帳戶 佈建和自訂多個管道 AWS Control Tower。

在程式碼開發期間，在 AFT 管道外部以程式碼 (IaC) 形式在本機測試 Terraform 基礎設施會很有幫助。此模式顯示如何執行下列動作：
+ 擷取儲存在 AFT 管理帳戶中 AWS CodeCommit 儲存庫中 Terraform 程式碼的本機副本。
+ 使用擷取的程式碼在本機模擬 AFT 管道。

此程序也可以用來執行不屬於正常 AFT 管道的 Terraform 命令。例如，您可以使用此方法執行命令，例如 `terraform validate`、`terraform destroy`、 `terraform plan`和 `terraform import`。

## 先決條件和限制
<a name="validate-account-factory-for-terraform-aft-code-locally-prereqs"></a>

**先決條件**
+ 使用 的作用中 AWS 多帳戶環境 [AWS Control Tower](https://aws.amazon.com/controltower)
+ 完全部署的 [AFT 環境](https://docs.aws.amazon.com/controltower/latest/userguide/taf-account-provisioning.html)
+ AWS Command Line Interface (AWS CLI)，[已安裝](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)並[設定](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html)
+ [AWS CLI 的登入資料協助程式 AWS CodeCommit](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-https-unixes.html)、安裝和設定
+ Python 3.x
+ 在本機電腦上安裝和設定的 [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
+ `git-remote-commit` 公用程式，[已安裝和設定](https://docs.aws.amazon.com/codecommit/latest/userguide/setting-up-git-remote-codecommit.html#setting-up-git-remote-codecommit-install)
+ [安裝並設定 Terraform](https://learn.hashicorp.com/collections/terraform/aws-get-started?utm_source=WEBSITE&utm_medium=WEB_IO&utm_offer=ARTICLE_PAGE&utm_content=DOCS) （本機 Terraform 套件版本必須與 AFT 部署中使用的版本相符）

**限制**
+ 此模式不包含 AWS Control Tower、AFT 或任何特定 Terraform 模組所需的部署步驟。
+ 在此程序期間在本機產生的輸出不會儲存在 AFT 管道執行時間日誌中。

## Architecture
<a name="validate-account-factory-for-terraform-aft-code-locally-architecture"></a>

**目標技術堆疊**
+ 部署內部署的 AFT 基礎設施 AWS Control Tower 
+ Terraform
+ Git
+ AWS CLI 第 2 版

**自動化和擴展**

此模式示範如何針對單一 AFT 受管的 AFT 全域帳戶自訂，在本機叫用 Terraform 程式碼 AWS 帳戶。驗證 Terraform 程式碼之後，您可以將其套用至多帳戶環境中的其餘帳戶。如需詳細資訊，請參閱 AWS Control Tower 文件中的[重新叫用自訂](https://docs.aws.amazon.com/controltower/latest/userguide/aft-account-customization-options.html#aft-re-invoke-customizations)。

您也可以使用類似的程序，在本機終端機中執行 AFT 帳戶自訂。若要從 AFT 帳戶自訂本機叫用 Terraform 程式碼，請在 AFT 管理帳戶中從 CodeCommit 複製 **aft-account-customizations** 儲存庫，而非 **aft-global-account-customizations** 儲存庫。

## 工具
<a name="validate-account-factory-for-terraform-aft-code-locally-tools"></a>

**AWS 服務**
+ [AWS Control Tower](https://docs.aws.amazon.com/controltower/latest/userguide/what-is-control-tower.html) 可協助您設定和管理 AWS 多帳戶環境，並遵循規範最佳實務。
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html) 是一種開放原始碼工具，可協助您 AWS 服務 透過命令列 shell 中的命令與 互動。

**其他服務**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一種基礎設施即程式碼 (IaC) 工具，可協助您使用程式碼來佈建和管理雲端基礎設施和資源。
+ [Git](https://git-scm.com/docs) 是開放原始碼的分散式版本控制系統。

**Code**

以下是範例 bash 指令碼，可用於在本機執行由 AFT 管理的 Terraform 程式碼。若要使用指令碼，請遵循此模式的 [Epics](#validate-account-factory-for-terraform-aft-code-locally-epics) 區段中的指示。

```
#! /bin/bash
# Version: 1.1 2022-06-24 Unsetting AWS_PROFILE since, when set, it interferes with script operation
#          1.0 2022-02-02 Initial Version
#
# Purpose: For use with AFT: This script runs the local copy of TF code as if it were running within AFT pipeline.
#        * Facilitates testing of what the AFT pipline will do 
#           * Provides the ability to run terraform with custom arguments (like 'plan' or 'move') which are currently not supported within the pipeline.
#
# © 2021 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.
# This AWS Content is provided subject to the terms of the AWS Customer Agreement
# available at http://aws.amazon.com/agreement or other written agreement between
# Customer and either Amazon Web Services, Inc. or Amazon Web Services EMEA SARL or both.
#
# Note: Arguments to this script are passed directly to 'terraform' without parsing nor validation by this script.
#
# Prerequisites:
#    1. local copy of ct GIT repositories
#    2. local backend.tf and aft-providers.tf filled with data for the target account on which terraform is to be run
#       Hint: The contents of above files can be obtain from the logs of a previous execution of the AFT pipeline for the target account.
#    3. 'terraform' binary is available in local PATH
#    4. Recommended: .gitignore file containing 'backend.tf', 'aft_providers.tf' so the local copy of these files are not pushed back to git

readonly credentials=$(aws sts assume-role \
    --role-arn arn:aws:iam::$(aws sts get-caller-identity --query "Account" --output text ):role/AWSAFTAdmin \
    --role-session-name AWSAFT-Session \
    --query Credentials )

unset AWS_PROFILE
export AWS_ACCESS_KEY_ID=$(echo $credentials | jq -r '.AccessKeyId')
export AWS_SECRET_ACCESS_KEY=$(echo $credentials | jq -r '.SecretAccessKey')
export AWS_SESSION_TOKEN=$(echo $credentials | jq -r '.SessionToken')
terraform "$@"
```

## 史詩
<a name="validate-account-factory-for-terraform-aft-code-locally-epics"></a>

### 將範例程式碼儲存為本機檔案
<a name="save-the-example-code-as-a-local-file"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將範例程式碼儲存為本機檔案。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html) | AWS 管理員 | 
| 讓範例程式碼可執行。 | 開啟終端機視窗，並執行下列其中一項操作來驗證您的 AWS AFT 管理帳戶：[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html)您的組織可能也有自訂工具，可為您的 AWS 環境提供身分驗證憑證。 | AWS 管理員 | 
| 在正確的 中驗證對 AFT 管理帳戶的存取 AWS 區域。 | 請確定您使用與您向 AFT 管理帳戶驗證的相同終端機工作階段。[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html) | AWS 管理員 | 
| 建立新的本機目錄來存放 AFT 儲存庫程式碼。 | 在相同的終端機工作階段中，執行下列命令：<pre>mkdir my_aft <br />cd my_aft</pre> | AWS 管理員 | 
| 複製遠端 AFT 儲存庫程式碼。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html) | AWS 管理員 | 

### 建立 AFT 管道在本機執行所需的 Terraform 組態檔案
<a name="create-the-terraform-configuration-files-required-for-the-aft-pipeline-to-run-locally"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 開啟先前執行的 AFT 管道，並將 Terraform 組態檔案複製到本機資料夾。 | AFT 管道需要在此史詩中建立的 `backend.tf`和 `aft-providers.tf`組態檔案，才能在本機執行。這些檔案會在雲端型 AFT 管道內自動建立，但必須手動建立，管道才能在本機執行。在本機執行 AFT 管道需要一組檔案，代表在單一 中執行管道 AWS 帳戶。[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html)**自動產生的 backend.tf 陳述式範例**<pre>## Autogenerated backend.tf ##<br />## Updated on: 2022-05-31 16:27:45 ##<br />terraform {<br />  required_version = ">= 0.15.0"<br />  backend "s3" {<br />    region         = "us-east-2"<br />    bucket         = "aft-backend-############-primary-region"<br />    key            = "############-aft-global-customizations/terraform.tfstate"<br />    dynamodb_table = "aft-backend-############"<br />    encrypt        = "true"<br />    kms_key_id     = "########-####-####-####-############"<br />    role_arn       = "arn:aws:iam::#############:role/AWSAFTExecution"<br />  }<br />}</pre>** **`backend.tf`和 `aft-providers.tf` 檔案繫結至特定 AWS 帳戶、AFT 部署和資料夾。這些檔案也不同，取決於它們是否位於相同 AFT 部署中的 **aft-global-customizations** 和 **aft-account-customizations** 儲存庫中。請務必從相同的執行時間清單中產生這兩個檔案。 | AWS 管理員 | 

### 使用範例 bash 指令碼在本機執行 AFT 管道
<a name="run-the-aft-pipeline-locally-by-using-the-example-bash-script"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 實作您要驗證的 Terraform 組態變更。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html) | AWS 管理員 | 
| 執行`ct_terraform.sh`指令碼並檢閱輸出。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html)** **[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html) | AWS 管理員 | 

### 將您的本機程式碼變更推回 AFT 儲存庫
<a name="push-your-local-code-changes-back-to-the-aft-repository"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將 `backend.tf`和 `aft-providers.tf` 檔案的參考新增至 `.gitignore` 檔案。 | 執行下列命令，將您所建立的 `backend.tf`** **和 `aft-providers.tf` 檔案新增至`.gitignore`檔案：<pre>echo backend.tf >> .gitignore<br />echo aft-providers.tf >>.gitignore</pre>將檔案移至`.gitignore`** **檔案可確保檔案不會遞交並推回遠端 AFT 儲存庫。 | AWS 管理員 | 
| 遞交程式碼變更並將其推送至遠端 AFT 儲存庫。 | [See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_tw/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html)您引入的程式碼會依照此程序進行變更，直到這個時間點 AWS 帳戶 僅套用至一個。 | AWS 管理員 | 

### 將變更推展到多個帳戶
<a name="roll-out-the-changes-to-multiple-accounts"></a>


| 任務 | Description | 所需的技能 | 
| --- | --- | --- | 
| 將變更推展到由 AFT 管理的所有帳戶。 | 若要將變更推展到由 AFT 管理 AWS 帳戶 的多個 ，請遵循 AWS Control Tower 文件中[重新叫用自訂](https://docs.aws.amazon.com/controltower/latest/userguide/aft-account-customization-options.html#aft-re-invoke-customizations)中的指示。 | AWS 管理員 | 