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
How to Use Terraform Workspaces per Environment in CIIsolate dev, staging, and prod state with Terraform workspaces in CI by selecting the workspace from a matrix…
How to Import Existing Resources Into Terraform in CIBring resources created outside Terraform under management in CI using import blocks with terraform plan -gen…