

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

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

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

这种模式利用 Ac GitHub tions 工作流程通过标准化的 JSON 负载自动配置资源，无需手动配置。这个自动化管道管理着完整的部署生命周期，并且可以与各种前端系统无缝集成，从自定义用户界面组件到 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)，然后选择相应服务的链接。

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

下图显示了此模式的组件和工作流。

![使用 GitHub 操作和 Terraform 自动配置资源的工作流程。](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/images/pattern-img/bff5d70e-e8f1-454a-94bc-60e8cc16e69f/images/d4a768c8-4e11-493c-85ed-f4bf7e76ce60.png)


架构图显示了以下操作：

1. 用户向 GitHub 操作提交 JSON 有效负载，从而触发自动化管道。

1.  GitHub 操作管道根据有效载荷规格从 Terragrunt 和 Terraform 存储库中检索所需的资源代码。

1. 管道使用指定 AWS 账户 ID 担任相应的 AWS Identity and Access Management (IAM) 角色。然后，管道将资源部署到目标，并使用特定于账户的 Amazon S3 存储桶 AWS 账户 和 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（亚马逊 VPC）](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html)可帮助您将 AWS 资源启动到您定义的虚拟网络中。该虚拟网络类似于您在数据中心中运行的传统网络，并具有使用 AWS的可扩展基础设施的优势。

**其他工具**
+ GitHub A@@ [c](https://docs.github.com/en/actions) tions 是一个持续集成和持续交付 (CI/CD) 平台，与 GitHub 存储库紧密集成。您可以使用 GitHub Actions 来自动执行构建、测试和部署管道。
+ [Terraform](https://www.terraform.io/) 是一款基础设施即代码 (IaC) 工具 HashiCorp ，可帮助您创建和管理云和本地资源。
+ [Terragrunt](https://terragrunt.gruntwork.io/docs/getting-started/overview/) 是一款编排工具，它扩展了 Terraform 和 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 凭证和敏感数据，以实现安全访问。
+ 将 OpenID Connect (OIDC) 提供程序配置为 GitHub 操作代入 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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 初始化 GitHub 存储库。 | 要初始化 GitHub 存储库，请使用以下步骤：[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/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_cn/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html) | DevOps 工程师 | 
| 设置 GitHub 机密和变量。 | 有关如何在存储库中设置存储库密钥和变量的说明，请参阅 GitHub 文档中的[为仓库创建配置变量](https://docs.github.com/en/actions/how-tos/write-workflows/choose-what-workflows-do/use-variables#creating-configuration-variables-for-a-repository)。 GitHub 配置以下变量：[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/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_cn/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>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 使用 curl 执行管道。 | 要使用 [curl](https://curl.se/) 执行管道，请执行以下步骤：[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html)<br />有关管道执行流程的更多信息，请参阅[其他信息](#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_cn/prescriptive-guidance/latest/patterns/create-an-api-driven-resource-orchestration-framework-using-github-actions-and-terragrunt.html)<br />您还可以使用在存储库中创建的 `output.json` 文件来交叉验证已创建的资源，其中该文件与 `terragrunt.hcl` 文件位于同一资源内。 | DevOps 工程师 | 

### 清理 资源
<a name="clean-up-resources"></a>


| Task | 说明 | 所需技能 | 
| --- | --- | --- | 
| 提交清理请求。 | 要删除不再需要的资源，请使用以下步骤：[See the AWS documentation website for more details](http://docs.aws.amazon.com/zh_cn/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 CloudTrail 日志监控 CloudWatch 日志文件](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 resources**
+ [创建存储库分派事件](https://docs.github.com/en/rest/repos/repos?apiVersion=2022-11-28#create-a-repository-dispatch-event)
+ [创建 web 挂钩](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 角色**-进行身份验证并担任操作所需的 IAM 角色 AWS 

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` – 环境（例如，开发和生产）
+ `Suffix`– 资源的附加标识符

`ResourceParameters`包含特定于资源的配置，该配置映射到 Terraform 文件中定义的变量。任何需要传递给 Terraform 模块的自定义变量都应包含在中。`ResourceParameters`对于 Amazon VPC，参数 `vpc_cidr` 是强制的。