てくなべ (tekunabe)

ansible / network automation / 学習メモ

[Terraform] plan 時に差分の有無を終了コードで判断できる -detailed-exitcode オプション

はじめに

Ansible から Terraform を呼べる cloud.terraform.terraform モジュールのコードを眺めているときに、terraform plan-detailed-exitcode オプションの存在を知りました。

どんなオプションだろうと、公式ドキュメントを見てみると、以下のように終了コードを詳細化できるオプションでした。

  • 0 = 差分なしで plan 成功
  • 1 = エラー
  • 2 = 差分ありで plan 成功

実際にためしてみます。

  • 環境
    • Terraform v1.8.2

-detailed-exitcode オプション あり

差分ありのとき: 終了コード 2

% terraform plan -detailed-exitcode

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

...(略)...

Plan: 1 to add, 0 to change, 0 to destroy.

────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
% echo $?
2

差分なしのとき: 終了コード 0

% terraform plan -detailed-exitcode
...(略)...

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
% echo $?
0

参考: デフォルト(-detailed-exitcode オプション なし)

比較のために、デフォルト(-detailed-exitcode オプション なし)のときの場合も載せておきます。

差分ありのとき: 終了コード 0 (差分なしと同じ)

% terraform plan

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the following symbols:
  + create

...(略)...

Plan: 1 to add, 0 to change, 0 to destroy.

────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Note: You didn't use the -out option to save this plan, so Terraform can't guarantee to take exactly these actions if you run "terraform apply" now.
% echo $?
0

差分なしのとき: 終了コード 0 (差分ありと同じ)

% terraform plan
...(略)...

No changes. Your infrastructure matches the configuration.

Terraform has compared your real infrastructure against your configuration and found no differences, so no changes are needed.
% echo $?
0

おわりに

差分があるときないときで処理を分けたいときに便利そうだなと思いました。