🚀

GitHub Actionsでterraform planの実行結果を整形してPRにコメントする方法

に公開

はじめに

TerraformのCI/CDを導入しているプロジェクトにおいて、自動デプロイにより意図せずリソースが変更・破壊されてしまうことは重大なリスクです。このような事態を防止するためには、terraform planの実行結果をPR上で事前にレビューすることが有効です。

本記事では、GitHub Actionsでterraform planの実行結果を整形してPRにコメントする方法を紹介します。

背景・課題

既存の課題

当初、tfcmtというツールを使用してterraform planの実行結果をPRにコメントしていました。しかし、以下の課題がありました:

  1. 複数サービス/アプリの結果をまとめられない: 複数のterraformで管理しているマイクロサービスやフロントエンドアプリがある場合、それぞれのterraform planの実行結果を1つのコメントにまとめられない
  2. コメントが重複: プッシュのたびに新しいコメントが作成され、PRが見づらくなる

目指す形

複数のterraformで管理しているサービスやアプリのterraform planの実行結果を、1つのPRコメントにまとめて表示したいと考えました。以下のような形式で、簡潔に表示します:

  • 各サービス/アプリごとにセクションを分ける
  • サマリー行(変更の概要)を表示
  • 詳細な変更内容は折りたたみで表示・非表示できる
  • 既存のコメントを更新する(新規作成しない)

実装内容

本実装は、以下の2つの処理で構成されます:

  1. terraform plan実行結果の整形: 複数のterraformで管理している各サービス/アプリごとにterraform planを実行し、結果を整形して1つのMarkdownファイルにまとめる
  2. PRコメントの更新: GitHub Actionsで整形したMarkdownファイルを読み込み、PRにコメントとして投稿する(既存コメントがあれば更新、なければ新規作成)

以下、それぞれの実装方法を説明します。

前提条件

本実装では、以下の前提条件が必要です:

  • GitHub Actionsのワークフローがpull_requestイベントでトリガーされる設定
  • AWS認証(OIDC)の設定が完了している
  • Terraform 0.15以降を使用している(terraform planの出力形式が0.15で変更されたため)

terraform plan実行結果の整形ロジック

terraform planの実行結果を整形するロジックを実装します。主な処理は以下の通りです:

  1. 各サービス/アプリごとにterraform planを実行
  2. 実行結果を一時ファイルに保存
  3. 実行結果ファイルからサマリー行を抽出し、詳細な変更内容も取得
  4. Markdown形式で整形してコメントファイルに追記

本記事ではbashスクリプトでの実装例を示します。

複数サービス/アプリのループ処理

複数のサービスやアプリに対してterraform planを実行し、結果を1つのMarkdownファイルにまとめます。

以下のスクリプトをscripts/format-plan-results.shとして保存します(後述のformat_plan_result関数も含まれます):

#!/bin/bash
# scripts/format-plan-results.sh

COMMENT_FILE="/tmp/comment.md"
SERVICES=("service1" "service2" "service3")  # 対象のサービス/アプリのリスト

# コメントファイルの初期化
echo "# Terraform Plan Results" > "${COMMENT_FILE}"
echo "" >> "${COMMENT_FILE}"

# 各サービスに対してplanを実行し、結果を整形
for service in "${SERVICES[@]}"; do
  plan_file="/tmp/plan-${service}.txt"
  
  # 各サービスのディレクトリでterraform planを実行
  (cd "services/${service}" && terraform plan -out=plan.tfplan > "${plan_file}" 2>&1)
  
  # 結果を整形してコメントファイルに追加
  format_plan_result "📦" "${service}" "${plan_file}" "${COMMENT_FILE}"
done

# HTMLコメントを追加(後述のGitHub Actionsで識別に使用)
echo "<!-- terraform-plan-comment -->" >> "${COMMENT_FILE}"

ポイント:

  • (cd ... && terraform plan ...)のようにサブシェル()で実行することで、ディレクトリ変更が他のループへ影響しないようにする
  • 各サービスでの実行結果を一時ファイルに保存し、後で整形処理を行う

サマリー行の抽出および詳細な変更内容の取得

format_plan_result関数で、terraform planの実行結果からサマリー行を抽出し、詳細な変更内容も取得します。

以下の関数をscripts/format-plan-results.shに含めます:

