123DevOps··5 min read

Ephemeral environments per Pull Request: a full environment for every PR (that deletes itself)

How to create per-PR preview environments with Argo CD ApplicationSet, automatic URLs, safe test data, and cost controls using quotas, TTLs, and scale-to-zero.

CI/CD

“It works on my machine” and “wait, is someone using staging?” are two phrases that disappear once every Pull Request gets its own environment: a copy of the application, with its own URL, created automatically when the PR opens and destroyed when it closes.

Ephemeral (or preview) environments change code review: the reviewer clicks a link and actually tests the feature; the product team validates it before the merge; end-to-end tests run against an isolated environment instead of fighting ten other PRs for staging.

How it works (overview)

  1. The PR is opened (or gets a label such as preview).
  2. CI builds the image tagged with the commit SHA.
  3. A generator creates a namespace and an application for that PR.
  4. An Ingress exposes the application at pr-123.preview.example.com.
  5. A comment on the PR shows the link.
  6. When the PR is closed, everything is removed.

With Argo CD: ApplicationSet and the Pull Request generator

Argo CD’s ApplicationSet has a generator that queries open PRs on GitHub, GitLab, Bitbucket, or Gitea and creates an Application for each one:

apiVersion: argoproj.io/v1alpha1
kind: ApplicationSet
metadata:
  name: api-previews
  namespace: argocd
spec:
  goTemplate: true
  generators:
    - pullRequest:
        github:
          owner: your-org
          repo: api
          tokenRef:
            secretName: github-token
            key: token
          labels:
            - preview          # only PRs with this label get an environment
        requeueAfterSeconds: 300
  template:
    metadata:
      name: 'api-pr-{{.number}}'
      finalizers:
        - resources-finalizer.argocd.argoproj.io  # deletes the resources along with the Application
    spec:
      project: previews
      source:
        repoURL: https://github.com/your-org/api
        targetRevision: '{{.head_sha}}'
        path: deploy/preview
        kustomize:
          nameSuffix: '-pr-{{.number}}'
          images:
            - 'ghcr.io/your-org/api:{{.head_sha}}'
      destination:
        server: https://kubernetes.default.svc
        namespace: 'preview-pr-{{.number}}'
      syncPolicy:
        automated:
          prune: true
          selfHeal: true
        syncOptions:
          - CreateNamespace=true

When the PR is closed (or loses the label), the generator removes the Application and the finalizer deletes the resources. One detail: the namespace created by CreateNamespace=true is not deleted automatically — include a Namespace resource in the preview manifests themselves or run a periodic cleanup job.

If you use Flux, you get the same result from a pipeline that creates per-PR Kustomizations, or from the Flux Operator with its set resources. Outside Kubernetes, platforms such as Vercel and Netlify offer out-of-the-box previews for frontends.

URLs and certificates

  • A wildcard DNS record (*.preview.example.com) pointing to the Ingress Controller;
  • A wildcard certificate via cert-manager (DNS-01 challenge);
  • The Ingress host set from the PR number, generated by the preview overlay.

And a CI step that comments the link on the PR:

gh pr comment "$PR_NUMBER" --edit-last --body \
  "🚀 Preview: https://pr-${PR_NUMBER}.preview.example.com" \
  || gh pr comment "$PR_NUMBER" --body \
  "🚀 Preview: https://pr-${PR_NUMBER}.preview.example.com"

The data problem

An environment without data is good for testing almost nothing. The options, from simplest to most sophisticated:

  1. Ephemeral database with seed data: a small Postgres in the namespace itself, populated by a script with fictitious data. Full isolation and low cost.
  2. Schema per PR in a shared staging database: fewer resources, but watch out for conflicting migrations.
  3. Databases with branching (some managed Postgres providers create instant copy-on-write copies): realistic data in seconds.

One non-negotiable rule: no production data containing personal information in previews. Besides the leak risk, it conflicts with privacy laws such as Brazil’s LGPD or the GDPR. Use synthetic or anonymized data.

For external dependencies (payment gateways, partner APIs), point to vendor sandboxes or mocks — and never give a preview production credentials.

Keeping costs under control

Dozens of open PRs can mean dozens of copies of the application. Without controls, previews become one of the biggest line items on the bill — and an easy target for zombie hunters.

Per-namespace quotas

apiVersion: v1
kind: ResourceQuota
metadata:
  name: preview-limits
spec:
  hard:
    requests.cpu: "2"
    requests.memory: 4Gi
    limits.memory: 8Gi
    pods: "20"

Other levers

  • Opt-in by label: not every PR needs an environment (dependency bumps, documentation).
  • One replica, minimal resources: previews don’t need high availability.
  • Scale to zero outside business hours and after a few hours without traffic.
  • TTL: previews for PRs with no activity for X days are removed (and recreated if the PR changes again).
  • Spot nodes dedicated to previews — interruptions are tolerable here.
  • A cap on concurrent previews per repository.
  • Cost tags (environment=preview, pr=123) to measure how much previews cost per month and compare that with the value they deliver.

Isolation and security

  • NetworkPolicies preventing previews from reaching staging or production namespaces;
  • A separate project in Argo CD (previews) allowed to create resources only in preview-* namespaces;
  • A separate cluster (or virtual clusters with vCluster) when the preview needs broader permissions, such as installing CRDs;
  • Authentication in front of the preview (SSO on the Ingress) if the feature can’t be public yet;
  • Be careful with PRs from forks in public repositories: don’t create environments or expose secrets for unreviewed code.

Measuring whether it’s worth it

  • Environment creation time (goal: a few minutes after the push);
  • Usage rate: how many previews were accessed at least once;
  • Bugs found before the merge that previously only showed up in staging;
  • Total monthly cost of previews and average cost per PR.

Checklist

  • PR generator creating and removing environments automatically
  • Wildcard DNS and certificate configured
  • Preview link commented on the PR
  • Synthetic data — never personal production data
  • Quotas, TTL, and scale-to-zero enabled
  • NetworkPolicies isolating previews from staging and production
  • Preview costs measured by tag

A good preview environment turns code review into product review — and deletes itself before it turns into cost.

Get updates on new posts and stay in the loop!