重构后如何保留 terraform 资源以使用 for_each?

Tal*_*ois 5 foreach terraform

目前我正在对我们的基础设施进行小型重构。我的项目的当前版本类似于以下内容: 我正在尝试使用 for_each 来重用变量。

resource "google_cloud_scheduler_job" "job" {
  name             = "Create_All_Dossier_Summary"
  description      = "desc1"
  schedule         = "0 19 * * 1"
  time_zone        = "America/Sao_Paulo"
  attempt_deadline = "320s"

  retry_config {
    retry_count = 1
  }

  http_target {
    http_method = "POST"
    uri         = "<some-url>"
  }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试将其升级为如下所示:

variable "description" {
  default = ["desc1", "desc 2"]
}

resource "google_cloud_scheduler_job" "job" {
  for_each = toset(var.description)
  name             = "Create_All_Dossier_Summary"
  description      = each.value
  schedule         = "0 19 * * 1"
  time_zone        = "America/Sao_Paulo"
  attempt_deadline = "320s"

  retry_config {
    retry_count = 1
  }

  http_target {
    http_method = "POST"
    uri         = "<some-url>"
  }
}
Run Code Online (Sandbox Code Playgroud)

所以,配置没问题,但是运行后terraform plan,terraform 正在破坏我的旧配置,这不是我希望 terraform 做的事情,我的目标是它只是创建第二个,因为第一个已经存在并且配置是一样的。

有没有办法告诉 terraform 在进行此重构后不要重新创建第一个资源?

Plan: 2 to add, 0 to change, 1 to destroy.
# google_cloud_scheduler_job.job will be destroyed
# google_cloud_scheduler_job.job["desc 2"] will be created
# google_cloud_scheduler_job.job["desc1"] will be created
Run Code Online (Sandbox Code Playgroud)

顺便说一句:我正在尝试使用对象列表,我在这里使用了字符串列表,因为它更容易演示。

Mat*_*ard 10

当 Terraform 配置中资源的命名空间/地址发生更改时,您必须使用子命令在状态中重命名其相应的 id state mv

terraform state mv google_cloud_scheduler_job.job 'google_cloud_scheduler_job.job["desc 2"]'
Run Code Online (Sandbox Code Playgroud)

请注意,由于在"语法中使用了,第二个资源地址必须完全转换为文字字符串,以便 shell 将其正确解释为参数。