重构后如何保留 Terraform 资源以使用 for_each?
How to keep terraform resource after refactoring to use for_each?
目前我正在对我们的基础架构进行小规模重构。我的项目的当前版本类似于以下内容:我正在尝试使用 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>"
}
}
我正在尝试将其升级到如下所示:
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>"
}
}
所以,配置没问题,但是在 运行 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
顺便说一句:我正在尝试使用一个对象列表,我在这里使用了一个字符串列表,因为它更容易演示。
当资源的namespace/address在Terraform config中改变时,那么你必须用state mv
子命令重命名它在state中对应的id:
terraform state mv google_cloud_scheduler_job.job 'google_cloud_scheduler_job.job["desc 2"]'
请注意,由于在语法中使用了 "
,因此 shell 必须将第二个资源地址完全转换为文字字符串才能将其正确解释为参数。
目前我正在对我们的基础架构进行小规模重构。我的项目的当前版本类似于以下内容:我正在尝试使用 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>"
}
}
我正在尝试将其升级到如下所示:
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>"
}
}
所以,配置没问题,但是在 运行 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
顺便说一句:我正在尝试使用一个对象列表,我在这里使用了一个字符串列表,因为它更容易演示。
当资源的namespace/address在Terraform config中改变时,那么你必须用state mv
子命令重命名它在state中对应的id:
terraform state mv google_cloud_scheduler_job.job 'google_cloud_scheduler_job.job["desc 2"]'
请注意,由于在语法中使用了 "
,因此 shell 必须将第二个资源地址完全转换为文字字符串才能将其正确解释为参数。