技術(tech)

Building CI for Terraform – Posting Plan Results as PR Comments

Introduction

When using Terraform, integrating a workflow to check plan execution results in CI is unavoidable.

By incorporating the "terraform-plan-comment" module, you can easily and clearly output Terraform plan execution results as comments on PRs, which I’ll introduce here.

Target Audience

  • People using Terraform
  • People building CI for Terraform
  • People who want to check Terraform plan execution results on PRs

Introduction to terraform-plan-comment

Here’s the GitHub repository:
https://github.com/borchero/terraform-plan-comment

The output looks like this:

It’s as easy to understand as the plan execution results you can check on Terraform Cloud.

How to Integrate into CI

This is very simple.
Here’s an excerpt of the relevant code:

      # Run Terraform Plan
      - name: Terraform Plan
        run: |
          terraform plan -var="env=${{ matrix.env }}" -out=tfplan-${{ matrix.dir }}-${{ matrix.env }}.out
        working-directory: ${{ matrix.dir }}

      # Post results to PR
      - name: Post Plan Results to PR
        uses: borchero/terraform-plan-comment@v2
        with:
          token: ${{ github.token }}
          header: "terraform-plan Dir: ${{ matrix.dir }} (${{ matrix.env }})"
          planfile: tfplan-${{ matrix.dir }}-${{ matrix.env }}.out
          working-directory: ${{ matrix.dir }}

Output the terraform plan execution results to an xxx.out file.
Then simply pass that result as input to this module.

The PR comment title can be set with header.

You also need to pass a GitHub token with permission to post comments to the PR.

When the PR commit progresses and CI is re-executed, it automatically updates the existing comment, so comments don’t keep accumulating.

Conclusion

I’m nothing but grateful to the people maintaining this module.
Here’s to a comfortable Terraform life!