工作時有時會需要搬移 terraform 資源, 紀錄下使用用法作為未來參考
使用 terraform state mv 搬移
可以用在 resource 及 module 上1
2
3terraform state mv aws_instance.one aws_instance.another # resource 搬移(重命名)
terraform state mv module.one module.another # module 搬移(重命名)
terraform state mv aws_instance.one module.another.instance # resource 搬移至 module 內使用 terraform moved 語法搬移
可以用在 resource 及 module 上1
2
3
4moved {
from = aws_instance.one
to = aws_instance.another
}Module 的搬移方式
1
2
3
4moved {
from = module.one
to = module.another
}手動進行 terraform state 操作
可以用在 resource, 也可用於不同資料夾下搬移 resource
可以用於舊有資源時的 IaC1
2
3terraform state rm aws_instance.one # 從 state 移除舊 resource
terraform import aws_instance.another i-a1234567 # 匯入機器到指定 resource
terraform import module.one.another i-a1234567 # 匯入機器到指定 module 的 resource