Prompt
How do I run infrastructure plans in pull requests before apply?
Latest observation
Oct 25, 2026
OpenAI APIWeb search: off
A common pattern is:
- Run
planautomatically on every pull request - Post the plan output back to the PR
- Only run
applyafter the PR is approved and merged
or via a separate manual approval step
Typical workflow
1) On PRs: run plan
Configure your CI/CD pipeline to trigger on pull request events. In that job:
- check out the code
- authenticate to your cloud/provider
- initialize Terraform/OpenTofu
- run
plan - save the plan as an artifact or comment it on the PR
Example with Terraform:
terraform init
terraform plan -out=tfplan
terraform show -no-color tfplan
2) On merge to main: apply
Run apply only on the main branch, ideally with protections:
terraform init
terraform apply -auto-approve tfplan
In most teams, apply is either:
- automatic after merge to
main - manual with an approval gate
- restricted to a protected environment
Recommended safeguards
- Use remote state so the plan reflects current infrastructure
- Use the same variables in plan and apply
- Store the plan artifact if you want to apply exactly what was reviewed
- Limit credentials on PR builds
- read-only where possible
- don’t expose secrets to untrusted forked PRs
- Comment the plan on the PR for visibility
- Fail the PR if the plan has changes only if that matches your policy
Example GitHub Actions setup
name: terraform
on:
pull_request:
push:
branches:
- main
jobs:
plan:
if: github.event_name == 'pull_request'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
- run: terraform plan -no-color -out=tfplan
- run: terraform show -no-color tfplan
apply:
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
- run: terraform apply -auto-approve
Best practice
If you want the exact reviewed plan to be applied, generate the plan in PR validation, store it as an artifact, and then apply that artifact after merge. If not, just rerun plan during apply to ensure it reflects the latest state.
If you tell me which tool you’re using—Terraform, OpenTofu, Pulumi, AWS CDK, etc.—and which CI system—GitHub Actions, GitLab CI, Azure DevOps, Jenkins—I can give you a ready-to-use pipeline example.