Platform Engineering · Lesson 194

Preview Environments and Environment Management: Ephemeral, Seeded, and Cleaned Up

Shared staging environments become queues and arguments: one team's broken change blocks everyone, and nobody knows what is deployed. Preview environments (ephemeral environments) give every pull request its own short-lived copy of the service and its dependencies, with a URL reviewers can open, built from the same definitions as production and deleted automatically when the pull request closes. Around them sits environment management: a clear set of long-lived environments with defined purposes, configuration differences kept small and explicit, realistic but safe seed data, and cost controls. This lesson follows one pull request through its preview, and shows two failures: previews nobody deleted, and a preview seeded with a copy of production customer data.

Difficulty: Advanced · Know this first: Lesson 192, Lesson 187

What you will learn

By the end of this lesson you can work at four levels:

This page teaches it with a plain-language analogy, an animated diagram with normal and failure scenarios, a simulator, a quiz, basic, intermediate, advanced, and master checks, the expert detail ("Go deeper"), a production incident, a hands-on lab with commands and their output, and a production design exercise.

Run it as:

When it breaks, I check

One thing to remember

Where the time goes

This bar adds up minutes of pipeline and environment work for one pull request. It is a worked example, not a measurement. The seed data and teardown hops decide whether previews are safe and affordable.

Try it: run previews for 40 pull requests a day

Pick how previews are torn down, what data they hold, and how dependencies are provided. The readouts show the monthly cost, the number of previews alive, and the exposure risk.

~30previews alive
$1.4ka month
nonepersonal data exposed if a URL leaks

Check yourself

Three questions. No score is saved anywhere — this is just you against the material.

Basic to master

Environment management grows in four levels: using previews, building them, keeping them safe and cheap, and running the environment strategy.

Basic — Use previews

At the basic level you review changes in their preview.

  • The preview URL and status on the pull request.
  • What the preview shares with other environments and what is its own.
  • When it will be deleted.

Where it breaks: sharing a preview URL outside the company "just for a demo".

Try it: Basic

A partner wants to see your feature. Do you send them the preview URL?

Now do it: Check whether your previews require login.

Intermediate — Build previews

At the intermediate level you create previews from pull requests.

  • An Argo CD ApplicationSet pull-request generator (or a CI job) with the production chart and a preview overlay.
  • A namespace per preview with quota, network policies, and labels.
  • Migrations and seed scripts run on a fresh database.

Try it: Intermediate

Which dependencies should a preview copy?

Now do it: List your service's dependencies and choose copy, share, or mock.

Advanced — Safe and cheap

At the advanced level previews cannot leak data or money.

  • Synthetic or reviewed-anonymised data only; no route or credential to production.
  • SSO on every preview URL; wildcard certificates.
  • Deletion on close, an expiry reaper, cost by namespace, scale to zero when idle.

Try it: Advanced

A preview created a cloud database outside Kubernetes. How do you make sure it is deleted?

Now do it: Find one external resource your previews create.

Master — An environment strategy

At the master level environments are a deliberate, small set.

  • Previews per pull request; one long-lived integration environment; staging only where it adds something (performance, partner testing); production.
  • Configuration differences listed and minimised; promotion by digest between them.
  • Non-production cost and data reviewed like production's.

Trade-off: previews cost compute per pull request and remove the shared-staging queue; most teams find the time saved worth far more than the cost.

Try it: Master

Your shared staging is always broken by someone. What is the usual fix?

Now do it: Count how often staging was blocked last month.

Go deeper

Previews with an Argo CD ApplicationSet: one Application per open pull request labelled "preview", from the production chart with preview values; it is deleted when the pull request closes (check the Argo CD documentation for your version).

apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata: {name: orders-previews, namespace: argocd}
spec:
  goTemplate: true
  generators:
  - pullRequest:
      github: {owner: example-org, repo: orders, labels: [preview]}
      requeueAfterSeconds: 120
  template:
    metadata: {name: 'orders-pr-{{.number}}'}
    spec:
      project: previews
      source:
        repoURL: https://github.com/example-org/orders.git
        targetRevision: '{{.head_sha}}'
        path: deploy/chart
        helm:
          valueFiles: [values.yaml, values-preview.yaml]
          parameters:
          - {name: host, value: 'pr-{{.number}}.preview.example.dev'}
          - {name: image.tag, value: '{{.head_sha}}'}
      destination: {server: https://kubernetes.default.svc, namespace: 'preview-{{.number}}'}
      syncPolicy:
        automated: {prune: true, selfHeal: true}
        syncOptions: [CreateNamespace=true]

A reaper as a backstop, for previews whose pull requests closed while the controller was unavailable (read the list before deleting anything):

now=$(date -u +%s)
kubectl get ns -l preview=true -o jsonpath='{range .items[*]}{.metadata.name} {.metadata.labels.expires-at}{"\n"}{end}' |
  while read ns exp; do [ "$exp" -lt "$now" ] && echo "expired: $ns"; done
# then, after review: kubectl delete ns 

Synthetic seed data should cover edge cases production data happens to contain (long and non-Latin names, zero and negative amounts, very large orders, missing optional fields) without containing anyone's real data. Libraries such as Faker generate plausible values; seed scripts live in the repository and run after migrations.

One time it broke

This is a composite of a failure pattern that keeps repeating; the details are illustrative. The demo that showed real customers.

Timeline

  • Months 0–6Previews restore last night's production database copy "so reviewers see realistic data". Preview URLs need no login.
  • Day 0A developer sends a preview URL to a partner for a demo, and it is posted in a public community chat.
  • Day 2The partner mentions it. The preview is deleted; all previews are purged; access logs show the customer pages were viewed from outside the company.
  • Days 2–10The exposure is assessed, reported to the regulator as required, and affected customers notified.

What changed after

Previews use generated synthetic data only, all preview hostnames sit behind single sign-on, a policy blocks database restores from production backups into non-production accounts, and demos use a dedicated environment with synthetic data.

Try it yourself, from scratch

Everything here runs on any Linux machine: your own laptop, WSL on Windows (run wsl --install in PowerShell once), or a small cloud VM. The Python needs only Python 3 and its standard library; check that you have it with python3 --version.

Before you start: A practice cluster: Docker, kind, and kubectl, then kind create cluster. Python 3 for the program.

1. Linux commands

Type each one, read what it prints, and compare it with the note above it.

  1. Create two preview namespaces labelled with their pull request, owner, and expiry (one already expired).

    Reversible

    Changes a real system: On a shared cluster, use your own kind cluster: namespace creation and deletion change the cluster.

    now=$(date -u +%s)
    kubectl create namespace preview-4127 && kubectl label ns preview-4127 preview=true pr=4127 owner=team-orders expires-at=$((now + 259200))
    kubectl create namespace preview-3990 && kubectl label ns preview-3990 preview=true pr=3990 owner=team-orders expires-at=$((now - 3600))
    kubectl get ns -l preview=true -L pr,owner,expires-at

    Options: expires-at is a Unix timestamp; labels are what the reaper and cost reports read.

    Expect: Two namespaces with their labels.

    Clean up: kubectl delete ns -l preview=true.

  2. Give the preview a quota, so one preview cannot take the cluster.

    Reversible

    kubectl create quota preview-quota -n preview-4127 --hard=requests.cpu=4,requests.memory=8Gi,pods=20
    kubectl get quota -n preview-4127

    Expect: The quota with its hard limits.

  3. Dry run of the reaper: list previews past their expiry, without deleting them.

    Read-only

    now=$(date -u +%s)
    kubectl get ns -l preview=true -o jsonpath='{range .items[*]}{.metadata.name} {.metadata.labels.expires-at}{"\n"}{end}' |
      while read ns exp; do [ "$exp" -lt "$now" ] && echo "expired: $ns"; done

    Expect: expired: preview-3990. Delete it after reading the list with kubectl delete ns preview-3990.

2. Python: previews.py

This program simulates a month of pull requests with previews, counting how many stay alive and what they cost with manual teardown and with deletion on close plus an expiry reaper. Then it generates synthetic seed customers with deliberate edge cases, and checks that no value in the seed matches a sample of production personal data. Save it as previews.py, then run it.

# previews.py
import random

random.seed(4127)                 # fixed seed: the same month and the same seed data on every run
rnd = random.Random(4127)
DAYS, PRS_PER_DAY, COST_PER_PREVIEW_DAY = 30, 40, 1.6

def month(auto):
    alive, total_days = [], 0
    for day in range(DAYS):
        alive = [(opened, closes) for opened, closes in alive
                 if not (auto and (day >= closes or day - opened >= 3))]          # deleted on close, or expired
        if not auto:
            alive = [(o, c) for o, c in alive if not (day >= c and rnd.random() < 0.08)]  # someone remembers, sometimes
        for _ in range(PRS_PER_DAY):
            alive.append((day, day + rnd.choice([0, 1, 1, 2, 3, 5])))
        total_days += len(alive)
    return len(alive), total_days * COST_PER_PREVIEW_DAY

for name, auto in (("manual teardown", False), ("delete on close + 3-day expiry", True)):
    alive, cost = month(auto)
    print(f"{name:<31} alive at month end {alive:>4}   preview cost {cost:>8,.0f} USD")
print()

FIRST = ["Ana", "Bo", "Chidinma", "Đức", "Siobhán", "Zoë", "李", "Mary-Kate"]
LAST = ["Ng", "O'Neill", "Van der Berg", "Abdul-Rahman", "Smith", "Ångström"]
def synthetic_customers(n):
    out = []
    for i in range(n):
        out.append({"id": f"c{i:04d}", "name": f"{rnd.choice(FIRST)} {rnd.choice(LAST)}",
                    "email": f"user{i:04d}@example.test",
                    "order_total": rnd.choice([0.0, 0.01, 19.99, 250.0, 99999.99])})
    out.append({"id": "c-long", "name": "A" * 120, "email": "long@example.test", "order_total": 1.0})
    return out

seed = synthetic_customers(8)
for c in seed[:4] + seed[-1:]:
    print(f"  {c['id']:<7} {c['name'][:28]:<28} {c['email']:<22} {c['order_total']:>9.2f}")
PRODUCTION_SAMPLE = {"ana.ng@gmail.com", "+44 7700 900123", "12 Hill Road"}
leaks = [v for c in seed for v in c.values() if str(v) in PRODUCTION_SAMPLE]
print(f"seed values that match production personal data: {len(leaks)}  (emails use the reserved example.test domain)")

Run it, and you should see this output:

$ python3 previews.py
manual teardown                 alive at month end  524   preview cost   16,571 USD
delete on close + 3-day expiry  alive at month end   78   preview cost    3,488 USD

  c0000   Ana Ng                       user0000@example.test      19.99
  c0001   Mary-Kate Smith              user0001@example.test       0.01
  c0002   Zoë Abdul-Rahman             user0002@example.test       0.00
  c0003   Chidinma Ångström            user0003@example.test     250.00
  c-long  AAAAAAAAAAAAAAAAAAAAAAAAAAAA long@example.test           1.00
seed values that match production personal data: 0  (emails use the reserved example.test domain)

3. What to notice

4. Advanced: every step as one Bash script

The same Linux steps, made into a real script you can keep and run again. It uses the Bash features a production script needs: functions (one per step), an array of step names, arguments to choose steps, a case for options, exit codes recorded for each step, and a trap that prints a summary even when you stop it with Ctrl+C. Make a folder for this lesson (mkdir -p ~/labs/preview-environments-and-environment-management && cd ~/labs/preview-environments-and-environment-management) and save this as lab.sh.

#!/usr/bin/env bash
# The Linux steps of "Preview Environments and Environment Management: Ephemeral, Seeded, and Cleaned Up", as one script (save it as lab.sh).
#
#   ./lab.sh          run every step, in order
#   ./lab.sh 2 4      run only steps 2 and 4
#   ./lab.sh --list   list the steps
#
# The steps share one shell, so a later step can use what an earlier one set up (a folder,
# a variable, a container): run them all in order the first time. Your own scripts should
# start with "set -euo pipefail"; this one runs teaching commands, and some of them fail on
# purpose, so it records each step's exit code instead of stopping at the first failure.

STEPS=(
  'Create two preview namespaces labelled with their pull request, owner, and expiry (one already expired).'
  'Give the preview a quota, so one preview cannot take the cluster.'
  'Dry run of the reaper: list previews past their expiry, without deleting them.'
)

step_1() {
now=$(date -u +%s)
kubectl create namespace preview-4127 && kubectl label ns preview-4127 preview=true pr=4127 owner=team-orders expires-at=$((now + 259200))
kubectl create namespace preview-3990 && kubectl label ns preview-3990 preview=true pr=3990 owner=team-orders expires-at=$((now - 3600))
kubectl get ns -l preview=true -L pr,owner,expires-at
}

step_2() {
kubectl create quota preview-quota -n preview-4127 --hard=requests.cpu=4,requests.memory=8Gi,pods=20
kubectl get quota -n preview-4127
}

step_3() {
now=$(date -u +%s)
kubectl get ns -l preview=true -o jsonpath='{range .items[*]}{.metadata.name} {.metadata.labels.expires-at}{"\n"}{end}' |
  while read ns exp; do [ "$exp" -lt "$now" ] && echo "expired: $ns"; done
}

# print a step that has to be run by hand, instead of running it
by_hand() {
  echo "  (run this one yourself: $1)"
  sed 's/^/    /'
}

RESULTS=()
run_step() {
  local n=$1 start=$SECONDS code
  printf '\n== step %d of %d: %s\n' "$n" "${#STEPS[@]}" "${STEPS[n-1]}"
  "step_$n"
  code=$?
  RESULTS+=("step $n: exit code $code, $((SECONDS - start)) s")
}

summary() {
  echo
  echo "== summary"
  local r
  for r in "${RESULTS[@]}"; do echo "  $r"; done
}

case "${1:-}" in
  -h|--help) sed -n '2,6p' "$0"; exit 0 ;;
  --list) for i in "${!STEPS[@]}"; do echo "$((i + 1)). ${STEPS[i]}"; done; exit 0 ;;
