Migration from terraform remote command to terraform backend system

Migration from terraform remote command to terraform backend system

先日terraform 0.9がリリースされました。

いくつかの面白そうな機能追加・変更がありますが、そのうちの一つとしてtfstateファイル(terraformで管理しているリソースの状態を記録しているjsonファイル)をクラウド管理するためのremoteコマンドが廃止され、代わりにbackendが実装されました。

backend以外の諸々の機能も気になりますが、今回はひとまずremoteコマンドからbackendへの移行をしてみます。

terraformのドキュメントには各メジャーバージョン毎のアップグレード手順が用意されており、0.9のアップグレード手順でremoteコマンドからbackendへの移行方法を見ることができます。

移行方法

今までは以下のようなコマンドでtfstateファイルのクラウド管理設定をしていました。

terraform remote config \
-backend=s3 \
-backend-config="bucket=my-terraform-state" \
-backend-config="key=infra/terraform.tfstate" \
-backend-config="region=us-east-1"

このremoteコマンドをもとに、以下の設定をmain.tfに追記します。これからはコマンドではなく、tfファイルでtfstateの管理方法を記述できるようになったのですね。

terraform {
  backend "s3" {
    bucket = "my-terraform-state"
    key    = "infra/terraform.tfstate"
    region = "us-east-1"
  }
}

追記したら、backendを初期化して有効にします。

terraform init

ちなみに、初期化しないでterraform planなどを実行した場合はちゃんと案内してくれます。

$ terraform plan
Backend reinitialization required. Please run "terraform init".
Reason: Initial configuration of the requested backend "s3"

The "backend" is the interface that Terraform uses to store state,
perform operations, etc. If this message is showing up, it means that the
Terraform configuration you're using is using a custom configuration for
the Terraform backend.

Changes to backend configurations require reinitialization. This allows
Terraform to setup the new configuration, copy existing state, etc. This is
only done during "terraform init". Please run that command now then try again.

If the change reason above is incorrect, please verify your configuration
hasn't changed and try again. At this point, no changes to your existing
configuration or state have been made.

Failed to load backend: Initialization required. Please see the error message above.

terraform planの結果です。よさそう。✨

$ terraform plan
Refreshing Terraform state in-memory prior to plan...
The refreshed state will be used to calculate this plan, but will not be
persisted to local or remote state storage.

...

No changes. Infrastructure is up-to-date.

This means that Terraform did not detect any differences between your
configuration and real physical resources that exist. As a result, Terraform
doesn't need to do anything.

以上でremoteコマンドからbackendへの移行ができました!

感想

tfstateの管理について、リポジトリをpullした時にしか実行しない割にはremoteコマンドは長くて覚え辛いものでした。

毎回remoteコマンドの実行手順を探すのが面倒でしたが今回追加されたbackendのお陰でだいぶ導入がシンプルになりましたね。

いままで

git clone git@github.com:ほげ/ふが.git

terraform remote config \
-backend=s3 \
-backend-config="bucket=my-terraform-state" \
-backend-config="key=infra/terraform.tfstate" \
-backend-config="region=us-east-1"

これから

git clone git@github.com:ほげ/ふが.git

terraform init

バケット名とか、固有名詞がなくなったのが良い。(๑•̀ㅂ•́)و✧

参考リンク