🐕

[CDK For Terraform]でバックエンドの設定変更したときのエラー対応

2024/04/23に公開

発生事象

cdktf で対象バックエンドの設定を誤ってしまったため
別の名称に変更してdiffを実行したところ以下エラーが発生しました。

                  │ Error: Backend configuration changed
                  │
                  │ A change in the backend configuration has been detected, which may require
                  │ migrating existing state.
                  │
                  │ If you wish to attempt automatic migration of the state, use "terraform init
                  │ -migrate-state".
                  │ If you wish to store the current configuration with no changes to the state,
                  │ use "terraform init -reconfigure".

対応内容

メッセージにあるとおりにreconfigureかmigrate-stateを実行すればOK [1]

ただ、terraform経由で実行してあげる必要があります。
cdktf.out/stacks/ 配下にStack名のディレクトリが存在しているはずなので
対象ディレクトリに移動して実行するかchdirのオプションを指定して実行してあげる必要があります。

make _TF=true "init -reconfigure"
[INFO]: AWS SSO aws-sample Authentication successful!
[CMD]:  aws-vault exec aws-sample -- terraform -chdir=cdktf.out/stacks/cloudwatch_alarm init -reconfigure

Initializing the backend...

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

Initializing provider plugins...
- Finding hashicorp/aws versions matching ">= 5.0.0, 5.45.0"...
- Installing hashicorp/aws v5.45.0...
- Installed hashicorp/aws v5.45.0 (signed by HashiCorp)

Terraform has created a lock file .terraform.lock.hcl to record the provider
selections it made above. Include this file in your version control repository
so that Terraform can guarantee to make the same selections by default when
you run "terraform init" in the future.

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.
  • diff確認
make diff
[INFO]: AWS SSO aws-sample Authentication successful!
[CMD]:  aws-vault exec aws-sample -- cdktf diff
(node:57712) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
cloudwatch_alarm  Initializing the backend...
cloudwatch_alarm  Initializing modules...
cloudwatch_alarm  Initializing provider plugins...
cloudwatch_alarm  - Reusing previous version of hashicorp/aws from the dependency lock file
cloudwatch_alarm  - Using previously-installed hashicorp/aws v5.45.0
cloudwatch_alarm  Terraform has been successfully initialized!

OK

脚注
  1. 独自のMakefile で実行するようにしているため出力内容が異なる可能性があります。 ↩︎

Goals Tech Blog

Discussion