

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

# 在本地验证 Account Factory for Terraform (AFT) 代码
<a name="validate-account-factory-for-terraform-aft-code-locally"></a>

*Alexandru Pop 和 Michal Gorniak，Amazon Web Services*

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

此模式显示了如何在本地测试由 Acco AWS Control Tower unt Fact HashiCorp ory for Terraform（AFT）管理的 Terraform 代码。Terraform 是一款基础设施即代码（IaC）工具，可帮助您使用代码来预调配和管理云基础设施和资源。AFT 设置了一个 Terraform 管道，可以帮助你在其中配置和自定义多个 AWS 账户 管道。 AWS Control Tower

在代码开发过程中，在 AFT 管道之外，在本地测试 Terraform 基础设施即代码（IaC）可能非常有用。此模式说明了如何执行以下操作：
+ 检索存储在您的 AFT 管理账户存储 AWS CodeCommit 库中的 Terraform 代码的本地副本。
+ 使用检索到的代码，在本地模拟 AFT 管道。

此过程还可以用于运行不属于普通 AFT 管道的 Terraform 命令。例如，您可使用此方法来运行 `terraform validate`、`terraform plan`、`terraform destroy` 和 `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 部署中使用的版本相匹配）

**限制**
+ 此模式不包括 AFT 或任何特定 Terraform 模块所需的 AWS Control Tower部署步骤。
+ 在此过程中在本地生成的输出不会保存到 AFT 管道运行时日志中。

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

**目标技术堆栈**
+ 部署在部署中部署的 AFT 基础架构 AWS Control Tower 
+ Terraform
+ Git
+ AWS CLI 第 2 版

**自动化和扩展**

此模式显示了如何在单个 AFT 管理的单个 AFT 管理中本地调用 Terraform 代码以进行 AFT 全局账户自定义。 AWS 账户验证您的 Terraform 代码之后，您可以将其应用到多账户环境中的其余账户。有关更多信息，请参阅文档中的 “[重新调用自定义](https://docs.aws.amazon.com/controltower/latest/userguide/aft-account-customization-options.html#aft-re-invoke-customizations)” AWS Control Tower 。

您还可以使用类似的过程，在本地终端中进行 AFT 账户自定义。要从 AFT 账户自定义项中本地调用 Terraform 代码，请在 AFT 管理账户中克隆**aft-account-customizations**存储库，而不是从 AFT **aft-global-account-customizations**管理账户 CodeCommit 中克隆存储库。

## 工具
<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 服务 通过命令行外壳中的命令进行交互。

**其他服务**
+ [HashiCorp Terraform](https://www.terraform.io/docs) 是一款基础设施即代码（IaC）工具，可帮助您使用代码来预调配和管理云基础设施和资源。
+ [Git](https://git-scm.com/docs) 是开源分布式版本控制系统。

**代码**

以下是 bash 脚本示例，可在本地运行由 AFT 管理的 Terraform 代码。若要使用此脚本，请按照此模式[操作说明](#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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将示例代码保存为本地文件。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/prescriptive-guidance/latest/patterns/validate-account-factory-for-terraform-aft-code-locally.html)您的组织可能还有一个自定义工具，可以为您的 AWS 环境提供身份验证凭证。 | AWS 管理员 | 
| 在正确的 AWS 区域中，验证对 AFT 管理账户的访问权限。 | 请确保使用您通过身份验证登录到您的 AFT 管理账户时使用的那个终端会话。[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 打开之前运行的 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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 实施要验证的 Terraform 配置更改。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_cn/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_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将对 `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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 将更改发布到由 AFT 管理的所有账户。 | 要将更改推广到由 AFT 管理 AWS 账户 的多个项目，请按照文档中 “[重新调用自定义](https://docs.aws.amazon.com/controltower/latest/userguide/aft-account-customization-options.html#aft-re-invoke-customizations)” 中的 AWS Control Tower 说明进行操作。 | AWS 管理员 | 