Terraform
使用 HCP Terraform 进行协作
在集合中的先前教程中,您使用 Terraform 创建、管理和销毁来自本地机器的基础设施。从本地机器管理 Terraform 工作区会创建一个单点故障,并使与团队协作进行基础设施项目变得困难。
HCP Terraform 允许您在组织内协作进行基础设施项目。它提供了一个安全的远程执行环境,让您可以协作管理基础设施的更改。它还会安全地存储 Terraform 状态和变量,包括 API 令牌和访问密钥。Terraform CLI 与 HCP Terraform 集成,因此您可以从本地机器触发远程运行。
在本教程中,您将把本地工作区迁移到 HCP Terraform,并使用 CLI 驱动的工作流程来触发运行。HCP Terraform 还支持使用 API 驱动的工作流程或 VCS 驱动的工作流程来配置基础设施,后者会在配置的仓库发生任何更改时触发运行。
先决条件
要遵循本教程,您需要
- 已安装 Terraform CLI(1.2.0+)。
- 已安装 AWS CLI。
- 一个 AWS 账户和 关联的凭证,允许您在
us-west-2区域中创建资源,包括一个 EC2 实例、VPC 和安全组。 - 本系列教程中 先前教程 中的配置和基础设施。
创建资源
在 上一教程中,您销毁了使用 Terraform 创建的基础设施。再次应用您的配置以重新创建工作区的基础设施。对确认提示回复 yes。
$ terraform apply
data.aws_ami.ubuntu: Reading...
data.aws_ami.ubuntu: Read complete after 1s [id=ami-0026a04369a3093cc]
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# module.vpc.aws_default_network_acl.this[0] will be created
+ resource "aws_default_network_acl" "this" {
+ arn = (known after apply)
+ default_network_acl_id = (known after apply)
+ id = (known after apply)
+ owner_id = (known after apply)
##...
Plan: 15 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
module.vpc.aws_vpc.this[0]: Creating...
module.vpc.aws_vpc.this[0]: Still creating... [10s elapsed]
module.vpc.aws_vpc.this[0]: Creation complete after 13s [id=vpc-07b6253940b170243]
## ...
module.vpc.aws_route_table_association.public[0]: Creating...
module.vpc.aws_subnet.private[1]: Creation complete after 4s [id=subnet-0daa2b4c37d3d9bd1]
module.vpc.aws_route_table_association.private[0]: Creating...
module.vpc.aws_route_table_association.private[1]: Creating...
module.vpc.aws_route_table_association.public[0]: Creation complete after 0s [id=rtbassoc-0f3b7ed7e1f49d2a1]
module.vpc.aws_route_table_association.private[0]: Creation complete after 0s [id=rtbassoc-01e3f044ca6bb5fe0]
module.vpc.aws_route_table_association.private[1]: Creation complete after 0s [id=rtbassoc-0647d3c7904113d60]
Apply complete! Resources: 15 added, 0 changed, 0 destroyed.
现在您已经重新创建了 VPC 和相关资源,将您本地工作区的状态迁移到 HCP Terraform。
注册 HCP Terraform
您需要一个 HCP Terraform 帐户才能完成本教程。访问 HCP Terraform 并按照提示创建一个 HCP Terraform 帐户。如果您已经拥有 HCP Terraform 帐户,可以使用它代替创建新帐户完成本教程。
在您使用 HCP Terraform 注册时,将收到一封电子邮件要求您确认您的电子邮件地址。单击链接确认您的电子邮件地址后,HCP Terraform 会将您带到组织页面。单击创建组织并按照提示创建您的新组织。
登录 HCP Terraform
接下来,使用 Terraform CLI 登录您的 HCP Terraform 帐户,方法是在终端中运行 terraform login。
$ terraform login
Terraform will request an API token for app.terraform.io using your browser.
If login is successful, Terraform will store the token in plain text in
the following file for use by subsequent commands:
/Users/YOU/.terraform.d/credentials.tfrc.json
Do you want to proceed?
Only 'yes' will be accepted to confirm.
Enter a value:
对确认提示回复 yes,Terraform 将打开浏览器窗口以允许您创建 API 令牌。
Enter a value: yes
---------------------------------------------------------------------------------
Terraform must now open a web browser to the tokens page for app.terraform.io.
If a browser does not open this automatically, open the following URL to proceed:
https://app.terraform.io/app/settings/tokens?source=terraform-login
---------------------------------------------------------------------------------
Generate a token using your browser, and copy-paste it into this prompt.
Terraform will store the token in plain text in the following file
for use by subsequent commands:
/Users/YOU/.terraform.d/credentials.tfrc.json
Token for app.terraform.io:
Enter a value:
按照浏览器中的工作流程生成 API 令牌。然后,在 Terraform 提示时将 API 令牌粘贴到您的终端中。Terraform 在您粘贴令牌时不会在屏幕上打印您的令牌。有关登录 HCP Terraform 的更多详细信息,请参阅 使用 HCP Terraform 身份验证 CLI 教程。
Enter a value:
Retrieved token for user YOU
---------------------------------------------------------------------------------
-
----- -
--------- --
--------- - -----
--------- ------ -------
------- --------- ----------
---- ---------- ----------
-- ---------- ----------
Welcome to HCP Terraform! - ---------- -------
--- ----- ---
Documentation: terraform.io/docs/cloud -------- -
----------
----------
---------
-----
-
New to HCP Terraform? Follow these steps to instantly apply an example configuration:
$ git clone https://github.com/hashicorp/tfc-getting-started.git
$ cd tfc-getting-started
$ scripts/setup.sh
将工作区连接到 HCP Terraform
为了将你的工作区连接到 HCP Terraform,你需要更新你的配置并从命令行重新初始化你的工作区。HCP Terraform 工作区类似于本地 Terraform 工作区,但会在 HCP Terraform 中执行 Terraform 操作并存储你的状态。HCP Terraform 还支持将你的工作区分组到项目中,以便更轻松地管理它们的访问权限和设置。
更新配置
在 terraform.tf 中更新 terraform 块,以添加将你的本地工作区连接到 HCP Terraform 的 cloud 块。
terraform.tf
terraform {
cloud {
organization = "your-organization-name"
workspaces {
project = "Learn Terraform"
name = "learn-terraform-aws-get-started"
}
}
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.92"
}
}
required_version = ">= 1.2.0"
}
将 your-organization-name 替换为你的组织名称,你可以在 HCP Terraform 门户中找到它。

