Terraform
构建基础设施
安装 Terraform 后,您就可以创建一些基础设施了。
您将在 Google Cloud Platform (GCP) 上构建基础设施,用于本教程,但 Terraform 可以使用 提供程序 管理各种资源。您可以在 用例部分 中找到更多示例。
在遵循这些教程时,您将使用 Terraform 配置、更新和销毁一组简单的基础设施,使用提供的示例配置。示例配置配置一个网络和一个 Linux 虚拟机。您还将了解远程后端、输入和输出变量以及如何配置资源依赖项。这些是更复杂配置的基础构建块。
先决条件
一个 Google Cloud Platform 帐户。 如果您没有 GCP 帐户,立即创建一个。本教程仅使用 GCP 免费层级 中包含的服务即可完成。
已在本地安装 gcloud CLI。
Terraform 1.2.0+ 安装在本地。
Google Cloud Shell
本教程也可作为 Google Cloud Shell 中的交互式教程提供。如果您愿意,可以 在 Google Cloud Shell 中遵循本教程。
设置 GCP
创建 GCP 帐户后,创建或修改以下资源以启用 Terraform 配置您的基础设施
一个 GCP 项目:GCP 将资源组织到项目中。立即创建一个 在 GCP 控制台中,并记下项目 ID。您可以在 云资源管理器 中查看您的项目列表。
Google Compute Engine:为您的项目 在 GCP 控制台中 启用 Google Compute Engine API。确保选择您用于遵循本教程的项目,然后单击“启用”按钮。
编写配置
用于描述 Terraform 中基础设施的一组文件称为 Terraform 配置。现在,您将编写您的第一个配置来创建一个网络。
每个 Terraform 配置都必须位于自己的工作目录中。为您的配置创建一个目录。
$ mkdir learn-terraform-gcp
进入该目录。
$ cd learn-terraform-gcp
Terraform 会加载工作目录中所有以 .tf 或 .tf.json 结尾的文件。为您的配置创建一个 main.tf 文件。
$ touch main.tf
打开你的文本编辑器,打开 main.tf,并粘贴以下配置。 确保将 <PROJECT_ID> 替换为你的项目 ID,然后保存文件。
terraform {
required_providers {
google = {
source = "hashicorp/google"
version = "6.8.0"
}
}
}
provider "google" {
project = "<PROJECT_ID>"
region = "us-central1"
zone = "us-central1-c"
}
resource "google_compute_network" "vpc_network" {
name = "terraform-network"
}
这是一个 Terraform 可以应用的完整配置。 在接下来的章节中,你将更详细地回顾配置的每个块。
Terraform 块
terraform {} 块包含 Terraform 设置,包括 Terraform 将用于配置你的基础设施的必需的提供程序。 对于每个提供程序,source 属性定义了一个可选的主机名、命名空间和提供程序类型。 Terraform 默认从 Terraform Registry 安装提供程序。 在此示例配置中,google 提供程序的源被定义为 hashicorp/google,这是 registry.terraform.io/hashicorp/google 的简写。
你还可以在 required_providers 块中为每个提供程序定义版本约束。 version 属性是可选的,但我们建议使用它来强制提供程序版本。 否则,Terraform 将始终使用提供程序的最新版本,这可能会引入破坏性更改。
要了解更多信息,请参考 提供器源文档。
提供程序
provider 块配置指定的提供程序,在本例中为 google。 提供程序是 Terraform 用于创建和管理你的资源的插件。 你可以在 Terraform 配置中定义多个提供程序块,以管理来自不同提供程序的资源。
资源
使用 resource 块来定义你的基础设施组件。 资源可能是一个物理组件,例如服务器,或者它可以是一个逻辑资源,例如 Heroku 应用程序。
资源块在块之前有两个字符串:资源类型和资源名称。 在此示例中,资源类型是 google_compute_network,名称是 vpc_network。 类型的前缀映射到提供程序的名称。 在示例配置中,Terraform 使用 google 提供程序管理 google_compute_network 资源。 资源类型和资源名称共同构成资源的唯一 ID。 例如,你的网络的 ID 是 google_compute_network.vpc_network。
资源块包含参数,你使用这些参数来配置资源。 参数可以包括机器大小、磁盘镜像名称或 VPC ID 等。 Terraform Registry GCP 文档页面 记录了每个 GCP 资源的必需和可选参数。 例如,你可以阅读 google_compute_network 文档以查看资源的受支持参数和可用属性。
GCP 提供程序 记录了受支持的资源,包括 google_compute_network 及其受支持的参数。
向 Google Cloud 身份验证
Terraform 必须向 Google Cloud 身份验证才能创建基础设施。
在你的终端中,使用 gcloud CLI 设置你的 应用程序默认凭据。
$ gcloud auth application-default login
你的浏览器将打开并提示你登录到你的 Google Cloud 帐户。 身份验证成功后,你的终端将显示 gcloud CLI 保存你的凭据的路径。
Credentials saved to file: [/Users/USER/.config/gcloud/application_default_credentials.json]
These credentials will be used by any library that requests Application Default Credentials (ADC).
GCP 提供程序会自动使用这些凭据向 Google Cloud API 身份验证。
初始化目录
当您创建一个新的配置,或者检出版本控制中的现有配置时,您需要使用 terraform init 初始化目录。 此步骤会下载配置中定义的提供商。
初始化目录。
$ terraform init
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/google versions matching "6.8.0"...
- Installing hashicorp/google v6.8.0...
- Installed hashicorp/google v6.8.0 (signed by HashiCorp)
Terraform has made some changes to the provider dependency selections recorded
in the .terraform.lock.hcl file. Review those changes and commit them to your
version control system if they represent changes you intended to make.
Terraform has been successfully initialized!
You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.
If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.
Terraform 会下载 google 提供商并将其安装在当前工作目录的隐藏子目录中,名为 .terraform。 terraform init 命令会打印 Terraform 安装的提供商版本。 Terraform 还会创建一个名为 .terraform.lock.hcl 的锁文件,该文件指定了使用的确切提供商版本,以确保每次 Terraform 运行的一致性。 这也允许您控制何时升级配置中使用的提供商。
格式化并验证配置
我们建议在所有配置文件中使用一致的格式。 terraform fmt 命令会自动更新当前目录中的配置,以提高可读性和一致性。
格式化您的配置。Terraform 会打印出它修改过的文件的名称(如果有)。在本例中,您的配置文件已经正确格式化,因此 Terraform 不会返回任何文件名。
$ terraform fmt
您还可以使用 terraform validate 命令确保您的配置在语法上有效且内部一致。
验证您的配置。上述提供的示例配置是有效的,因此 Terraform 将返回一条成功消息。
$ terraform validate
Success! The configuration is valid.
创建基础设施
现在使用 terraform apply 命令应用配置。 Terraform 将打印类似于以下内容的输出。 为了简洁起见,我们已截断了一些输出。
$ terraform apply
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:
# google_compute_network.vpc_network will be created
+ resource "google_compute_network" "vpc_network" {
+ auto_create_subnetworks = true
+ delete_default_routes_on_create = false
+ gateway_ipv4 = (known after apply)
+ id = (known after apply)
+ internal_ipv6_range = (known after apply)
+ mtu = (known after apply)
+ name = "terraform-network"
+ network_firewall_policy_enforcement_order = "AFTER_CLASSIC_FIREWALL"
+ numeric_id = (known after apply)
+ project = (known after apply)
+ routing_mode = (known after apply)
+ self_link = (known after apply)
}
Plan: 1 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:
Terraform 将指示它计划进行的 инфраструктура 更改,并在进行这些更改之前提示您批准。
此输出显示了 *执行计划*,描述了 Terraform 将采取哪些操作以创建与配置匹配的基础设施。 输出格式类似于 Git 等工具生成的 diff 格式。 输出具有 + 位于 resource "google_compute_network" "vpc_network" 旁边,表示 Terraform 将创建此资源。 在其下方,它显示了将设置的属性。 当显示的值为 (known after apply) 时,表示在创建资源之前无法知道该值。
Terraform 现在将暂停并等待批准才能继续。 如果计划中的任何内容看起来不正确或危险,则可以在不更改基础设施的情况下安全地在此处中止。
在这种情况下,该计划看起来是可以接受的,因此在确认提示处键入 yes 以继续。 Terraform 预置网络可能需要几分钟时间。
Enter a value: yes
google_compute_network.vpc_network: Creating...
google_compute_network.vpc_network: Still creating... [10s elapsed]
google_compute_network.vpc_network: Still creating... [20s elapsed]
google_compute_network.vpc_network: Still creating... [30s elapsed]
google_compute_network.vpc_network: Creation complete after 38s [id=projects/testing-project/global/networks/terraform-network]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
您现在已经使用 Terraform 创建了基础设施! 访问 GCP 控制台以查看您预置的网络。 确保您查看的是配置中提供商中配置的相同区域和项目。
检查状态
当你应用你的配置时,Terraform 会将数据写入名为 terraform.tfstate 的文件中。Terraform 将其管理资源的 ID 和属性存储在此文件中,以便以后可以更新或销毁这些资源。
Terraform 状态文件是 Terraform 跟踪其管理的资源所用的唯一方式,并且通常包含敏感信息,因此您必须安全地存储您的状态文件,并且仅将其分发给需要管理您的基础设施的可信团队成员。在生产环境中,我们建议将您的状态远程存储到 HCP Terraform 或 Terraform Enterprise。Terraform 还支持其他几种远程后端,您可以使用它们来存储和管理您的状态。
使用 terraform show 检查当前状态。
$ terraform show
# google_compute_network.vpc_network:
resource "google_compute_network" "vpc_network" {
auto_create_subnetworks = true
delete_default_routes_on_create = false
description = null
enable_ula_internal_ipv6 = false
gateway_ipv4 = null
id = "projects/test-project/global/networks/terraform-network"
internal_ipv6_range = null
mtu = 0
name = "terraform-network"
network_firewall_policy_enforcement_order = "AFTER_CLASSIC_FIREWALL"
numeric_id = "1234567890123456789"
project = "test-project"
routing_mode = "REGIONAL"
self_link = "https://www.googleapis.com/compute/v1/projects/test-project/global/networks/terraform-network"
当 Terraform 创建此网络时,它还从 Google 提供程序收集了其元数据,并将其记录在状态文件中。稍后,您将修改您的配置以引用这些值来配置其他资源或输出。