Skip to content
Latchkey

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-approve

Notes

  • 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

Run this faster and cheaper on Latchkey managed runners. Start free →