如果您已经在 Terraform 之外创建了一些东西,并且想要让 Terraform 管理它或者想弄清楚如何使用 Terraform 最好地配置它,您可以使用 Terraform's import command 来获取任何支持它的资源。
因此,如果您通过 Google Cloud 控制台创建了一个名为 terraform-test 的 forwarding rule,并且想知道它如何映射到 Terraform 的 google_compute_forwarding_rule 资源,那么您可以运行 terraform import google_compute_forwarding_rule.default terraform-test 将其导入到 Terraform 的状态文件中。
如果您随后运行了一个计划,Terraform 会告诉您它的状态为 google_compute_forwarding_rule.default,但该资源未在您的代码中定义,因此它会想要删除它。
如果您添加了使计划生效所需的最小配置:
resource "google_compute_forwarding_rule" "default" {
name = "terraform-test"
}
然后再次运行计划,Terraform 将告诉您需要更改哪些内容才能使导入的转发规则看起来像您定义的配置。假设您已经完成了诸如在负载均衡器上设置描述之类的操作,Terraform 的计划将显示如下内容:
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
~ update in-place
-/+ destroy and then create replacement
Terraform will perform the following actions:
~ google_compute_forwarding_rule.default
description: "This is the description I added via the console" => ""
Plan: 5 to add, 5 to change, 3 to destroy.
这告诉您 Terraform 想要删除转发规则上的描述以使其与配置匹配。
如果您随后将资源定义更新为:
resource "google_compute_forwarding_rule" "default" {
name = "terraform-test"
description = "This is the description I added via the console"
}
然后 Terraform 的计划将显示一个空的更改集:
No changes. Infrastructure is up-to-date.
This means that Terraform did not detect any differences between your
configuration and real physical resources that exist. As a result, no
actions need to be performed.
此时,您已将 Terraform 代码与 Google Cloud 中资源的实际情况对齐,并且应该能够轻松地查看需要在 Terraform 端设置的内容,以使事情在 Google Cloud 控制台中按预期发生。