How to Tear Down a Preview Environment When a PR Closes in GitHub Actions
Run a cleanup job on the pull_request closed event, keyed on the same PR number you deployed to, so merged and abandoned PRs free their resources.
The closed type fires for both merges and abandons. Use the same per-PR identifier from deploy time to target the exact environment, then run your destroy command.
Steps
- Trigger on
pull_requesttypeclosed. - Recompute the per-PR name from
github.event.pull_request.number. - Run the destroy command for that environment.
Workflow
.github/workflows/preview-teardown.yml
on:
pull_request:
types: [closed]
jobs:
teardown:
runs-on: ubuntu-latest
env:
PREVIEW_NAME: pr-${{ github.event.pull_request.number }}
steps:
- uses: actions/checkout@v4
- run: ./destroy-preview.sh --name "$PREVIEW_NAME"Gotchas
closedcovers both merge and close, so one job handles every exit path.- Make the destroy step idempotent so a re-run on an already-deleted environment still succeeds.
Related guides
How to Deploy a Preview Environment Per Pull Request in GitHub ActionsStand up an ephemeral preview environment for every pull request in GitHub Actions by triggering on pull_requ…
How to Clean Up Stale Preview Environments on a Schedule in GitHub ActionsReap orphaned or expired preview environments with a scheduled GitHub Actions workflow that lists open PRs an…