使用Terraform的count和for_each方法定义的资源如何从Terraform管理中移除

首先

大家好,本次介绍如何使用terraform state rm命令将现有资源从Terraform管理中移除的小技巧。

我想介绍一种解决方法,当在使用Terraform进行实施时,例如在将相同资源部署到多个区域或可用区时,许多人可能会使用count或for_each来处理这些用例。但是,如果您直接使用terraform state rm命令来删除使用count或for_each定义的资源,那么会遇到以下错误。

$ terraform state rm google_compute_subnetwork.private["tokyo"]
Acquiring state lock. This may take a few moments...
╷
│ Error: Index value required
│ 
│   on  line 1:
│   (source code not available)
│ 
│ Index brackets must contain either a literal number or a literal string.
╵

Releasing state lock. This may take a few moments...

使用count或for_each定义资源并将其解除管理的方法

总结来说,“将使用单引号定义的资源名称括起来”是一个解决方案。

如输出示例所示,当我们用单引号将Terraform资源名称括起来时,预期的结果是现有资源将不再由Terraform管理。真是喜大普奔。

$ terraform state rm 'google_compute_subnetwork.private["tokyo"]'
Acquiring state lock. This may take a few moments...
Removed google_compute_subnetwork.private["tokyo"]
Successfully removed 1 resource instance(s).
Releasing state lock. This may take a few moments...

结束

这个信息可能有点晚,你觉得如何?有人可能会想:“嗯,不会有这种用例吧?”但也许有时候不小心会将现有环境错误地导入到其他资源上。希望这对你有所帮助。

以上是关于使用 terraform state rm 命令从 Terraform 管理中移除资源的小技巧的介绍。


    • Terraform は、HashiCorp, Inc. の米国およびその他の国における商標または登録商標です。

 

    その他、記載されている会社名および商品・製品・サービス名は、各社の商標または登録商標です。
bannerAds