Lesson 14 advanced

Terraform CI/CD Pipeline

Build a GitHub Actions pipeline for Terraform with OIDC instead of stored keys, plan on every pull request, tests and policy checks, a human approval before apply, saved plans and a nightly drift check.

Running terraform apply from laptops works for one person. With a team it causes the problems infrastructure as code was meant to solve: nobody knows which version of the code was applied, credentials sit on many machines, and reviews happen after the fact. A pipeline makes the pull request the place where infrastructure changes are proposed, reviewed and applied.

The flow Orbit wants

  1. A developer opens a pull request that changes infra/.
  2. CI checks formatting, validates, runs tests and posts the plan on the pull request.
  3. Reviewers read the code and the plan, then approve.
  4. On merge to main, CI plans again, waits for a human approval on the production environment and applies exactly that plan.
  5. Every night, CI runs a plan and alerts if real infrastructure drifted from the code.

Credentials: OIDC, not stored keys

The pipeline needs AWS access. Storing an access key as a GitHub secret works, but it never expires and anyone who can edit workflows can exfiltrate it. With OpenID Connect, GitHub issues a short-lived token for each job and AWS exchanges it for temporary credentials, scoped to your repository and branch.

The AWS side, done once (in a separate bootstrap configuration):

resource "aws_iam_openid_connect_provider" "github" {
  url            = "https://token.actions.githubusercontent.com"
  client_id_list = ["sts.amazonaws.com"]
}

data "aws_iam_policy_document" "github_plan" {
  statement {
    actions = ["sts:AssumeRoleWithWebIdentity"]
    principals {
      type        = "Federated"
      identifiers = [aws_iam_openid_connect_provider.github.arn]
    }
    condition {
      test     = "StringEquals"
      variable = "token.actions.githubusercontent.com:aud"
      values   = ["sts.amazonaws.com"]
    }
    condition {
      test     = "StringLike"
      variable = "token.actions.githubusercontent.com:sub"
      values   = ["repo:orbit/infra:*"]
    }
  }
}

resource "aws_iam_role" "github_plan" {
  name               = "orbit-terraform-plan"
  assume_role_policy = data.aws_iam_policy_document.github_plan.json
}

Create two roles: a read-only orbit-terraform-plan role any branch can use, and an orbit-terraform-apply role whose trust condition only allows repo:orbit/infra:environment:production. A malicious pull request can then plan, but never apply.

The pull request workflow

.github/workflows/terraform-pr.yml:

name: terraform-pr

on:
  pull_request:
    paths: ["infra/**"]

permissions:
  id-token: write        # needed for OIDC
  contents: read
  pull-requests: write   # to comment the plan

concurrency:
  group: terraform-${{ github.ref }}
  cancel-in-progress: true

jobs:
  plan:
    runs-on: ubuntu-latest
    defaults:
      run:
        working-directory: infra/envs/prod
    steps:
      - uses: actions/checkout@v5

      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.17.1
          terraform_wrapper: false

      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/orbit-terraform-plan
          aws-region: eu-west-1

      - run: terraform fmt -check -recursive ../..
      - run: terraform init -input=false
      - run: terraform validate
      - run: terraform init -input=false && terraform test
        working-directory: infra/modules/orbit-app
      - run: terraform plan -input=false -lock=false -no-color -out=tfplan
      - run: terraform show -no-color tfplan > plan.txt

      - name: Comment plan
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const plan = fs.readFileSync('infra/envs/prod/plan.txt', 'utf8');
            const body = '### Terraform plan (prod)\n```\n' + plan.slice(0, 60000) + '\n```';
            await github.rest.issues.createComment({ ...context.repo, issue_number: context.issue.number, body });

Points worth copying:

  • -lock=false on pull request plans: they never write state, so they should not block a real apply. Never use it on apply.
  • concurrency cancels outdated runs when someone pushes again.
  • The plan text is trimmed, because GitHub comments have a size limit.
  • terraform test runs module tests with mock providers (lesson 6), so they need no cloud access.

Policy checks in the pipeline

Tests check that a module does what it promises. Policies check that a plan follows the rules of your organisation: no public buckets, only approved instance types, tags present. Options in 2026:

  • Terraform Policy, generally available in Terraform 1.17: terraform plan, apply and query accept a -policies flag that evaluates HCL policy files (.policy.hcl) against the plan, locally or in CI, with no separate engine.
  • HCP Terraform policy sets (Sentinel or OPA) when you run in HCP Terraform.
  • Static scanners such as Trivy (trivy config infra/) or Checkov (checkov -d infra/) that read the code itself and catch common misconfigurations before any plan.

Run the scanner on every pull request; it takes seconds and catches many issues before a human reviewer has to.

Applying on merge, with approval

.github/workflows/terraform-apply.yml:

name: terraform-apply