esac

[ $# -eq 0 ] && set -- $(seq 1 "${#STEPS[@]}")
for n in "$@"; do
  if ! [[ $n =~ ^[0-9]+$ ]] || (( n < 1 || n > ${#STEPS[@]} )); then
    echo "there is no step '$n'; try --list" >&2
    exit 2
  fi
done
trap summary EXIT
trap 'echo; echo "stopped with Ctrl+C"; exit 130' INT
for n in "$@"; do run_step "$n"; done

Then make it executable and run it:

chmod +x lab.sh
./lab.sh --list     # the steps
./lab.sh            # every step, then a summary of exit codes and times
./lab.sh 2 3        # only steps 2 and 3

5. Learn the basics behind it

New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.

If you remember nothing else

Design exercise

Eight teams share one staging environment that is broken most days, and want previews per pull request. Design the preview and environment strategy.

Clarifying questions to ask

How are previews created and from what definitions? What do they share and what do they copy? Where does seed data come from? How are they secured? How and when are they deleted? Which long-lived environments remain, and why?

Rough sizing

Say 8 teams, 40 pull requests a day, 12 services, a typical pull request open for 1.5 days, and a non-production budget of $4,000 a month.

Shape of the answer

Argo CD ApplicationSets with pull-request generators using each service's production chart and a preview overlay; a namespace per preview with quota, default-deny policies, and expiry labels; Postgres containers with migrations and synthetic seed scripts; shared non-production versions of services the change does not touch, mocks for third parties; SSO in front of a wildcard preview domain; E2E tests as pull request checks; deletion on close plus a nightly reaper and scale-to-zero when idle; one integration environment for merged changes, staging only for performance and partner tests; cost by namespace reported weekly.

Trade-offs to name

Previews cost compute per pull request, kept small by sharing stable dependencies and scaling to zero; synthetic data misses some real-world oddities, which is why seeds include deliberate edge cases; removing shared staging changes habits that teams may resist at first.

Failure modes and how to troubleshoot them

Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.

ScenarioWhereEffectWhat goes wrong
No teardownHop 9: TeardownBreaksTeardown is a manual step "after merging". Over six months 310 preview namespaces accumulate, each with a managed database instance and a load balancer. The non-production bill triples before a cost review finds them.
Production data in previewsHop 5: Seed dataBreaksTo make previews realistic, each one restores last night's copy of the production database. A developer shares a preview URL publicly for a partner demo; the preview has no login.

How to troubleshoot

  1. Write down the symptom and when it started: what users see, which number moved, and what changed just before (a deploy, a config change, traffic).
  2. Walk the path in order, from the first hop to the last: Pull request → Definition → Namespace → Dependencies → Seed data → Secrets → Preview URL → Tests and review → Teardown. The first hop whose evidence is wrong is where to dig.
  3. At that hop, run the read-only check from the diagram or the lab first; change nothing until the evidence points at a cause.
  4. Fix the smallest thing that restores service, or roll back the last change, and confirm the symptom is gone with the same check.
  5. Write down what you found and the check that would have caught it sooner, so the next person starts there.

References and review

The official documentation and standards behind this lesson. Versions and defaults change; when a command or field here differs from them, trust the official page.

Last updated . Next review due by November 2027. Found something out of date? Tell me.

Saved on this device, in this browser.
Next in this series · Lesson 195
PostgreSQL for Platform Engineers

I have lost count of the times a slow app turned out to be a database problem. The app code was fine. The query was not. Or the pool was empty. Or the disk was full and nobody had set an alert on it.

Go to Lesson 195 →

Or browse the full course from the Lessons index.