LoginSignup
3
1

More than 5 years have passed since last update.

既存のtfディレクトリをWorkspaces管理に移行する

Last updated at Posted at 2017-09-11

TL;DR

Terraform 0.10から、Workspacesという機能が追加されました。
https://www.terraform.io/docs/state/workspaces.html

0.9で追加された State: Environmentsが名称変更されたものです。

1つのディレクトリで、任意の複数の環境(e.g dev, stg, prod)を切り替えられるようにするものです。

下記を適用する下準備として、既存のtfディレクトリをWorkspaces管理に移行する際にはまったことのメモです。
Terraform Best Practices in 2017

既存のtfディレクトリをWorkspaces管理に移行する。

1. 既存のstateファイルからworkspaceを作る(とincompatible state lineageエラーが出る)

terraform workspace new -state=./terraform.tfstate [workspace名]
$ terraform workspace new -state=terraform.tfstate example
Created and switched to workspace "example"!

You're now on a new, empty workspace. Workspaces isolate their state,
so if you run "terraform plan" Terraform will not see any existing state
for this configuration.
incompatible state lineage; given 3d2aa9e3-198b-400c-a1aa-0a8e15ac44b4 but want 768adb25-938d-45cc-9195-fae815470dd3
$

詳細は確認していませんが、newした時点で作成されるtfstateファイルにはlineageが発行されているのですが、
-stateで指定した既存のtfstateで上書きする際に、既存のtfstateファイルでまるごと上書きしてしまい、lineageが一致しなくなることが問題のようです。

2. stateファイルをs3などのremoteで管理している場合は、stateファイルをremoteとsyncした上で手動マージする

remoteの最新stateファイルをpullし、workspace:example用のtfstateファイルを置き換える

terraform state pull > ./terraform.tfstate.d/example/terraform.tfstate

"modules"を既存のもので差し替え、pushする

terraform state push ./terraform.tfstate.d/example/terraform.tfstate

3. 既存のtfstateファイルを引き継げているかをplanの結果を見て確認する

terraform plan -var-file=./tfvars/example.tfvars -out=path_to_plan.plan

問題なく移行できていれば、planの実行結果に新規作成されるリソースは存在しないはず。

3
1
0

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
3
1