はじめに
% 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
おわりに
いかがだったでしょうか。
知識の整理に役立てば幸いです。
おまけ
合わせて読みたい記事(個人的偏見に基づく)