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
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.
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.
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.
Three questions. No score is saved anywhere — this is just you against the material.
Environment management grows in four levels: using previews, building them, keeping them safe and cheap, and running the environment strategy.
At the basic level you review changes in their preview.
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.
At the intermediate level you create previews from pull requests.
Try it: Intermediate
Which dependencies should a preview copy?
Now do it: List your service's dependencies and choose copy, share, or mock.
At the advanced level previews cannot leak data or money.
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.
At the master level environments are a deliberate, small set.
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.
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.
This is a composite of a failure pattern that keeps repeating; the details are illustrative. The demo that showed real customers.
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.
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.
Type each one, read what it prints, and compare it with the note above it.
Create two preview namespaces labelled with their pull request, owner, and expiry (one already expired).
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
Give the preview a quota, so one preview cannot take the cluster.
kubectl create quota preview-quota -n preview-4127 --hard=requests.cpu=4,requests.memory=8Gi,pods=20 kubectl get quota -n preview-4127
Dry run of the reaper: list previews past their expiry, without deleting them.
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"; donepreviews.pyThis 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)
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
New to a feature used above? These W3Schools pages explain each one from zero, with examples you can run in the browser.
echo, Pipes, Loops, If...Else.Eight teams share one staging environment that is broken most days, and want previews per pull request. Design the preview and environment strategy.
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?
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.
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.
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.
Each row is one way this system went wrong in the diagram's scenarios. The hop number is where to look first.
| Scenario | Where | Effect | What goes wrong |
|---|---|---|---|
| No teardown | Hop 9: Teardown | Breaks | Teardown 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 previews | Hop 5: Seed data | Breaks | To 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. |
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.