Terraformのinit系のコマンドを整理してみた
目次
はじめに
こんにちは、CloudBuildersのsugawaraです。
Terraform を使っていると、とりあえず最初にterraform initを実行する、という流れが半ば習慣になっている方も多いのではないでしょうか。自分も普段何気なくterraform initを実行しています。
ただ、場合によってはterraform init が失敗し、terraform init -reconfigureやterraform init -upgradeを実行するように求められることがあります。そのたびに「とりあえず言われた通りに実行する」すれば問題ないのですが、
- なぜそのオプションが必要なのか
- 実行すると何が変わるのか
- 裏でどのような処理が走っているのか
といった点をきちんと理解できていたかと言われると、正直あやふやな部分がありました。そこで今回は、terraform initとそのオプションについて、実際に手を動かしながら整理してみます。
先に結論
terraform init系オプションは、以下のように使う場面ごとに整理できます。
| コマンド | 使う場面 |
| terraform init | 初期化や通常の設定変更をする(下記の3つ以外) |
| terraform init -reconfigure | backend設定変更を反映するが、stateファイルは移動しない |
| terraform init -migrate-state | backend変更に伴い、stateファイルを移行したい |
| terraform init -upgrade | provider / module を更新したい |
迷った場合は、ざっくり以下で判断できます。
- backendを変更した → -reconfigureまたは-migrate-state
- provider / moduleを更新したい → -upgrade
- それ以外の通常の初期化 → terraform init
terraform initとは
initコマンド
Terraformを実行するための準備/初期化コマンドです。主に次のような処理を行います。
- backend(stateファイル保存先)の初期化
Terraformはplan / applyの結果をstateファイルに保存します。initコマンドでは、指定されたbackend(localやS3など)に接続し、このstateファイルを読み書きできるようにします。backendを指定していない場合、作業ディレクトリ内であるlocalが使われます。 - providerプラグインのダウンロード
AWSなどのサービスと通信するため、Terraformはproviderというプラグインを利用します。initコマンドでは、required_providersで指定したproviderをレジストリから取得し、.terraform/providers以下に配置します。ここで取得したバイナリが、plan / apply 実行時に使われます。 - moduleの取得
moduleブロックで参照している外部モジュール(Gitリポジトリや Terraform RegistryのURL など)をダウンロードし、.terraform/modules以下に展開します。ローカルパス(例:./modules/xxx)の場合はコピーはされず、参照先が解決されます。 - .terraformディレクトリの生成
上記のbackendのメタデータやproviderのバイナリ、moduleの展開先などは、すべて.terraformディレクトリに格納されます。このディレクトリが作成されることで、そのディレクトリ内でterraform plan / applyが実行可能になります。.terraform は通常.gitignore に含め、.terraform.lock.hcl だけをバージョン管理に含めます。
主に以下のタイミングで実行します。
- 初めてTerraformを実行するとき
- providerを追加・変更したとき
- moduleを追加・変更したとき
- .terraform ディレクトリを削除したとき
reconfigureオプション
terraform init -reconfigureは、backendの設定に変更があった場合に実行します。例えば、以下のようなケースが考えられます。
- backendの種類を変更したとき
例:stateファイルの配置場所をローカルからS3バケットに変更するとき - stateの保存先を変更したとき
例:S3 backendのまま、別のバケットにstateファイルを移すとき、もしくは同じバケット内でも、key(ファイルパス)を変更したとき - backendのパラメータを変更したとき
例:S3 backendのregionを変更するとき、もしくはencryptをtrueにしてstateファイルの暗号化を有効にしたとき
reconfigureオプションは、以前初期化したbackendの情報(キャッシュ)を無視し、再度backend設定を読み込むためのものです。Terraformは一度initを実行すると、使用しているbackendの情報を .terraform ディレクトリ内に保持します。そのため、backend 設定を書き換えた場合でも、Terraform は「以前の backend 設定」を前提に動作しようとします。
この状態でbackend設定に差分があると、エラーメッセージが表示されます。-reconfigureを付けてinitを実行すると、Terraformはこれまで保持していたbackend情報を破棄し、新しいbackend設定で再初期化を行います。
なお、stateファイルを自動で移動するわけではありません。実際にstateファイルを新しいbackendに移すときには、terraform init -migrate-stateを実行する必要があります。
migrate-stateオプション
terraform init -migrate-stateは、backendの設定を変更した際に既存のstateファイルを新しいbackendに移行するためのオプションです。
Terraformではbackendを変更しただけでは stateファイルは自動で移動されません。例えばbackendをlocalから S3 に変更した場合、local環境には既存のterraform.tfstateが残ったままとなり、新しいbackend(S3)にはstate が存在しない状態になります。
この状態で terraform planなどを実行すると、Terraformはbackendの不整合を検知し、再初期化を求めるエラーを表示します。
-migrate-stateを付けてinitを実行すると、Terraformは以下の処理を行います。
・現在のbackendから既存のstateを読み取る
・新しいbackendにstateファイルをコピーする
・以降、新しいbackendをstateの参照先として利用する
つまり、stateファイルの管理場所を安全に引き継ぐためのオプションと言えます。
upgradeオプション
upgradeは、providerやmoduleのバージョンを、設定されている制約の範囲内で新しいものに更新するためのオプションです。実行すると、バージョン制約の範囲内で新しい providerやmodule が取得されます。
「ロックファイルに載っている provider のバージョンが、現在の required_providers の制約を満たさない」ときに、init が失敗して「must use terraform init -upgrade」と表示されることがあります。その場合にこのオプションで解消できます。
ただし、provider のバージョン変更は plan の結果に影響することがあるため、チーム開発では慎重に扱う必要があります。
実際にやってみた
実際に検証環境として東京リージョンを使い、S3 バケットを1つ作成するだけの最小構成を用意します。reconfigureオプションの検証では、そのバケットstateファイルの保存先(S3 backend)としても使います。また、upgradeオプションについてはproviderのバージョン変更で対応します。
terraform init
まず、以下のようなterraform.tfとs3.tfを用意し、terraform initを実行します。
### terraform.tf
terraform {
backend "local" {} # 省略可
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-northeast-1"
}### s3.tf
resource "aws_s3_bucket" "main" {
bucket = "terraform-init-demo-20250219"
}実際に任意のディレクトリで初めてterraform initを実行したログとなります。
$ terraform init
Initializing the backend...
Successfully configured the backend "local"! Terraform will automatically
use this backend unless the backend configuration changes.
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 5.0"...
- Installing hashicorp/aws v5.100.0...
- Installed hashicorp/aws v5.100.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.terraform init実行後のディレクトリ構成を確認してみます。
$ tree -a -L 8
.
├── .terraform
│ ├── providers
│ │ └── registry.terraform.io
│ │ └── hashicorp
│ │ └── aws
│ │ └── 5.100.0
│ │ └── linux_amd64
│ │ ├── LICENSE.txt
│ │ └── terraform-provider-aws_v5.100.0_x5
│ └── terraform.tfstate
├── .terraform.lock.hcl
├── s3.tf
└── terraform.tf.terraformディレクトリが生成され、init時にダウンロードされたproviderプラグインやstateファイルが保存されているのがわかります。今回の例ではAWS providerが取得されており、.terraform/providers/… 以下にバイナリファイルが配置されています。Terraformはplan / applyの実行時にこのproviderを利用してAWSと通信します。
また、.terraform.lock.hclも生成されています。このファイルはproviderのバージョンを固定し、実行環境の再現性を担保するためのものです。
このままterraform plan/applyを実行してS3バケットを作成します。
$ terraform apply
Terraform used the selected providers to generate the following execution plan.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_s3_bucket.main will be created
+ resource "aws_s3_bucket" "main" {
+ acceleration_status = (known after apply)
+ acl = (known after apply)
+ arn = (known after apply)
+ bucket = "terraform-init-demo-20250219"
+ bucket_domain_name = (known after apply)
+ bucket_prefix = (known after apply)
+ bucket_regional_domain_name = (known after apply)
+ force_destroy = false
+ hosted_zone_id = (known after apply)
+ id = (known after apply)
+ object_lock_enabled = (known after apply)
+ policy = (known after apply)
+ region = (known after apply)
+ request_payer = (known after apply)
+ tags_all = (known after apply)
+ website_domain = (known after apply)
+ website_endpoint = (known after apply)
+ cors_rule (known after apply)
+ grant (known after apply)
+ lifecycle_rule (known after apply)
+ logging (known after apply)
+ object_lock_configuration (known after apply)
+ replication_configuration (known after apply)
+ server_side_encryption_configuration (known after apply)
+ versioning (known after apply)
+ website (known after apply)
}
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
aws_s3_bucket.main: Creating...
aws_s3_bucket.main: Creation complete after 1s [id=terraform-init-demo-20250219]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed.terraform init -migrate-state
先ほど作成したS3バケットを、今度はbackendの保存先として指定するように terraform.tfのbackendブロックをlocalからs3に書き換えます。
terraform {
backend "s3" {
bucket = "terraform-init-demo-20250219"
key = "terraform.tfstate"
region = "ap-northeast-1"
encrypt = false # 後ほどtrueにする
}
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-northeast-1"
}
この時点ではbackendの再初期化が必要な状態となるため、terraform planを実行すると以下のようなエラーが表示されます。
$ terraform plan
╷
│ Error: Backend initialization required: please run "terraform init"
│
│ Reason: Backend type changed from "local" to "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 set up the new configuration, copy existing state, etc. Please
│ run
│ "terraform init" with either the "-reconfigure" or "-migrate-state" flags to
│ use the current configuration.
│
│ 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.Reason: Backend type changed from “local” to “s3″となっているので、想定通りbackendの設定を変更したことによるエラーだとわかります。また、Please run “terraform init” with either the “-reconfigure” or “-migrate-state”とあるので、オプション付きのterraform initを実行する必要があります。
terraform init -migrate-stateを実行してstateファイルの管理もS3へ移動します。
$ terraform init -migrate-state
Initializing the backend...
Terraform detected that the backend type changed from "local" to "s3".
Do you want to copy existing state to the new backend?
Pre-existing state was found while migrating the previous "local" backend to the
newly configured "s3" backend. No existing state was found in the newly
configured "s3" backend. Do you want to copy this state to the new "s3"
backend? Enter "yes" to copy and "no" to start with an empty state.
Enter a value: yes
Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v5.100.0
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.これでS3バケットにstateファイルが格納されます。
terraform init -reconfigure
次に、reconfigureを実行する必要がある場面についてみていきます。backendに指定しているS3バケットの設定を変更します。具体的には、encryptをfalseからtrueに修正します。
terraform {
backend "s3" {
bucket = "terraform-init-demo-20250219"
key = "terraform.tfstate"
region = "ap-northeast-1"
encrypt = true # ここを修正する
}
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-northeast-1"
}
この状態でterraform planを実行すると、以下のようなエラーが表示されます。
$ terraform plan
╷
│ Error: Backend initialization required: please run "terraform init"
│
│ Reason: Backend configuration block has changed
│
│ 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 set up the new configuration, copy existing state, etc. Please
│ run
│ "terraform init" with either the "-reconfigure" or "-migrate-state" flags to
│ use the current configuration.
│
│ 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.ちなみにオプションなしのterraform initを実行しても、以下のエラーになります。
$ terraform init
Initializing the backend...
╷
│ 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".今回はstateファイルの移動はないため、-reconfigure付きでterraform initを実行します。すると、問題なくinitが完了します。
$ terraform init -reconfigure
Initializing the backend...
Successfully configured the backend "s3"! Terraform will automatically
use this backend unless the backend configuration changes.
Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
- Using previously-installed hashicorp/aws v5.100.0
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.terraform init -upgrade
最後に、terraform init -upgradeを実行する必要がある場面についてです。Terraformはデフォルトでは .terraform.lock.hcl を参照するため、required_providersのversion制約を変更してもproviderは自動更新されません。
今回は.terraform.lock.hclのawsのバージョンが5.100.0 で固定されてますが、以下のようにrequired_providersをもっと新しい範囲に変更して、lockが合わない状態を作ります。
terraform {
backend "s3" {
bucket = "terraform-init-demo-20250219"
key = "terraform.tfstate"
region = "ap-northeast-1"
encrypt = true
}
required_providers {
aws = {
source = "hashicorp/aws"
# version = "~> 5.0"
version = "~> 6.0" # こちらに変更する
}
}
}
provider "aws" {
region = "ap-northeast-1"
}この状態でterraform initを実行します。
$ terraform init
Initializing the backend...
Initializing provider plugins...
- Reusing previous version of hashicorp/aws from the dependency lock file
╷
│ Error: Failed to query available provider packages
│
│ Could not retrieve the list of available versions for provider hashicorp/aws:
│ locked provider registry.terraform.io/hashicorp/aws 5.100.0 does not match
│ configured version constraint ~> 6.0; must use terraform init -upgrade to
│ allow selection of new versions
│
│ To see which modules are currently depending on hashicorp/aws and what
│ versions are specified, run the following command:
│ terraform providers.terraform.lock.hclはproviderのバージョンを固定するファイルで、Terraformはinitの際にrequired_providersよりもlockファイルを優先して参照します。そのため、lockファイル側が5.100.0のままだと、新たに追加したバージョン制約~> 6.0を満たさず、initが失敗して「must use terraform init -upgrade」のメッセージが表示されます。そこで-upgradeで実行すると、問題なく初期化されます。
$ terraform init -upgrade
Initializing the backend...
Initializing provider plugins...
- Finding hashicorp/aws versions matching "~> 6.0"...
- Installing hashicorp/aws v6.33.0...
- Installed hashicorp/aws v6.33.0 (signed by HashiCorp)
Terraform has made some changes to the provider dependency selections recorded
in the .terraform.lock.hcl file. Review those changes and commit them to your
version control system if they represent changes you intended to make.
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.ここまでproviderの例でupgradeオプションを確認しましたが、このオプションはmoduleを更新したい場合にも使用します。例えば、次のようなケースです。
- moduleのバージョン制約を変更したとき
- module側でバグ修正や機能追加があり、新しいバージョンを利用したいとき
- チームメンバーがmoduleバージョンを更新しており、自分の環境も揃えたいとき
Terraform は一度取得した module を .terraform/modules 配下にキャッシュするため、単にバージョンを書き換えただけではmoduleは更新されません。このような場合に terraform init -upgrade を実行することで、バージョン制約を再評価し、新しいmoduleを取得できます。
※ moduleの更新は構成や挙動に影響する可能性があるため、provider と同様に慎重な確認が必要です。
おわりに
今回はterraform initコマンドについて改めて整理してみました。なんとなく実行していたterraform initですが、整理したことによって、エラーメッセージが出たときに何を見ればいいかが明確になり、次に-reconfigureや-migrate-stateを求められても迷わず対応できそうです。同じように「とりあえず言われた通りに実行していた」という方の参考になれば幸いです。