# plan結果を整形する関数を定義
format_plan_result() {
  # 引数の受け取り($1, $2, $3, $4は引数の順番を表す)
  local emoji=$1        # 第1引数: 絵文字(例: "📦")
  local service_name=$2 # 第2引数: サービス名(例: "service1")
  local plan_file=$3    # 第3引数: terraform planの実行結果ファイルのパス
  local output_file=$4  # 第4引数: 出力先のMarkdownファイルのパス

  echo "### ${emoji} ${service_name}" >> "${output_file}"
  echo "" >> "${output_file}"

  if grep -q "Plan:" "${plan_file}"; then
    PLAN_SUMMARY=$(grep "Plan:" "${plan_file}" | tail -1 | sed 's/\x1b\[[0-9;]*m//g')
  else
    PLAN_SUMMARY="No changes. Your infrastructure matches the configuration."
  fi

  echo "${PLAN_SUMMARY}" >> "${output_file}"
  echo "" >> "${output_file}"
  echo "<details>" >> "${output_file}"
  echo "<summary>📋 変更されるリソース (Click to expand)</summary>" >> "${output_file}"
  echo "" >> "${output_file}"
  sed -n '/Terraform will perform the following actions:/,/^Plan:/p' "${plan_file}" | \
    sed 's/\x1b\[[0-9;]*m//g' | head -n -1 >> "${output_file}"
  echo "" >> "${output_file}"
  echo "</details>" >> "${output_file}"
  echo "" >> "${output_file}"
}

ポイント:

  • grep "Plan:"でサマリー行を検索
  • sed 's/\x1b\[[0-9;]*m//g'でANSIエスケープコードを除去
  • サマリー行が見つからない場合は「No changes」を表示
  • <details>タグで詳細を折りたたみ
  • sed -n '/Terraform will perform the following actions:/,/^Plan:/p'で詳細な変更内容を取得

PRコメントの更新機能

GitHub Actionsで、既存のPRコメントを更新する機能を実装します。

既存コメントの識別

前述の実装例において、コメントファイルの末尾にHTMLコメント(<!-- terraform-plan-comment -->)を追加しました。このHTMLコメントは、GitHub Actionsで既存コメントを検索する際のマーカーとして使用します。

注意: コメントファイルのパスは、後述のGitHub Actionsで読み込むファイルパスと一致させる必要があります。

GitHub Actionsでのコメント更新

actions/github-scriptを使用して、既存のコメントを検索し、更新します。

ワークフローの設定例:

name: Terraform Plan Comment

on:
  pull_request:
    types: [opened, synchronize, reopened]
    branches:
      - main

jobs:
  terraform-plan:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      
      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3
      
      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: ${{ secrets.AWS_ROLE_ARN }}
          aws-region: ap-northeast-1
      
      - name: Run terraform plan and format
        run: |
          chmod +x scripts/format-plan-results.sh
          ./scripts/format-plan-results.sh  # 前述のスクリプトを実行
      
      - name: Comment PR
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const comment = fs.readFileSync('/tmp/comment.md', 'utf8');
            const { data: comments } = await github.rest.issues.listComments({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.issue.number,
            });
            const botComment = comments.find(comment =>
              comment.user.type === 'Bot' &&
              comment.body.includes('<!-- terraform-plan-comment -->')
            );
            if (botComment) {
              // 既存コメントを更新
              await github.rest.issues.updateComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                comment_id: botComment.id,
                body: comment
              });
              console.log('Updated existing plan comment');
            } else {
              // 新規コメントを作成
              await github.rest.issues.createComment({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: context.issue.number,
                body: comment
              });
              console.log('Created new plan comment');
            }

ポイント:

  • listCommentsでPRの全コメントを取得
  • HTMLコメント<!-- terraform-plan-comment -->を含むBotコメントを検索
  • 既存コメントがあればupdateCommentで更新、なければcreateCommentで新規作成
  • context.issue.numberはpull_requestイベントでも正常に動作する(PRはGitHub上でIssueとして扱われるため)
  • ファイルパス(/tmp/comment.md)は、スクリプトで生成したファイルパスと一致させる必要がある

PRコメントの表示例

上記の実装により、実際のPRコメントでは以下のような形式で表示されます。

実行結果の概要

terraform plan実行結果の概要

詳細な変更内容

terraform plan実行結果の詳細な変更内容

まとめ

本記事では、GitHub Actionsでterraform planの実行結果を整形してPRにコメントする方法を紹介しました。

主なポイント:

  • スクリプトでterraform planの実行結果を抽出
  • 複数サービスに対する抽出結果を1つのコメントファイルに集約
  • コメントファイルの末尾に、既存のPRコメント識別用のHTMLコメントを追加
  • GitHub Actionsでスクリプトを実行し、PRコメントを更新または新規作成

これにより、複数のterraformで管理しているマイクロサービスやフロントエンドアプリがある場合でもterraform planの実行結果をレビューしやすくなり、安全なデプロイが可能になります。

Virtual Craft Tech Blog

Discussion