DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

TerraformLesson 13 of 17
Your progress · 0%
On this page
  1. Plan on PR, apply on merge
  2. GitHub Actions
  3. GitLab CI
  4. Jenkins
↖ Course roadmap
Lesson 13 · CI/CD integration

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.

30 min read · intermediate · hands-on

By the end of this lesson you'll be able to

0 of 4 complete
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.
Code walkthrough: the GitHub Actions, GitLab CI and Jenkins pipelines: explained, not run.
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

Laptops plan; the pipeline applies, after a human has read the plan.© Diagram: DevOps Academy

Laptops plan; the pipeline applies, after a human has read the plan.© Diagram: DevOps Academy

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:

# 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)
terraform plan -detailed-exitcode
  • terraforminfrastructure as code
  • planpreview changes

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.

# .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:

# .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):

// 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.

⌘
Mini 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.

Input: An infra/ folder with one environmentOutput: .github/workflows/terraform.yml
Reveal one safe solution
$ 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 $?"
terraform plan -detailed-exitcode -input=false >/dev/null; echo "exit code $?"
  • terraforminfrastructure as code
  • planpreview changes

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 yourself

0 of 5 steps done

Run each task in your own account or terminal, then tick it off.

Knowledge check

Quick check

Question 1 of 3

What does terraform plan -detailed-exitcode return when there are changes?

Go deeper

Official reading for this lesson

  • GuideAutomate Terraform with GitHub ActionsHashiCorp ↗
  • Toolhashicorp/setup-terraform actionHashiCorp on GitHub ↗
  • DocsConfiguring OpenID Connect in AWS (GitHub Actions)GitHub Docs ↗
  • GuideRunning Terraform in automationHashiCorp ↗
  • DocsGitLab-managed Terraform state and CIGitLab Docs ↗
  • ToolAtlantis (pull request automation for Terraform)Atlantis ↗

Or get every quiz answer right and it completes itself.

Something unclear, wrong or out of date in this lesson? Tell me, and I'll fix it.

← PreviousEnvironments: workspaces or foldersNext lesson →Testing Terraform code