Skip to content
Latchkey

How to Destroy Ephemeral Terraform Environments in CI

A workspace keyed on the PR number gives each pull request an isolated environment that a closed-PR trigger can destroy automatically.

On PR open, select a workspace named for the PR and apply. On the closed event, select the same workspace and run terraform destroy -auto-approve so nothing lingers.

Destroy on PR close

.github/workflows/preview.yml
on:
  pull_request:
    types: [closed]
jobs:
  teardown:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
      - run: terraform init -input=false
      - run: terraform workspace select pr-${{ github.event.pull_request.number }}
      - run: terraform destroy -auto-approve -input=false
      - run: terraform workspace select default && terraform workspace delete pr-${{ github.event.pull_request.number }}

Gotchas

  • You cannot delete the workspace you are currently in; switch to default first.
  • Ephemeral environments still create real, billable resources; ensure the teardown always runs.

Related guides

Run this faster and cheaper on Latchkey managed runners. Start free →