← All writing

Automating Terraform in CI/CD: Pull Request Plans, Atlantis & Drift Detection

· Sourabh G Kulkarni

Moving off laptop terraform apply: pull request plan previews, OIDC authentication without long-lived keys, and scheduled drift detection.

Automating Terraform in CI/CD: Pull Request Plans, Atlantis & Drift Detection

Running terraform apply from a personal developer laptop is a rite of passage for early startups. It is also an operational catastrophe waiting to happen.

When engineers run Terraform locally:

  1. State locks collide when two engineers deploy simultaneously.
  2. Local provider caches and CLI versions drift, producing conflicting plans.
  3. Engineers require broad administrator IAM keys on their workstations, creating an enormous attack surface.

The enterprise standard moves Terraform execution entirely into CI/CD pipelines (via GitHub Actions, GitLab CI, or Atlantis) guarded by OpenID Connect (OIDC) and automated drift detection.

sequenceDiagram
    autonumber
    actor Dev as Platform Engineer
    participant PR as Pull Request (GitHub / Atlantis)
    participant CI as Pipeline Runner (OIDC Fed)
    participant Cloud as AWS / Azure IAM
    participant State as Remote S3 + DynamoDB

    Dev->>PR: Push branch & Open PR
    PR->>CI: Trigger Plan Workflow
    CI->>Cloud: Request Short-Lived Token (OIDC)
    Cloud-->>CI: Return STS Session Token
    CI->>State: Acquire Lock & Read State
    CI->>PR: Post Speculative Plan Diff as Comment
    Dev->>PR: Approve & Merge to main
    PR->>CI: Trigger Apply Workflow
    CI->>Cloud: Apply Changes
    CI->>State: Release Lock & Commit State

1. Passwordless Cloud Auth: OIDC Instead of IAM Secret Keys

Never store AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in GitHub repository secrets. If compromised, attackers have persistent cloud access.

Instead, configure GitHub Actions OIDC Federation with AWS IAM:

# .github/workflows/terraform-plan.yml
name: Terraform Speculative Plan
on:
  pull_request:
    branches: [ main ]

permissions:
  id-token: write # Required for requesting the JWT
  contents: read
  pull-requests: write

jobs:
  plan:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      # Exchange GitHub JWT for short-lived 15-min AWS STS credentials
      - name: Configure AWS Credentials (OIDC)
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/github-actions-terraform-plan
          aws-region: us-east-1

      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.9.0

      - name: Terraform Init
        run: terraform init

      - name: Terraform Plan
        id: plan
        run: |
          terraform plan -no-color -out=tfplan.binary
          terraform show -no-color tfplan.binary > plan_output.txt

      # Post plan output directly on the Pull Request for peer review
      - name: Comment Plan on PR
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const plan = fs.readFileSync('plan_output.txt', 'utf8');
            const body = `### 📋 Speculative Terraform Plan\n\`\`\`hcl\n${plan.slice(0, 65000)}\n\`\`\``;
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: body
            });

2. Plan vs. Apply Separation & Branch Protection

Production stability relies on two golden rules:

  1. Speculative Plan on PR: Generates an isolated plan, verifies syntax (terraform fmt -check, tflint), runs security checks (tfsec / trivy), and comments the diff on the PR.
  2. Apply Only on Merge: terraform apply runs exclusively on the default branch (main) after mandatory code review approvals and passing status checks.

Atlantis: In-PR Comment Automation

For teams that prefer conversational git workflows, Atlantis acts as an internal bot webhook. Engineers comment atlantis plan and atlantis apply directly in the PR thread, and Atlantis holds an exclusive state lock on the branch until merged.


3. Automated Drift Detection Cron

What happens when someone logs into the AWS Web Console at 2 AM during an outage and manually edits a security group? Terraform state has now drifted from reality.

Run a scheduled daily workflow to catch out-of-band changes:

# .github/workflows/drift-detection.yml
name: Scheduled IaC Drift Detection
on:
  schedule:
    - cron: '0 6 * * 1-5' # Weekdays at 6:00 AM UTC

jobs:
  detect-drift:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/github-actions-drift-detector
          aws-region: us-east-1
      - uses: hashicorp/setup-terraform@v3
      - run: terraform init
      - name: Check Drift
        run: |
          # Exit code 2 indicates drift detected
          terraform plan -detailed-exitcode -no-color || exit_code=$?
          if [ $exit_code -eq 2 ]; then
            echo "⚠️ Drift detected between code and cloud infrastructure!"
            # Send alert to Slack webhook
            curl -X POST -H 'Content-type: application/json' --data '{"text":"🚨 Terraform Drift Detected in Production!"}' ${{ secrets.SLACK_WEBHOOK_URL }}
          fi

By decoupling credentials from developer laptops and automating execution through PR-based pipelines with OIDC, your infrastructure remains audited, reproducible, and immune to rogue out-of-band edits.