Terraform Advanced — CI/CD Exercises

1 minute read

Practice CI/CD patterns for Terraform.


Exercise 1 — GitHub Actions Plan Stage

Task: Write a GitHub Actions job that runs terraform plan only on pull requests affecting infra/ files.

Answer
jobs:
  plan:
    if: github.event_name == 'pull_request'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - run: terraform init
        working-directory: infra
      - run: terraform plan -no-color
        working-directory: infra

With trigger:

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

Exercise 2 — OIDC Trust Policy

Task: Write the IAM trust policy condition that limits GitHub OIDC to the main branch of repo myorg/infra.

Answer
{
  "Condition": {
    "StringEquals": {
      "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
      "token.actions.githubusercontent.com:sub": "repo:myorg/infra:ref:refs/heads/main"
    }
  }
}

Exercise 3 — Atlantis Config

Task: Write an atlantis.yaml for a repo with two projects: infra/networking and infra/app, both auto-planning on .tf changes.

Answer
version: 3
projects:
  - name: networking
    dir: infra/networking
    autoplan:
      enabled: true
      when_modified: ["*.tf", "*.tfvars"]
  - name: app
    dir: infra/app
    autoplan:
      enabled: true
      when_modified: ["*.tf", "*.tfvars"]

Chapter Summary

  • GitHub Actions: Plan on PR, apply on merge — use OIDC for auth
  • GitLab CI: Similar pattern with rules: and when: manual for apply
  • Atlantis: PR-based workflow with atlantis plan / atlantis apply comments
  • Terraform Cloud: Fully managed with built-in state, Sentinel policies, and run triggers
  • Always require approval before apply in production

← Terraform Cloud Runs Chapter 11: Security →

Updated: