LoginSignup
2
0

はじめに

% terraform stateのサブコマンドの内、いくつかを業務で使ったので、これを機に% terraform stateのサブコマンドの使用例やシチュエーションについてまとめたいと思います。

本編

terraform state list

% terraform state listはstate内のリソース一覧を取得できます。

% terraform state list 
aws_instance.example
module.example
module.example.module.child
module.example.aws_instance.example
...

-state=statefileでstatefileを指定できたり、-id=IDでID指定もできます。
ID指定以外の絞り込みはgrepさえ使えば良さそうです。

terraform state mv

% terraform state mvはリソース名の変更やリソースのモジュールへの移動等ができます。また異なるステートファイルへの移動も可能です。

% terraform state mv aws_instance.old aws_instance.new

またterraformでは破壊的変更が加わるコマンドには-dry-runオプションがついていることが多く(全てついているかもしれません)、terraform state mvも例外ではありません。

以下のように実行するのをオススメします。

% terraform state mv -dry-run aws_instance.old aws_instance.new
% terraform state mv aws_instance.old aws_instance.new

mv は破壊的コマンドなので使用には十分注意し、適宜バックアップをとって実行して下さい

terraform state pull

terraform state pullはステートファイルをプルして標準出力するコマンドです。

% terraform state pull 

特定のファイルに保存するために、リダイレクトと一緒に使うと良いでしょう。

% terraform state pull > backup.tfstate

terraform state pullはステートを変更する作業を実施する際には、バックアップを取るという意味で実施した方が良いでしょう。

terraform state push

terraform state pushはローカルのステートファイルをリモートへプッシュするコマンドです。

% terraform state push backup.tfstate

-forceで強制pushも可能です。

terraform state replace-provider

terraform state replace-providerはステートファイル内のプロバイダー情報を置換するコマンドです。プロバイダーのアップグレードや変更時に役立ちます。

% terraform state replace-provider registry.terraform.io/-/aws registry.terraform.io/hashicorp/aws

terraform state rm

terraform state rmはステートファイルからリソースを削除するコマンドです。

% terraform state rm aws_instance.unwanted

先述した理由と同じ理由で-dry-runをつけて実行するのが良いでしょう。

% terraform state -dry-run rm aws_instance.unwanted
% terraform state rm aws_instance.unwanted

terraform state show

terraform state showはステートファイル内の特定のリソースの詳細情報を表示できます。
terraform state listで正確なリソース名を取得してから実施すると良いでしょう。

% terraform state show aws_instance.example

おわりに

いかがだったでしょうか。
知識の整理に役立てば幸いです。

おまけ

合わせて読みたい記事(個人的偏見に基づく)

2
0
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
2
0