kasei_sanのブログ

かせいさんのIT系のおぼえがきです。胡乱の方はnoteとtwitterへ

Terraform Cloud にある state を mv する方法

流れ

  • state ファイルをローカルに持ってくる
  • backend をローカルに変更
  • terraform state mv を実行
  • terraform state push を実行
  • backend を Terraform Cloud に戻す(この時に、state を overwrite する)

state ファイルをローカルに持ってくる

terraform state pull > tmp.tfstate    

backend をローカルに変更

cat << EOF > override.tf
terraform {
  backend "local" {
  }
}
EOF
$ terraform init -reconfigure
Initializing modules...

Initializing the backend...

Successfully configured the backend "local"! Terraform will automatically
use this backend unless the backend configuration changes.

terraform state mv を実行

terraform state mv -state=tmp.tfstate ...

変更されたことを確認

terraform state list -state=tmp.tfstate | grep ...

terraform state push を実行

terraform state push tmp.tfstate

backend を Terraform Cloud に戻す(この時に、state を overwrite する)

rm override.tf
$ terraform init -reconfigure
Initializing modules...

Initializing the backend...
Acquiring state lock. This may take a few moments...
Do you want to copy existing state to the new backend?
  Pre-existing state was found while migrating the previous "local" backend to the
  newly configured "remote" backend. An existing non-empty state already exists in
  the new backend. The two states have been saved to temporary files that will be
  removed after responding to this query.

  Previous (type "local"): /var/folders/12/02rv601d4kv6gmbxrzg4hzzh0000gn/T/terraform229570062/1-local.tfstate
  New      (type "remote"): /var/folders/12/02rv601d4kv6gmbxrzg4hzzh0000gn/T/terraform229570062/2-remote.tfstate

  Do you want to overwrite the state in the new backend with the previous state?
  Enter "yes" to copy and "no" to start with the existing state in the newly
  configured "remote" backend.

既存の状態を新しいバックエンドにコピーするか? と聞かれるので「yes」と回答する

リモートのstateでも、変更が維持されていることを確認

terraform state list | grep ...