Terraform GitHub Actions Pipeline Prompt
Design a production-grade GitHub Actions workflow for Terraform that runs fmt/validate/plan on PRs, posts plan summaries as comments, and gates apply behind environments and OIDC cloud auth.
- Target user
- Platform engineers wiring Terraform into GitHub Actions CI/CD
- Difficulty
- Intermediate
- Tools
- Claude, ChatGPT
The prompt
You are a senior platform engineer who has built Terraform delivery pipelines on GitHub Actions for teams managing hundreds of stacks. Design a complete, secure workflow. I will provide: - Repo layout (mono-repo vs per-stack dirs, environments) - Cloud provider(s) and current auth method (static keys, OIDC, Vault) - Branch protection and reviewer requirements - Backend type (S3/GCS/azurerm/TFC) and locking setup - Current pain points (slow plans, secret leakage, apply races) Your job: 1. **Workflow topology** — decide PR-triggered `plan` vs `main`-triggered `apply`. Recommend two workflows (or one with conditional jobs) and explain the trade-off versus a single matrix job. 2. **OIDC cloud auth** — replace any static credentials with `id-token: write` + provider role assumption (`aws-actions/configure-aws-credentials`, Workload Identity Federation, or `azure/login`). Show the exact `permissions:` block and trust-policy conditions scoped to `repo:` and `ref:`. 3. **Plan stage** — `fmt -check`, `init` with backend config, `validate`, `plan -out=tfplan -lock-timeout=120s`, and upload the plan artifact. Show how to detect "no changes" and short-circuit. 4. **PR comment** — render `terraform show -no-color tfplan` into a collapsed `<details>` comment, with an add/change/destroy summary line at the top. Update the existing comment instead of stacking new ones. 5. **Apply gate** — use a GitHub Environment with required reviewers and the *exact same* plan artifact (never re-plan at apply time). Explain why re-planning at apply is dangerous. 6. **Concurrency & locking** — set `concurrency:` keyed by stack+environment to serialize runs and prevent two applies racing on the same state. 7. **Matrix for many stacks** — a path-filter step that computes the changed stacks and feeds a dynamic matrix, so only touched directories plan. 8. **Guardrails** — caching providers, pinning action SHAs, masking sensitive outputs, failing on `destroy` count above a threshold without an override label. Output as: (a) `.github/workflows/terraform-plan.yml`, (b) `terraform-apply.yml`, (c) the OIDC trust policy, (d) the dynamic-matrix script, (e) a rollout checklist for migrating off static keys. Bias toward: same-artifact apply, least-privilege OIDC, deterministic and serialized runs.