2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Terraformの依存関係の自動アップデートには「-detailed-exitcode」が便利

Posted at

terraform自体やProviderのバージョンをRenovateなどを使って自動でアップデートする際に、-detailed-exitcodeが便利だったので紹介します。

自動アップデートにする際の不安点

terraformのコードを管理しているリポジトリでは、

  1. CIでterraform planを実行する
  2. CIがパスしたらPull Requestをmergeする
  3. 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
    • 通常通り
GitHub Actionsの例
    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]' }}

さいごに

これで依存関係の自動アップデートができ、楽になりました。
似たようなことを思った人の役に立てれば幸いです。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?