迁移到 HCP Terraform
现在你已经配置了 HCP Terraform 集成,运行 terraform init 以重新初始化你的配置并将你的状态复制到 HCP Terraform。对确认提示回复 yes 以确认迁移。
$ terraform init
Initializing HCP Terraform...
Do you wish to proceed?
As part of migrating to HCP Terraform, Terraform can optionally copy
your current workspace state to the configured HCP Terraform workspace.
Answer "yes" to copy the latest state snapshot to the configured
HCP Terraform workspace.
Answer "no" to ignore the existing state and just activate the configured
HCP Terraform workspace with its existing state, if any.
Should Terraform migrate your existing state?
Enter a value: yes
Initializing modules...
Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v5.98.0
HCP Terraform has been successfully initialized!
You may now begin working with HCP Terraform. Try running "terraform plan" to
see any changes that are required for your infrastructure.
If you ever set or change modules or Terraform Settings, run "terraform init"
again to reinitialize your working directory.
当你在配置中添加 cloud 块后运行 terraform init 时,Terraform 会在项目和工作区不存在时创建新的项目和工作区,或者在它们已经存在时使用现有的项目和工作区。
配置 AWS 凭据
terraform init 步骤在你的 HCP Terraform 组织中创建了 Learn Terraform 项目和 learn-terraform-aws-get-started 工作区。为了使 HCP Terraform 能够使用 AWS 提供程序进行身份验证并配置你的资源,你需要使用你的 AWS 凭据配置你的工作区。
导航到你在 HCP Terraform 中的 learn-terraform-aws-get-started 工作区,并转到工作区的 **变量** 页面。在 **工作区变量** 下,将你的 AWS_ACCESS_KEY_ID 和 AWS_SECRET_ACCESS_KEY 添加为 **环境变量**,并确保将它们标记为 **敏感**。

