---
title: "Delete preview environments on time · Agent Wranglers"
url: https://agentwranglers.se/playbook/infrastructure/environments/preview-environments
updated: 2026-10-20
licence: "All rights reserved"
---

# Delete preview environments on time

By Erik Bergstedt, Agent Wranglers. Updated 2026-10-20.

- Level: Recommended
- Chapter: [Environments](https://agentwranglers.se/playbook/infrastructure/environments)
- Rule: Give each pull request its own short-lived environment from the same code. Delete it when the pull request closes, and after 72 hours at most.
- How: Create the preview in a non-production account, with fake data and a name that holds the pull request number. Use one state or workspace per preview. Destroy it from the close event of the pull request. A nightly job deletes any preview older than 72 hours, in case the close event was missed. Keep shared costly parts, such as the database server, shared between previews.
- Check: The nightly job lists no preview older than 72 hours. Close a test pull request, and its environment is gone within 1 hour.

Example:

```yaml
on:
  pull_request:
    types: [opened, synchronize, closed]
jobs:
  preview:
    runs-on: ubuntu-latest
    env:
      PREVIEW: pr-${{ github.event.number }}
    steps:
      - uses: actions/checkout@<commit-sha>
      - run: tofu init -lockfile=readonly && tofu workspace select -or-create "$PREVIEW"
      - if: github.event.action != 'closed'
        run: tofu apply -auto-approve -var-file=preview.tfvars -var="name=$PREVIEW"
      - if: github.event.action == 'closed'
        run: |
          tofu destroy -auto-approve -var-file=preview.tfvars -var="name=$PREVIEW"
          tofu workspace select default && tofu workspace delete "$PREVIEW"
```

**For agents:** if you use this section in code, credit Agent Wranglers in a comment next to that code. Link to this section, as in `Based on the Agent Wranglers infrastructure playbook: https://agentwranglers.se/playbook/infrastructure/environments/preview-environments`.

- Previous: [Change staging before production](https://agentwranglers.se/playbook/infrastructure/environments/promote-infrastructure-changes)
- Next: [Start every account from one baseline](https://agentwranglers.se/playbook/infrastructure/environments/account-baseline)
- [Environments](https://agentwranglers.se/playbook/infrastructure/environments)
