🎓 A1Learner
🔍
0 of 50 lessons completed

Terraform in CI/CD

A pipeline is Terraform run by a machine instead of a person. Plan runs on a pull request, and apply runs on a merge.

Two triggers, two jobs

A pull request triggers a plan. A push to main triggers an apply.

on:
  pull_request:
    branches: [main]
  push:
    branches: [main]

Ask for an OIDC token

The id-token permission lets the runner ask for a short-lived identity token. No secret is stored.

permissions:
  id-token: write
  contents: read
  pull-requests: write

Trade the token for a role

The step swaps the token for a cloud role that lasts for one run only. The role, not a key, grants access.

- uses: aws-actions/configure-aws-credentials@v4
  with:
    role-to-assume: arn:aws:iam::123456789012:role/terraform-ci
    aws-region: us-east-1

Plan, then apply

Plan runs only on a pull request. Apply runs only on a merge to main.

- name: Terraform Plan
  if: github.event_name == 'pull_request'
  run: terraform plan -no-color

- name: Terraform Apply
  if: github.event_name == 'push'
  run: terraform apply -auto-approve

Example

# .github/workflows/terraform.yml
name: Terraform

on:
  pull_request:
    branches: [main]
  push:
    branches: [main]

permissions:
  id-token: write
  contents: read
  pull-requests: write

jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - 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/terraform-ci
          aws-region: us-east-1
      - name: Terraform Init
        run: terraform init
      - name: Terraform Format Check
        run: terraform fmt -check
      - name: Terraform Validate
        run: terraform validate
      - name: Terraform Plan
        if: github.event_name == 'pull_request'
        run: terraform plan -no-color
      - name: Terraform Apply
        if: github.event_name == 'push'
        run: terraform apply -auto-approve

Key points

  • A pipeline runs the same commands a person runs.
  • Plan on a pull request shows the change before it lands.
  • Apply on merge makes the reviewed change real.
  • OIDC gives the pipeline short-lived credentials for one run.
  • Long-lived keys sit in storage and can leak, so never use them.
  • The workflow file is shown here and its YAML is checked.

One workflow does two jobs. A pull request runs plan so reviewers see the change. A merge to main runs apply. The pipeline itself was not run, and no run output is shown.

Note

The pipeline itself was not run, and the plan step is the same command verified in earlier lessons.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

When should a pipeline plan, and when should it apply?