チェック用ワークフローの作成(PR時)

Pull Request時にterraform fmt・validate・planを実行し、結果をPRのコメントに投稿するワークフローを作成します。

1. ワークフローファイルの作成

Visual Studio Codeのエクスプローラーでterraform-cicd-handsonフォルダを右クリックし、「新しいフォルダー」から.github/workflowsを作成し、その中にterraform-plan.ymlを作成します。

terraform-cicd-handson/
├── README.md
├── main.tf
├── variables.tf
├── terraform.tfvars
└── .github/
    └── workflows/
        └── terraform-plan.yml  ← このファイルを作成

作成したファイルに以下の内容を記述して保存します。

name: Terraform Plan

on:
  pull_request:
    branches:
      - main

permissions:
  id-token: write
  contents: read
  pull-requests: write

env:
  AWS_REGION: ap-northeast-1
  TF_VERSION: "1.12"

jobs:
  terraform-plan:
    name: Terraform Plan
    runs-on: ubuntu-latest

    steps:
      - name: Checkout source
        uses: actions/checkout@v5

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: ${{ env.TF_VERSION }}

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@v5
        with:
          role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/tf-cicd-handson-github-actions-role
          aws-region: ${{ env.AWS_REGION }}

      - name: Terraform Format Check
        id: fmt
        run: terraform fmt -check -recursive
        continue-on-error: true

      - name: Terraform Init
        run: terraform init

      - name: Terraform Validate
        id: validate
        run: terraform validate

      - name: Terraform Plan
        id: plan
        run: terraform plan -no-color -input=false
        continue-on-error: true

      - name: Post Plan to PR
        uses: actions/github-script@v7
        with:
          script: |
            const fmtOutcome = '${{ steps.fmt.outcome }}';
            const validateOutcome = '${{ steps.validate.outcome }}';
            const planOutcome = '${{ steps.plan.outcome }}';
            const planOutput = `${{ steps.plan.outputs.stdout }}`.slice(0, 60000);

            const body = `### Terraform Plan 結果

            | チェック | 結果 |
            |---------|------|
            | 📝 Format | \`${fmtOutcome}\` |
            | ✅ Validate | \`${validateOutcome}\` |
            | 📋 Plan | \`${planOutcome}\` |

            <details>
            <summary>Plan 詳細(クリックで展開)</summary>

            \`\`\`
            ${planOutput}
            \`\`\`
            </details>`;

            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: body
            });

      - name: Check Results
        if: steps.fmt.outcome == 'failure' || steps.plan.outcome == 'failure'
        run: exit 1

コードを解説します。

      - name: Setup Terraform
        uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: ${{ env.TF_VERSION }}

hashicorp/setup-terraformアクションで、指定したバージョンのTerraformをランナー環境にインストールしています。

      - name: Terraform Format Check
        id: fmt
        run: terraform fmt -check -recursive
        continue-on-error: true

terraform fmt -checkはコードのフォーマットが統一されているかをチェックします。-recursiveでサブディレクトリも対象にします。continue-on-error: trueを指定しているため、フォーマットが崩れていてもワークフローは続行し、最後のステップで結果をまとめて判定します。

      - name: Terraform Plan
        id: plan
        run: terraform plan -no-color -input=false
        continue-on-error: true

terraform planで変更内容をプレビューします。-no-colorはANSIカラーコードを除去してコメントに投稿しやすくするオプションです。-input=falseは対話入力を無効にします。

      - name: Post Plan to PR
        uses: actions/github-script@v7

actions/github-scriptを使って、Plan結果をPull Requestのコメントとして投稿しています。レビュアーはGitHubの画面上でPlan結果を確認でき、どのリソースが追加・変更・削除されるかを把握したうえでレビューできます。

      - name: Check Results
        if: steps.fmt.outcome == 'failure' || steps.plan.outcome == 'failure'
        run: exit 1

最後に、fmtまたはplanが失敗していた場合はワークフロー全体を失敗させます。保護ブランチのステータスチェックと組み合わせることで、問題のあるコードのマージを防止できます。

2. 動作確認

作成したチェック用ワークフローが正しく動作するかを、実際にPull Requestを作成して確認します。今回のPull Requestで、配置したTerraformコード(main.tf・variables.tf・terraform.tfvars)とチェック用ワークフロー(terraform-plan.yml)をまとめてmainブランチに投入します。

作業用のブランチを作成します。

git switch -c feature/add-cicd-pipeline

追加したファイルをまとめてステージングします。

git add .

コミットします。

git commit -m "add terraform code and plan workflow"

Pushします。

git push origin feature/add-cicd-pipeline

GitHubのリポジトリ画面を開き、Compare & pull request(表示されない場合はPull requestsタブからNew pull request)をクリックします。baseにmain、compareにfeature/add-cicd-pipelineを選択し、Create pull requestをクリックしてPull Requestを作成します。

Pull Requestが作成されると、下部のChecksセクションにTerraform Plan / Terraform Plan (pull_request)のチェックが表示され、ワークフローが自動的に実行されはじめます。

しばらく待つと、github-actionsボットからPlan結果のコメントがPull Requestに投稿されます。コメントの上部の表には、以下の3項目の結果が表示されます。

  • 📝 Format: フォーマットチェックの結果を表示する(success / failure)
  • ✅ Validate: 構文検証の結果を表示する(success / failure)
  • 📋 Plan: terraform planの実行結果を表示する(success / failure)

表の下の**Plan 詳細(クリックで展開)**を開くと、terraform planの出力全文を確認できます。今回のPull Requestで新規に追加されるTerraformコードが対象となり、VPC・サブネット・インターネットゲートウェイ・ルートテーブル・セキュリティグループ・EC2のリソースがto addとして表示されます。

Plan結果のコメントがPull Requestに投稿されており、Format・Validate・Planがすべてsuccessになっていれば、チェック用ワークフローの動作確認は完了です。次の適用ワークフローの動作確認でも同じPull Requestを利用するため、マージはまだ行わずに開いたままにしておきます。