GitHub Actions Workflow for Terraform Plan on PR, Apply on Merge
Plan Terraform on PRs and apply automatically on merge.
This workflow plans on pull requests for review, then applies the same configuration once it merges to main.
The workflow
.github/workflows/terraform.yml
name: Terraform
on:
pull_request:
push:
branches: [main]
permissions:
id-token: write
contents: read
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
apply:
if: github.ref == 'refs/heads/main' && github.event_name == 'push'
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- uses: hashicorp/setup-terraform@v3
- run: terraform init
- run: terraform apply -auto-approveNotes
- The plan job runs on PRs; the apply job is gated to pushes on main.
- Authenticate to your cloud with OIDC rather than static keys.
- Use a protected environment on the apply job for an approval gate.
Run it cheaper
Point runs-on: at a Latchkey label to run this workflow at roughly 69% lower per-minute cost, with self-healing for transient failures.
Related guides
How to Use OIDC to Authenticate GitHub Actions to AWSAuthenticate GitHub Actions to AWS with OIDC - no long-lived secrets. Set up the IAM role, trust policy, and…
GitHub Actions Workflow for Deploy to AWS via OIDCA GitHub Actions workflow that deploys to AWS by assuming an IAM role through OIDC, with no long-lived access…