LoginSignup
5
3

More than 1 year has passed since last update.

【Terraform】Backend の切り替え方法とは?

Last updated at Posted at 2022-11-02

はじめに

業務で terraform import を実施する機会があり、検証のために Backend を S3 → local に切り替える機会があったので記事としてアウトプットしたいと思います。

S3 → local に変更する場合

1.backend を一時的に local に切り替える。

backend.tfterraform.tf 等、backend先が記述されているファイルを以下のように修正する。

terraform {
#  backend "s3" {
#    bucket = "mybucket"
#    key    = "path/to/my/key"
#    region = "ap-northeast-1"
#  }
   backend "local" {
     path   = "terraform.tfstate"
   }
}

2.terraform init -migrate-state を実行する。

以下コマンドを実行すると、S3 に保存されている backend(stateファイル) が local にコピーされる。
(-migrate-state は、 backend をコピーするためのオプション)

コマンド
terraform init -migrate-state

s3 → local に backend をコピーするかどうか確認されるので、 yes と入力する。

実行例
% terraform init -migrate-state
Initializing modules...

Initializing the backend...
Terraform detected that the backend type changed from "s3" to "local".

Do you want to copy existing state to the new backend?
  Pre-existing state was found while migrating the previous "s3" backend to the
  newly configured "local" backend. No existing state was found in the newly
  configured "local" backend. Do you want to copy this state to the new "local"
  backend? Enter "yes" to copy and "no" to start with an empty state.

  Enter a value: yes ← ここで yes と入力

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

〜〜〜長いので省略〜〜〜
%

local → S3 に戻す場合

1.backend を local → S3 に戻す。

backend.tfterraform.tf 等、backendが記述されているファイルを修正する。
local の記述を削除する。

terraform {
  backend "s3" {
    bucket = "mybucket"
    key    = "path/to/my/key"
    region = "ap-northeast-1"
  }
}

2.terraform init -reconfigure を実行する。

以下コマンドを実行し、backend を local → S3 に戻す。
(local の設定を S3 にコピーしないようにするために -reconfigure を使用する。)

コマンド
terraform init -reconfigure
実行例
% terraform init -reconfigure
Initializing modules...

Initializing the backend...

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

〜〜〜長いので省略〜〜〜
%

3.ローカルに保存されている terraform.tfstate 等のファイルを削除する。

terraform init -migrate-state 実行後に作成されたファイルになります。

ファイルの例
terraform.tfstate
terraform.tfstate.1666956416.backup
terraform.tfstate.backup

参考

5
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3