How to Run terraform plan on Pull Requests in CI
Running terraform plan on the pull request shows the exact resource diff a merge would apply, which is the core of plan-review-before-apply.
Generate the plan on pull_request with read-only credentials, save it with -out, and keep the apply for the merge job. Never apply from the PR job.
Steps
- Authenticate with read-only cloud credentials (OIDC preferred).
- Run
terraform initthenterraform plan -out=tfplan -input=false. - Upload
tfplanas an artifact or post its summary as a PR comment.
Workflow
.github/workflows/ci.yml
on:
pull_request:
permissions:
contents: read
id-token: write
jobs:
plan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init -input=false
- run: terraform plan -out=tfplan -input=false -no-colorGotchas
- Give the PR job read-only cloud permissions so a plan can never mutate infrastructure.
- A saved
tfplanis tied to a state version; a later apply may reject a stale plan.
Related guides
How to Post a Terraform Plan as a PR CommentRender a Terraform plan into a collapsible pull request comment in GitHub Actions with actions/github-script,…
How to Run terraform apply on Merge to MainApply Terraform only after a merge to main in GitHub Actions, gated by a protected environment with required…