terraform自体やProviderのバージョンをRenovateなどを使って自動でアップデートする際に、-detailed-exitcode
が便利だったので紹介します。
自動アップデートにする際の不安点
terraformのコードを管理しているリポジトリでは、
- CIでterraform planを実行する
- CIがパスしたらPull Requestをmergeする
- mergeされたらterraform applyする
のような設定をしていることがよくあると思います。
依存関係の自動アップデートをするとなると、planの結果を見ずにmergeすることになるので、アップデートによって生じた意図しない差分がapplyされてしまう可能性があります。
解決案
terraform planに-detailed-exitcode
というオプションがあるので、これを使うことで差分がある場合はCIをfailさせることができます。
-detailed-exitcode
- Returns a detailed exit code when the command exits. When provided, this argument changes the exit codes and their meanings to provide more granular information about what the resulting plan contains:
- 0 = Succeeded with empty diff (no changes)
- 1 = Error
- 2 = Succeeded with non-empty diff (changes present)
ドキュメントにあるように、このオプションをつけることで、
- 差分がない場合: exit code 0
- エラーの場合: exit code 1
- 差分がある場合: exit code 2
を返してくれます。
そのため、-detailed-exitcode
を使い以下のような処理にしてあげることで、差分がある場合は自動アップデートを止めることができます。
- 依存関係のアップデートのPull Request(例: Renovate, dependabot)
-
-detailed-exitcode
オプションを使い、差分がある場合はCIをfailさせる
-
- それ以外のPull Request
- 通常通り
steps:
# 略
- run: docker compose run --rm terraform plan -no-color
if: ${{ github.actor != 'renovate[bot]' }}
- run: docker compose run --rm terraform plan -no-color -detailed-exitcode
if: ${{ github.actor == 'renovate[bot]' }}
さいごに
これで依存関係の自動アップデートができ、楽になりました。
似たようなことを思った人の役に立てれば幸いです。