TerraformのStateをS3からTerraform Cloudに移行する

TerraformのStateをチームで管理するときに、複数の環境からplanやapplyを実行できるようにするためにS3などのクラウドのストレージをバックエンドにすることが多いと思います。

通常のストレージをバックエンドにしていると、複数の環境から同時にapplyが実行されたときに壊れてしまう可能性があります。CIで実行するようにしていても、設定が適切ではなく平行に動いてしまうような場合などに壊れる可能性があります。

Terraform CloudにはStateのロック機能がありこのような事故から開放されるため、Stateの管理をS3からTerraform Cloudに移行したいと思います。

環境

  • Terraform v0.12.24
  • 元のBackendはS3
  • Terraform Cloudのアカウントは作成済み

手順

Terraform Cloudへのアクセス設定

まずはterraformコマンドがTerraform Cloudにアクセスできるようにします。

terraformのバージョンが0.12.21以降の場合は terraform login コマンドを実行して、ブラウザに表示されたトークンを入力すれば完了です。

www.terraform.io

loginコマンドが使えない場合は $HOME.terraformrc というファイルを作成し、以下のようにトークンを設定します。

credentials "app.terraform.io" {
  token = "xxxxxx.atlasv1.zzzzzzzzzzzzz"
}

また、TF_CLI_CONFIG_FILE という環境変数を設定すれば、任意の場所に任意の名前で設定ファイルを作成できます。

www.terraform.io

www.terraform.io

backendの書き換え

S3の設定が書かれていたbackendをTerraform Cloudのものに書き換えます。

  backend "s3" {
    ...
  }

これを削除して以下のように書き換えます。

  backend "remote" {
    hostname     = "app.terraform.io"
    organization = "your_organization_name"

    workspaces {
      name = "your_workspaces_name"
    }
  }

移行

準備が整ったので移行させていきます。

terraform init を実行するだけで移行ができます。
実行すると以下のように聞かれるので yes を入力します。

$ terraform init

Initializing the backend...
Backend configuration changed!

Terraform has detected that the configuration specified for the backend
has changed. Terraform will now check for existing state in the backends.


Terraform detected that the backend type changed from "s3" to "remote".
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 "s3" backend to the
  newly configured "remote" backend. No existing state was found in the newly
  configured "remote" backend. Do you want to copy this state to the new "remote"
  backend? Enter "yes" to copy and "no" to start with an empty state.

  Enter a value:

yes を入力し、問題なく成功すれば以下のように表示されます。

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

Initializing provider plugins...

Terraform has been successfully initialized!

You may now begin working with Terraform. Try running "terraform plan" to see
any changes that are required for your infrastructure. All Terraform commands
should now work.

If you ever set or change modules or backend configuration for Terraform,
rerun this command to reinitialize your working directory. If you forget, other
commands will detect it and remind you to do so if necessary.

これで移行が完了です。

参考