Environments Recommended
Delete preview environments on time
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 to do it
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.
Example
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"
How to check
The nightly job lists no preview older than 72 hours. Close a test pull request, and its environment is gone within 1 hour.
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.