Overview and What You Will Learn
A Terraform pipeline in GitHub Actions runs terraform plan on every pull request and terraform apply only after merge, using short-lived AWS credentials obtained through OpenID Connect (OIDC). This replaces laptop-based applies, where two engineers can apply at once, nobody has a reliable record of what changed, and reviewers must trust a pasted plan.
By the end of this lab you will be able to:
- Create an AWS OIDC provider and separate plan and apply roles with tight trust policies
- Build a plan workflow that checks format, validates, lints, scans, and plans on every PR
- Post the plan to the PR as a comment safely, without script injection
- Run
terraform applyon merge behind a GitHub Environment approval and a concurrency lock - Cache Terraform providers correctly
- Run the same plan across several environments with a matrix
- Pin Terraform versions so laptops and CI agree
Why This Matters in Production
Imagine a payments platform team where engineers apply from laptops. One day an engineer applies with credentials from a different AWS profile than the one shown in the plan pasted into Slack, and the infrastructure created is not what anyone reviewed. A team at a company like PhonePe or Stripe avoids this class of problem by letting only a CI identity apply, with credentials that exist for minutes and can only be obtained from a specific repository and environment. (This scenario is illustrative, not a documented incident.)
Core Principles
The pipeline has two halves with different permissions. The plan half runs on every pull request with a read-only role. The apply half runs after merge, behind a human approval, with a write role.
lint, scan] CHK --> PLAN[Plan with
read-only role] PLAN --> CMT[Plan posted
as PR comment] CMT --> REV{Reviewer
approves?} REV -->|yes| MRG[Merge to main] MRG --> GATE[Environment
approval] GATE --> APPLY[Apply with
write role] classDef code fill:#326CE5,color:#ffffff classDef tool fill:#10B981,color:#ffffff classDef gate fill:#F97316,color:#ffffff class PR,MRG code class CHK,PLAN,CMT,APPLY tool class REV,GATE gate
OIDC works because GitHub issues each job a signed token that names the repository, branch, or environment it came from. AWS checks that token against the trust policy on the role, so the trust policy is the real security boundary.
Detailed Step-by-Step Practical Lab
How to Set Up OIDC Between GitHub Actions and AWS
OIDC lets a workflow request short-lived AWS credentials directly, so no access key is stored as a GitHub secret. Create the provider and two roles once, from a bootstrap configuration run by an administrator.
locals { github_repo = "zerodha-platform/infrastructure" roles = { plan = { # Subject claim for any pull_request workflow in this repo sub = "repo:${local.github_repo}:pull_request" policy_arn = "arn:aws:iam::aws:policy/ReadOnlyAccess" } apply = { # Subject claim for jobs that use the "production" environment sub = "repo:${local.github_repo}:environment:production" policy_arn = "arn:aws:iam::aws:policy/PowerUserAccess" # starter only, replace with a scoped policy } }} resource "aws_iam_openid_connect_provider" "github" { url = "https://token.actions.githubusercontent.com" client_id_list = ["sts.amazonaws.com"]} resource "aws_iam_role" "github_terraform" { for_each = local.roles name = "github-terraform-${each.key}" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [{ Effect = "Allow" Principal = { Federated = aws_iam_openid_connect_provider.github.arn } Action = "sts:AssumeRoleWithWebIdentity" Condition = { StringEquals = { "token.actions.githubusercontent.com:aud" = "sts.amazonaws.com" "token.actions.githubusercontent.com:sub" = each.value.sub } } }] })} resource "aws_iam_role_policy_attachment" "github_terraform" { for_each = local.roles role = aws_iam_role.github_terraform[each.key].name policy_arn = each.value.policy_arn}SecurityThe
subcondition is the entire security boundary. A pattern likerepo:*:*would let any GitHub repository assume your role. Match your exact organisation and repository, and use an exact environment or branch for the apply role.
RememberRecent versions of the AWS provider no longer require
thumbprint_listfor the GitHub OIDC provider. On older provider versions you must still supply it. The plan role also needs read and lock access to your state backend, so attach a small state-access policy as well.
How to Write a Terraform Plan Workflow for Pull Requests
The plan workflow checks quality gates first, then plans, then reports the result on the PR even when the plan fails.
name: Terraform Plan on: pull_request: paths: ["environments/**", "modules/**"] permissions: id-token: write # lets the job request an OIDC token contents: read pull-requests: write # lets the job comment on the PR jobs: plan: runs-on: ubuntu-latest defaults: run: working-directory: environments/prod steps: - uses: actions/checkout@v4 - name: Configure AWS credentials via OIDC uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789012:role/github-terraform-plan aws-region: ap-south-1 - uses: hashicorp/setup-terraform@v3 with: terraform_version: 1.9.8 - name: Format check run: terraform fmt -check -recursive - name: Init run: terraform init -input=false - name: Validate run: terraform validate - uses: terraform-linters/setup-tflint@v4 - name: Lint run: tflint --init && tflint - name: Scan with Trivy uses: aquasecurity/trivy-action@0.28.0 with: scan-type: config scan-ref: environments/prod severity: HIGH,CRITICAL exit-code: "1" - name: Plan id: plan run: terraform plan -no-color -input=false continue-on-error: true # capture failures so we can comment first - name: Comment plan on PR uses: actions/github-script@v7 env: PLAN_STDOUT: ${{ steps.plan.outputs.stdout }} PLAN_STDERR: ${{ steps.plan.outputs.stderr }} with: script: | const raw = process.env.PLAN_STDOUT || process.env.PLAN_STDERR || "No output"; const plan = raw.slice(0, 60000); // GitHub comments cap near 65,536 characters const fence = "`".repeat(3); await github.rest.issues.createComment({ issue_number: context.issue.number, owner: context.repo.owner, repo: context.repo.repo, body: `#### Terraform Plan\n${fence}\n${plan}\n${fence}` }); - name: Fail job if plan failed if: steps.plan.outcome == 'failure' run: exit 1Common MistakePasting
${{ steps.plan.outputs.stdout }}straight into the JavaScript template. Plan output can contain backticks or${}that break the script, and untrusted text inside the script body is a code-injection risk. Pass it throughenvand readprocess.envas shown.
How to Run Terraform Apply on Merge with an Approval Gate
A GitHub Environment with required reviewers adds a human approval after the merge, and a concurrency group stops two applies from running at once. The apply job plans and applies in one run so the logged plan matches what is applied.
# .github/workflows/terraform-apply.ymlname: Terraform Apply on: push: branches: [main] paths: ["environments/**", "modules/**"] permissions: id-token: write contents: read concurrency: group: terraform-prod cancel-in-progress: false # never cancel an apply that is running jobs: apply: runs-on: ubuntu-latest environment: production # triggers required-reviewer approval defaults: run: working-directory: environments/prod steps: - uses: actions/checkout@v4 - name: Configure AWS credentials via OIDC uses: aws-actions/configure-aws-credentials@v4 with: role-to-assume: arn:aws:iam::123456789012:role/github-terraform-apply aws-region: ap-south-1 - uses: hashicorp/setup-terraform@v3 with: terraform_version: 1.9.8 - run: terraform init -input=false - run: terraform plan -input=false -out=tfplan - run: terraform apply -input=false tfplanIn the repository settings, add the production environment and set required reviewers. Even after a PR merges, a designated approver must approve in GitHub before the job runs apply, which is a second gate independent of code review.
How to Cache Terraform Providers in GitHub Actions
Provider downloads are large, so caching them saves minutes per run. The plugin cache directory must be set with the TF_PLUGIN_CACHE_DIR environment variable, because .terraformrc does not expand shell variables.
jobs: plan: runs-on: ubuntu-latest env: TF_PLUGIN_CACHE_DIR: /home/runner/.terraform.d/plugin-cache steps: - uses: actions/checkout@v4 - name: Create plugin cache directory run: mkdir -p "$TF_PLUGIN_CACHE_DIR" - name: Cache Terraform providers uses: actions/cache@v4 with: path: /home/runner/.terraform.d/plugin-cache key: ${{ runner.os }}-tf-providers-${{ hashFiles('**/.terraform.lock.hcl') }}TipCommit
.terraform.lock.hcl. It pins provider versions and gives the cache key something stable to hash.
How to Plan Multiple Environments with a Matrix
A matrix runs the same job once per environment instead of copying workflow files.
jobs: plan: runs-on: ubuntu-latest strategy: fail-fast: false matrix: environment: [dev, staging, prod] defaults: run: working-directory: environments/${{ matrix.environment }} steps: - uses: actions/checkout@v4 - uses: hashicorp/setup-terraform@v3 with: terraform_version: 1.9.8 - run: terraform init -input=false - name: Plan for ${{ matrix.environment }} run: terraform plan -input=falseAdd the OIDC step to each job in a real pipeline. Use separate roles per environment so a dev job cannot read production.
How to Add Security Scanning to a Terraform Pipeline
Static scanning fails the PR before a plan is even read. tfsec has been folded into Trivy, so the config scanner is the maintained route.
# Examples of findings that fail the jobAWS-0086 S3 bucket does not block public ACLsAWS-0107 Security group rule allows ingress from 0.0.0.0/0How to Pin the Terraform Version Everywhere
An exact pin keeps your laptop and the CI runner on the same Terraform version, so plans match.
# versions.tfterraform { required_version = "= 1.9.8" # keep in sync with the workflow's terraform_version}Production Best Practices & Common Pitfalls
- Use separate roles for plan and apply. Plan runs on every PR, so give it read-only access and a
pull_requestsubject. Reserve write access for the apply role bound to theproductionenvironment. - Use a GitHub Environment for the apply gate, not only branch protection. Branch protection controls who can merge code. An Environment with required reviewers controls who can authorize the apply.
- Add a concurrency group to apply. Without it, two merges in quick succession can start overlapping applies against the same state.
- Never use
pull_request_targetfor plan. It runs with repository secrets in the context of untrusted PR code. - Pin third-party actions to a release tag or commit SHA. A moving tag can change under you.
- Handle
continue-on-errordeliberately. It lets the PR comment show the real error, but you must fail the job afterward or a broken plan looks green. - Know the plan and apply gap. If the apply job plans again after merge, the result can differ from the reviewed plan when main changed in between. Planning and applying in the same run, as shown, and keeping applies serialized reduces that risk.
Quick Reference & Troubleshooting Commands
| Trigger | Job | What Runs |
|---|---|---|
pull_request |
Plan | fmt, init, validate, tflint, scan, plan, PR comment |
push to main |
Apply | init, plan, apply behind Environment approval |
| Error | Root Cause | Fix |
|---|---|---|
Not authorized to perform sts:AssumeRoleWithWebIdentity |
Trust policy sub does not match the job's repo, event, or environment |
Compare the exact sub string in the token with the trust policy |
| Plan comment never appears | Missing pull-requests: write permission |
Add it to the workflow permissions block |
| Apply stuck on "Waiting" | Environment requires reviewers | A designated reviewer must approve in GitHub |
| Provider downloads on every run | Cache key misses or TF_PLUGIN_CACHE_DIR not set |
Set the env var and hash the committed lock file |
| Comment step fails on large plans | Plan exceeds the comment size limit | Truncate the output or upload the plan as an artifact |