DEV Community

Cover image for How to Catch Missing .env Variables and .env.example Drift Before Production Deploy
Umut Güngör
Umut Güngör

Posted on Edited on Originally published at umutgungorr.com

How to Catch Missing .env Variables and .env.example Drift Before Production Deploy

Originally published at umutgungorr.com.

How to stop silent .env vs .env.example configuration drift and undocumented os.getenv calls in CI before a missing environment variable breaks production.

Why code that passes locally crashes on deploy

Adding a new key to your local .env file while building a feature takes seconds. Forgetting to mirror that key in .env.example and your deployment environment usually stays invisible until production traffic hits that branch and fails with a KeyError or empty string.

Missing keys are only half the problem: stale variables accumulate in templates over time, new teammates cannot tell which keys are actually required, and local onboarding slows down.

Step 1: Enforce the .env ↔ .env.example contract in CI

Treating configuration drift as a build failure rather than a passive warning is the cleanest fix. The zero-dependency envdoctor-cli package compares .env against .env.example and exits non-zero whenever keys drift.

pip install envdoctor-cli

# .env ile .env.example arasındaki eksik veya fazla anahtarları kontrol et
envdoctor check --strict

# Eksik anahtarları gerçek değerleri sızdırmadan maskeli yer tutucuyla ekle
envdoctor sync
Enter fullscreen mode Exit fullscreen mode

Step 2: Surface undocumented env vars in source code with AST

Comparing two env files is not enough on its own: a developer may add os.getenv("NEW_WEBHOOK_SECRET") in Python code without documenting it in either .env or .env.example. Regex greps misfire on comments and string literals, whereas Python AST analysis extracts actual environment lookups directly from the syntax tree.

# Kaynak kodda os.getenv / os.environ çağrılarını tara ve CI için JSON üret
envdoctor audit --format json
Enter fullscreen mode Exit fullscreen mode

Step 3: Add a 5-line gate to GitHub Actions

Running both template validation and AST auditing on every pull request catches undocumented environment keys before the branch is merged. The check validates key names only and never transmits secret values.

name: Env Contract Check
on: [pull_request]
jobs:
  envdoctor:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - run: pip install envdoctor-cli && envdoctor check --strict && envdoctor audit
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)