on:
  push:
    branches: [main]
    paths: ["infra/**"]

permissions:
  id-token: write
  contents: read

concurrency:
  group: terraform-apply-prod
  cancel-in-progress: false

jobs:
  apply:
    runs-on: ubuntu-latest
    environment: production
    defaults:
      run:
        working-directory: infra/envs/prod
    steps:
      - uses: actions/checkout@v5
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.17.1
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/orbit-terraform-apply
          aws-region: eu-west-1
      - run: terraform init -input=false
      - run: terraform plan -input=false -out=tfplan
      - run: terraform apply -input=false tfplan
  • environment: production with required reviewers configured in the repository settings pauses the job until someone approves. The approval also unlocks the apply role through its OIDC trust condition.
  • cancel-in-progress: false queues applies instead of cancelling one halfway, which could leave a stale lock.
  • Applying the saved plan means Terraform does exactly what was planned in this job, and refuses if state changed in between.

To make reviewers approve the exact plan shown, add a step that prints terraform show tfplan before the approval, or split plan and apply into two jobs and pass the plan file as an artifact (encrypted, it can contain secrets).

Nightly drift detection

name: terraform-drift
on:
  schedule:
    - cron: "0 5 * * *"
jobs:
  drift:
    runs-on: ubuntu-latest
    permissions:
      id-token: write
      contents: read
    steps:
      # checkout, setup-terraform, credentials and init as above
      - run: terraform plan -input=false -lock=false -detailed-exitcode
        working-directory: infra/envs/prod

-detailed-exitcode returns 0 when there are no changes, 2 when there are changes and 1 on errors. Exit code 2 fails the job, so GitHub notifies the team that something changed outside Terraform. This is also the safety net that makes -minimal-refresh (lesson 3) acceptable on pull request plans.

Other ways to run Terraform in CI

OptionStrength
Plain GitHub Actions or GitLab CI (this lesson)Full control, no extra service
HCP Terraform with VCS-driven runsPlans on PRs, approvals, state, policies and drift detection built in
Atlantis (self-hosted)Plan and apply driven by pull request comments
Spacelift, env0, ScalrCommercial platforms with policy, cost and drift features

Quick reference

TaskCommand or setting
Fail CI on unformatted codeterraform fmt -check -recursive
Never prompt in CI-input=false
Plan without taking the lock (PRs only)terraform plan -lock=false
Save and apply an exact planplan -out=tfplan, then apply tfplan
Exit code 2 on changesterraform plan -detailed-exitcode
Pin the Terraform versionhashicorp/setup-terraform with terraform_version
Short-lived AWS credentialsaws-actions/configure-aws-credentials with role-to-assume
Require a human approvalenvironment: production with required reviewers

Exercise

Why give the pull request workflow a read-only plan role and keep a separate apply role?

  1. terraform plan does not work with write permissions
  2. Anyone who can open a pull request can change the workflow; a read-only role means a malicious PR can plan but never change infrastructure
  3. GitHub limits each workflow to one IAM role
  4. Apply roles are only allowed in HCP Terraform
Show answer

Answer: B. Workflow files in a pull request run with that PR’s code. Restricting the powerful role to the protected production environment (through the OIDC sub claim) keeps write access behind review and approval.

Exercise

The nightly job runs terraform plan -detailed-exitcode and exits with code 2. What does that mean?

  1. The plan failed with an error
  2. Terraform needs to be upgraded
  3. The plan succeeded and found changes: the real infrastructure differs from the code
  4. The state lock was held by another job
Show answer

Answer: C. With -detailed-exitcode, 0 means no changes, 1 means error and 2 means changes are pending, which in a nightly job means drift.

Key takeaways

  • Make the pull request the place where plans are reviewed and changes are approved.
  • Use OIDC for short-lived cloud credentials; separate read-only plan and apply roles.
  • Run fmt, validate, terraform test, scanners and policies on every pull request.
  • Apply only on the main branch, behind an environment approval, from a saved plan.
  • Queue applies with concurrency and never cancel one halfway.
  • A nightly plan -detailed-exitcode catches drift.

FAQ

Should pull request plans run against production?

Yes, with the read-only role. A plan against the real environment is the only one that shows what the merge will really do. Use -lock=false so PR plans never block applies.

Is a saved plan file safe to upload as an artifact?

Plan files can contain sensitive values in plain text. If you pass them between jobs, keep retention short, restrict who can download artifacts and prefer ephemeral values so secrets are not in the plan at all.

How do I handle several environments in one pipeline?

Use a matrix over the environment folders for plans, and a separate apply job per environment with its own GitHub environment, role and approval rules. Apply to staging first and promote to production after it succeeds.

Do I still need terraform validate if I run plan?

It is cheap and gives clearer errors faster, without credentials. Keep it as an early step so contributors get feedback in seconds.

↑ ↓ navigate Enter open Esc close