# Terraform in CI/CD

Run Terraform from a pipeline instead of laptops: checks and plan on every pull request, apply the reviewed plan on merge, with short-lived cloud credentials, in GitHub Actions, GitLab CI and Jenkins.

Course: [Terraform](https://devops.rajeev.pro/courses/terraform), lesson 13. About 30 minutes, intermediate. Source: https://devops.rajeev.pro/courses/terraform/13-ci-cd-integration

## What you will learn

- Describe the plan-on-PR, apply-on-merge workflow and why laptops shouldn't apply
- Use terraform plan -detailed-exitcode in scripts
- Write a GitHub Actions workflow with OIDC credentials, a plan job and a protected apply job
- Translate the same flow to GitLab CI and Jenkins

> **Lab status.** **Verified lab:** plan -detailed-exitcode exit codes, and the workflow's YAML structure and job wiring (parsed, not run). Run on Terraform 1.17.1; the output shown is real. <br />**Code walkthrough:** the GitHub Actions, GitLab CI and Jenkins pipelines: explained, not run. <br />**Cloud lab:** the pipelines need a repository, runners and an AWS role trusted through OIDC.

When five people apply from five laptops, nobody knows who changed what, every laptop needs
production credentials, and two applies collide. Teams fix this the same way they fix deployments:
a pipeline. Every change goes through a pull request, CI plans it, a human reviews the plan, and only
the pipeline applies.

## Plan on PR, apply on merge

> **Figure.** A pipeline: open a pull request from a feature branch, checks run fmt, validate, tflint and trivy, plan is posted as a PR comment, a human reviews the plan, merge to main, and apply runs in a protected environment with OIDC credentials. Below, exit codes CI can use from terraform plan -detailed-exitcode: 0 no changes, 1 error, 2 changes present. The same idea works in GitHub Actions with hashicorp/setup-terraform, GitLab CI with a plan job and a manual apply job, Jenkins with an input step before apply, and Atlantis or HCP Terraform for pull request automation.
>
> Laptops plan; the pipeline applies, after a human has read the plan.

The flow, step by step:

1. **A developer opens a pull request** with a Terraform change.
2. **CI runs the pre-plan checks** from lesson 7: `fmt -check`, `validate`, `tflint`, and a security
   scan (lesson 16).
3. **CI runs `terraform plan`** against the real backend (it reads resources and takes the state lock)
   and posts the plan as a comment.
4. **A reviewer reads the plan**, not just the code. "2 to destroy" on a database gets caught here.
5. **On merge to main**, CI runs `terraform apply`, with production protected by an approval rule.

Three settings make Terraform behave in a pipeline: `-input=false` (never wait for a prompt that
nobody will answer), `-no-color` (clean logs), and `TF_IN_AUTOMATION=1` (shorter messages without
"next, run this command" hints).

### Exit codes scripts can use

`-detailed-exitcode` turns plan into a yes/no signal. The real runs from the lab:

```text
# nothing changed
$ terraform plan -detailed-exitcode
No changes. Your infrastructure matches the configuration.
(exit code 0)
# after editing content in main.tf
$ terraform plan -detailed-exitcode
...
Plan: 1 to add, 0 to change, 1 to destroy.
(exit code 2)
```

0 means no changes, 1 means an error, 2 means changes. A nightly job that runs plan on production
and alerts on exit code 2 is a simple **drift detector**.

## GitHub Actions

This workflow runs checks and a plan on every pull request, and on merge to main it plans again,
waits for approval, and applies **that exact saved plan**. It uses **OIDC**: GitHub issues the job a
signed token, and AWS swaps it for temporary credentials of a role that trusts only this repository,
so no access keys are stored anywhere.

> **Code walkthrough.** This workflow wasn't run for this course, which has no AWS pipeline. It follows the docs of each action linked in Resources. Pin each action to a release (or a commit SHA) you've reviewed.

```yaml
# .github/workflows/terraform.yml
name: terraform
on:
  pull_request:
    paths: ['infra/**']
  push:
    branches: [main]
    paths: ['infra/**']

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

concurrency: terraform-prod # never two runs against prod at once

defaults:
  run:
    working-directory: infra/envs/prod

jobs:
  plan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.17.1
          terraform_wrapper: false # plain exit codes and output
      - uses: terraform-linters/setup-tflint@v4

      # 1. checks that need no cloud credentials
      - run: terraform fmt -check -recursive
      - run: terraform init -input=false
      - run: terraform validate
      - run: tflint --init && tflint --format=compact
      - uses: aquasecurity/trivy-action@0.28.0
        with:
          scan-type: config
          scan-ref: infra/envs/prod
          severity: HIGH,CRITICAL
          exit-code: '1' # fail the job on findings

      # 2. plan with credentials that can read, and take the state lock
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/terraform-plan
          aws-region: ap-south-1
      - run: terraform plan -input=false -no-color -out=tfplan
      - run: terraform show -no-color tfplan > plan.txt

      # 3. on a PR: post the plan as a comment for code review
      - if: github.event_name == 'pull_request'
        uses: actions/github-script@v7
        with:
          script: |
            const plan = require('fs').readFileSync('infra/envs/prod/plan.txt', 'utf8');
            const fence = '`'.repeat(3); // a Markdown code block around the plan
            await github.rest.issues.createComment({
              ...context.repo, issue_number: context.issue.number,
              body: fence + '\n' + plan.slice(-60000) + '\n' + fence, // comments have a size limit
            });

      # 4. on main: keep the exact plan for the apply job
      - if: github.ref == 'refs/heads/main'
        uses: actions/upload-artifact@v4
        with:
          name: tfplan
          path: infra/envs/prod/tfplan
          retention-days: 1 # plan files contain secrets: keep them briefly

  apply:
    if: github.ref == 'refs/heads/main'
    needs: plan
    runs-on: ubuntu-latest
    environment: production # pauses for a named reviewer
    steps:
      - uses: actions/checkout@v4 # same commit, same lock file as the plan
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.17.1
          terraform_wrapper: false
      - uses: actions/download-artifact@v4
        with:
          name: tfplan
          path: infra/envs/prod
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/terraform-apply
          aws-region: ap-south-1
      - run: terraform init -input=false
      - run: terraform apply -input=false tfplan # the reviewed plan, nothing else
```

How it guarantees "what was approved is what runs":

1. **Two plans, two purposes.** The pull-request plan is for **code review**: it shows what the change
   would do. After merge, main may also contain other merged changes, so the workflow plans again on
   main. **That** plan is what the approver reads (in the plan job's log) before approving the
   `production` environment, and it's the one applied.
2. **The saved file travels between jobs.** `upload-artifact` and `download-artifact` move the exact
   `tfplan` binary from the plan job to the apply job, which runs `terraform apply tfplan`, not a
   fresh plan.
3. **The approval is tied to that exact file.** Approving the `production` environment approves one
   **workflow run**. Without a `run-id`, `download-artifact` only fetches artifacts from that same run,
   so the apply job can only get the `tfplan` its own plan job made, and the approver reads that plan in
   the same run's log. A re-run or a new commit produces a new plan and needs a new approval.
4. **Same commit, same versions.** The apply job checks out the same commit, so the configuration and
   `.terraform.lock.hcl` match, and init installs the same provider builds the plan used.
5. **Stale plans are refused.** If anything changed the state between plan and apply, `terraform apply
tfplan` fails with a "Saved plan is stale" error instead of applying something nobody saw. Plan
   again and get a new approval.
6. **`concurrency`** stops two runs from planning and applying against production at the same time.

### Credentials and IAM

- **Two roles, scoped by repository and branch** in each role's trust policy. The apply role trusts
  only `main` and the `production` environment.
- **"Read-only" plan role is a simplification.** A plan reads every managed resource, so it needs read
  permissions on them, but it also **writes**: with the S3 backend and `use_lockfile = true`, it creates
  and deletes a `<key>.tflock` object to hold the lock. So the plan role needs `s3:ListBucket` on the
  bucket, `s3:GetObject` on the state key, and `s3:GetObject`, `s3:PutObject` and `s3:DeleteObject` on
  the `.tflock` key, plus KMS decrypt if the state is encrypted with a customer key. It must **not** be
  able to write the state object itself or change infrastructure.
- **The apply role** additionally writes the state object and has the permissions to create and change
  the resources, nothing broader. Least privilege here takes iteration: start from the resources in
  the configuration, not from `AdministratorAccess`.

### Plan files are secrets

A saved plan contains every value in it, sensitive ones included. Artifacts are readable by anyone
with read access to the repository, so keep `retention-days` short, keep the repository private, or
encrypt the plan before uploading. Never post the binary plan anywhere public; the PR comment uses
`terraform show` output, where sensitive values are redacted.

## GitLab CI

The same flow in GitLab, with a manual gate before apply:

```yaml
# .gitlab-ci.yml
image:
  name: hashicorp/terraform:1.17.1
  entrypoint: ['']

stages: [validate, plan, apply]

validate:
  stage: validate
  script:
    - terraform fmt -check -recursive
    - terraform init -input=false
    - terraform validate

plan:
  stage: plan
  script:
    - terraform init -input=false
    - terraform plan -input=false -out=tfplan
  artifacts:
    paths: [tfplan]
    expire_in: 1 day

apply:
  stage: apply
  script:
    - terraform init -input=false
    - terraform apply -input=false tfplan
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
      when: manual # someone clicks "run" after reading the plan
```

GitLab can also store Terraform state for you (GitLab-managed state, an HTTP backend) and supports
OIDC to AWS with ID tokens.

## Jenkins

In Jenkins, `stash` saves the binary plan so the apply stage uses exactly that file, even if it runs
on a different agent, and an `input` step pauses for approval in between (a code walkthrough, not run
here):

```groovy
// Jenkinsfile
pipeline {
  agent none
  options { timestamps(); disableConcurrentBuilds() }
  stages {
    stage('Plan') {
      agent { label 'terraform' }
      steps {
        dir('infra/envs/prod') {
          sh 'terraform init -input=false'
          sh 'terraform plan -input=false -no-color -out=tfplan'
          sh 'terraform show -no-color tfplan > plan.txt'
          archiveArtifacts artifacts: 'plan.txt' // readable plan for the approver
          stash name: 'tfplan', includes: 'tfplan' // the exact binary plan
        }
      }
    }
    stage('Approve') {
      when { branch 'main' }
      steps {
        input message: 'Apply the plan in plan.txt to production?' // holds no agent while waiting
      }
    }
    stage('Apply') {
      when { branch 'main' }
      agent { label 'terraform' }
      steps {
        dir('infra/envs/prod') {
          unstash 'tfplan'
          sh 'terraform init -input=false'
          sh 'terraform apply -input=false tfplan'
        }
      }
    }
  }
}
```

`agent none` at the top plus an agent per stage means the approval wait doesn't tie up an executor,
and `stash`/`unstash` carries the plan between agents instead of hoping the workspace is still there.
`disableConcurrentBuilds()` plays the role of GitHub's `concurrency`. The CI/CD course covers Jenkins
pipelines in depth. For credentials, run agents with an IAM role (on EC2 or EKS) rather than storing
keys in Jenkins.

### Dedicated tools

**Atlantis** (open source) runs plan when a PR opens and apply when someone comments `atlantis apply`,
all inside the pull request. **HCP Terraform** (HashiCorp's service) runs plans and applies remotely
with state, policy checks and approvals built in. Both implement the same idea as the workflows above.

> **In production.** Make the pipeline the only identity allowed to apply in production; developers get read-only access. Run a scheduled plan with `-detailed-exitcode` to catch drift, and alert the owning team on exit code 2.

## Mission: Write a plan-on-PR, apply-on-merge workflow

Write .github/workflows/terraform.yml for one environment folder: fmt, validate and plan on pull requests; apply only on main, after approval through a protected environment; OIDC credentials, with no stored keys; Terraform pinned. Then test plan's exit codes locally with and without a change.

- You need: An infra/ folder with one environment
- You'll have: .github/workflows/terraform.yml

```sh
$ terraform plan -detailed-exitcode -input=false >/dev/null; echo "exit code $?"
$ # edit a resource, then:
$ terraform plan -detailed-exitcode -input=false >/dev/null; echo "exit code $?"
```

Locally you should see `0` then `2`, as in the lab. For the workflow, check three things: `apply`
has `if: github.ref == 'refs/heads/main'`, it uses `environment:` with required reviewers, and no
step references an access key.

## Try it

- Run `terraform plan -detailed-exitcode; echo $?` with no changes, then after editing a resource.
- Read the GitHub Actions workflow in this lesson and mark which steps run on PRs and which on main.
- Set up an AWS IAM role trusted by GitHub's OIDC provider in a test account (optional).
- Add `-input=false` to every Terraform command in a script and explain why.
- Do the mini mission and keep `.github/workflows/terraform.yml`.

## Quiz

1. What does `terraform plan -detailed-exitcode` return when there are changes?
   - 0
   - 1
   - **2** (answer)
   Why: 0 means no changes, 1 means an error, 2 means the plan has changes. Scripts use it to detect drift or decide whether to apply.

2. Why use OIDC instead of storing AWS access keys in CI secrets?
   - It's faster
   - **CI gets short-lived credentials for one job by assuming a role; there are no long-lived keys to leak or rotate** (answer)
   - OIDC is required by Terraform
   Why: The cloud trusts tokens from your CI provider for a specific repository and branch, and hands out temporary credentials.

3. Where should terraform apply for production run?
   - On the developer's laptop after a plan
   - **In the pipeline after merge, behind a protected environment, using the reviewed plan** (answer)
   - Anywhere, as long as it's planned first
   Why: One place applies, with one set of credentials and a full log. Reviews happen on the plan, before merge.

## Resources

- [Automate Terraform with GitHub Actions](https://developer.hashicorp.com/terraform/tutorials/automation/github-actions) (HashiCorp)
- [hashicorp/setup-terraform action](https://github.com/hashicorp/setup-terraform) (HashiCorp on GitHub)
- [Configuring OpenID Connect in AWS (GitHub Actions)](https://docs.github.com/en/actions/security-for-github-actions/security-hardening-your-deployments/configuring-openid-connect-in-amazon-web-services) (GitHub Docs)
- [Running Terraform in automation](https://developer.hashicorp.com/terraform/tutorials/automation/automate-terraform) (HashiCorp)
- [GitLab-managed Terraform state and CI](https://docs.gitlab.com/user/infrastructure/iac/) (GitLab Docs)
- [Atlantis (pull request automation for Terraform)](https://www.runatlantis.io/) (Atlantis)