应用配置
现在更新并在 HCP Terraform 中应用你的配置。取消注释 main.tf 中的 EC2 实例配置。
main.tf
resource "aws_instance" "app_server" {
ami = data.aws_ami.ubuntu.id
instance_type = var.instance_type
vpc_security_group_ids = [module.vpc.default_security_group_id]
subnet_id = module.vpc.private_subnets[0]
tags = {
Name = var.instance_name
}
}
同时取消注释 outputs.tf 中的输出值。
outputs.tf
output "instance_hostname" {
description = "Private DNS name of the EC2 instance."
value = aws_instance.app_server.private_dns
}
现在,运行 terraform apply 在 HCP Terraform 中触发运行。Terraform 执行计划和应用运行在 HCP Terraform 中远程进行,并将输出流式传输到你的终端窗口。对确认提示回复 yes 以指示 HCP Terraform 配置你的基础设施。
$ terraform apply
will cancel the remote apply if it's still pending. If the apply started it
will stop streaming the logs, but will not stop the apply running remotely.
Preparing the remote apply...
To view this run in a browser, visit:
https://app.terraform.io/app/your-organization-name/learn-terraform-aws-get-started/runs/run-abCDEFghijkLMnopY
Waiting for the plan to start...
## ...
Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_instance.app_server will be created
+ resource "aws_instance" "app_server" {
+ ami = "ami-0e847e970c9565775"
+ arn = (known after apply)
## ...
Plan: 1 to add, 0 to change, 0 to destroy.
Changes to Outputs:
+ instance_hostname = (known after apply)
Do you want to perform these actions in workspace "learn-terraform-aws-get-started"?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
aws_instance.app_server: Creating...
aws_instance.app_server: Still creating... [10s elapsed]
aws_instance.app_server: Creation complete after 13s [id=i-0be76e73004969a35]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
Outputs:
instance_hostname = "ip-10-0-1-111.us-west-2.compute.internal"
Terraform 现在将您的工作区的状态远程存储在 HCP Terraform 中。请访问 Terraform 打印出的 URL,以在 HCP Terraform 中查看运行情况。借助 CLI 驱动的工作流程,您可以从本地机器执行 Terraform 命令,HCP Terraform 将执行它们并将输出流式传输到您的 CLI。您还可以查看计划和应用运行的结果,并在 HCP Terraform 中配置您的工作区。
销毁工作区
通过运行 terraform destroy 销毁您在本教程中配置的资源。响应确认提示,输入 yes,指示 HCP Terraform 销毁工作区中管理的所有资源。
$ terraform destroy
Running apply in HCP Terraform. Output will stream here. Pressing Ctrl-C
will cancel the remote apply if it's still pending. If the apply started it
will stop streaming the logs, but will not stop the apply running remotely.
Preparing the remote apply...
To view this run in a browser, visit:
https://app.terraform.io/app/your-organization-name/learn-terraform-aws-get-started/runs/run-zvFXqwertyUIOPab
Waiting for the plan to start...
Terraform v1.12.0
on linux_amd64
Initializing plugins and modules...
## ...
Plan: 0 to add, 0 to change, 16 to destroy.
Changes to Outputs:
- instance_hostname = "ip-10-0-1-111.us-west-2.compute.internal" -> null
Do you really want to destroy all resources in workspace "learn-terraform-aws-get-started"?
Terraform will destroy all your managed infrastructure, as shown above.
There is no undo. Only 'yes' will be accepted to confirm.
Enter a value: yes
module.vpc.aws_default_security_group.this[0]: Destroying... [id=sg-014b478a2b1cd316e]
module.vpc.aws_route_table_association.public[0]: Destroying... [id=rtbassoc-0f3b7ed7e1f49d2a1]
module.vpc.aws_route_table_association.private[1]: Destroying... [id=rtbassoc-0647d3c7904113d60]
module.vpc.aws_default_network_acl.this[0]: Destroying... [id=acl-0fafc47f15e7c59f5]
module.vpc.aws_route.public_internet_gateway[0]: Destroying... [id=r-rtb-0956189f24b1a92ae1080289494]
module.vpc.aws_route_table_association.private[0]: Destroying... [id=rtbassoc-01e3f044ca6bb5fe0]
module.vpc.aws_default_route_table.default[0]: Destroying... [id=rtb-0a78b66d2a9e3e4d7]
## ...
aws_instance.app_server: Still destroying... [id=i-069c5ad5f53ba2ce2, 01m20s elapsed]
aws_instance.app_server: Still destroying... [id=i-069c5ad5f53ba2ce2, 01m30s elapsed]
aws_instance.app_server: Destruction complete after 1m33s
module.vpc.aws_subnet.private[1]: Destroying... [id=subnet-0daa2b4c37d3d9bd1]
module.vpc.aws_subnet.private[0]: Destroying... [id=subnet-0c30a4ca611a967c3]
module.vpc.aws_subnet.private[0]: Destruction complete after 0s
module.vpc.aws_subnet.private[1]: Destruction complete after 1s
module.vpc.aws_vpc.this[0]: Destroying... [id=vpc-0a3754c28c3d86167]
module.vpc.aws_vpc.this[0]: Destruction complete after 0s
Destroy complete! Resources: 16 destroyed.
接下来,通过导航到您的 learn-terraform-aws-get-started 工作区的 HCP Terraform 中的 设置 > 销毁和删除 选项卡来删除您的工作区。单击 从 HCP Terraform 中删除 按钮,然后按照提示删除您的工作区。
您还可以通过导航到其 设置 页面,单击 删除 按钮,然后按照提示删除您的项目。
交互式终端
您可以在我们的交互式终端中学习如何在不设置云账户的情况下创建您的基础设施。
启动终端
本教程包括一个免费的交互式命令行实验室,您可以跟随实际云基础设施进行操作。
下一步
在这些教程中,您学习了如何安装 Terraform CLI,如何使用它来创建、管理和销毁基础设施,以及如何将您的工作区迁移到 HCP Terraform。随着您的基础设施运营日益成熟,HCP Terraform 允许您与您的团队协作,安全地存储您的状态和变量,并与您的版本控制系统集成以管理您的 Terraform 配置。
有关 Terraform 配置语言、资源管理或导入现有基础设施的更多实践经验,请查看以下资源。
配置语言 - 进一步熟悉变量、输出、依赖项、元参数和其他语言特性,以编写更复杂的 Terraform 配置。
模块 - 使用模块组织和重用 Terraform 配置。
- 了解如何使用 Terraform 管理其他 AWS 资源。
要获得 HCP Terraform VCS 驱动的工作流程的实践介绍,请 按照 HCP Terraform 入门教程。