# Terraform workflow: ephemeral pull-request environments with automated teardown

## When

Integration testing needs real infrastructure per change: preview environments for PRs that touch Terraform or the app it deploys.

## Steps

1. PR opened: CI creates the environment. Options: `terraform workspace new pr-[number]` on a shared config, or a parameterized directory. Seed with PR-specific variables (names, tags with the PR number and TTL).
2. `terraform apply` with the PR's config. Post the key outputs (URLs, connection info) as a PR comment so reviewers can actually use the environment.
3. PR merged or closed: CI runs `terraform plan -destroy -out` and, after the standard destroy review (automated for ephemeral envs with tight scoping), applies the destroy.
4. Verify teardown: the destroy job confirms zero remaining resources for that environment. Orphaned PR environments are the cost leak.

## Rules for agents

1. Ephemeral envs must be cheap and bounded: small instance types, short TTLs, and a reaper job that destroys environments older than N days regardless of PR state. PRs get abandoned; the reaper is the backstop.
2. Never let ephemeral envs share state or backends with permanent environments. One key prefix per PR, derived from the PR number.
3. Name everything with the PR number. Untagged mystery resources from dead PRs are the number one ephemeral-env failure.
4. The destroy on PR close must be as automated as the create. A manual teardown step will be skipped under deadline pressure, every time.
5. Cost: put a budget alert on the ephemeral-env account/project. Preview environments have a way of becoming load-test environments at 3am.
