TL;DR: .env.example is supposed to document every variable your app needs, but nothing enforces it. Someone adds STRIPE_WEBHOOK_SECRET to the code and their own .env, forgets the example file, and the next deploy fails at runtime. The script below parses both files, reports missing keys, empty required values, keys that aren't in the example (usually typos), duplicate keys and broken quotes, and never prints a value. It can also check os.environ instead of a file, so the same check runs in CI where secrets come from the pipeline.
Three ways .env files break
Most dotenv bugs I've debugged fall into three buckets:
- Drift. A new variable lands in the code and in one developer's
.env, but not in.env.example. Everyone else finds out from a stack trace. - Typos.
STRIPE_WEBOOK_SECRET=...is a perfectly valid line. The app readsSTRIPE_WEBHOOK_SECRET, gets nothing, and falls back to a default or crashes later. - Shadowing. The same key appears twice, usually after a copy-paste. Most loaders silently use one of them, and it's not always the one you just edited.
A schema library can solve this, but for most projects the example file already is the schema. It just needs a checker.
The convention
- Every key the app reads is listed in
.env.example, with a placeholder value. - Keys are required by default. Mark a key optional with a
# optionalcomment on the line above it or at the end of the line. - A required key must be present and non-empty.
Here's the demo example file:
# Database
DATABASE_URL=postgres://user:pass@localhost:5432/app
REDIS_URL=redis://localhost:6379
# Payments
STRIPE_SECRET_KEY=sk_test_xxx
STRIPE_WEBHOOK_SECRET=whsec_xxx
# optional: only needed for error reporting
SENTRY_DSN=
LOG_LEVEL=info # optional
And a .env with every problem from the list above (a blank required value, a duplicate, a typo):
export DATABASE_URL="postgres://app:s3cret@db.internal:5432/app"
REDIS_URL=
STRIPE_SECRET_KEY='sk_live_should_never_be_printed'
STRIPE_WEBHOOK_SECRET=whsec_live_also_secret
STRIPE_WEBHOOK_SECRET=whsec_old_value
STRIPE_WEBOOK_SECRET=whsec_typo
The script
Standard library only: argparse, os, re, sys.
#!/usr/bin/env python3
"""Check a .env file (or the real environment) against .env.example.
Reports missing keys, empty required keys, unknown extra keys, duplicate
keys and malformed lines. Never prints a value. Stdlib only.
Exit codes: 0 = OK, 1 = problems found, 2 = usage / file error.
"""
import argparse
import os
import re
import sys
KEY_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
class Entry:
__slots__ = ("key", "value", "line", "optional")
def __init__(self, key, value, line, optional=False):
self.key, self.value, self.line, self.optional = key, value, line, optional
def parse(text):
"""Parse dotenv text. Returns (entries, errors)."""
entries, errors = [], []
lines = text.splitlines()
i, pending_optional = 0, False
while i < len(lines):
lineno, raw = i + 1, lines[i]
i += 1
line = raw.strip()
if not line:
pending_optional = False
continue
if line.startswith("#"):
if re.search(r"\boptional\b", line, re.I):
pending_optional = True
continue
if line.startswith("export "):
line = line[len("export "):].lstrip()
if "=" not in line:
errors.append(f"line {lineno}: expected KEY=value")
pending_optional = False
continue
key, rest = line.split("=", 1)
key, rest = key.strip(), rest.lstrip()
if not KEY_RE.match(key):
errors.append(f"line {lineno}: invalid key name {key!r}")
pending_optional = False
continue
optional = pending_optional
pending_optional = False
if rest[:1] in ("'", '"'):
quote = rest[0]
body = rest[1:]
# double-quoted values may span lines
while quote not in body and quote == '"' and i < len(lines):
body += "\n" + lines[i]
i += 1
if quote not in body:
errors.append(f"line {lineno}: unterminated {quote} quote for {key}")
continue
value, tail = body.split(quote, 1)
if re.search(r"#\s*optional\b", tail, re.I):
optional = True
else:
# unquoted: "#" starts a comment only at the start or after whitespace
parts = re.split(r"(?:^|\s)#", rest, maxsplit=1)
value = parts[0].strip()
comment = parts[1] if len(parts) > 1 else ""
if re.search(r"\boptional\b", comment, re.I):
optional = True
entries.append(Entry(key, value, lineno, optional))
return entries, errors
def compare(example, actual, strict=False):
"""example/actual: lists of Entry. Returns (errors, warnings)."""
errors, warnings = [], []
for name, entries in (("example", example), ("env", actual)):
seen = {}
for e in entries:
if e.key in seen:
errors.append(f"{name}: duplicate key {e.key} "
f"(lines {seen[e.key]} and {e.line})")
seen[e.key] = e.line
have = {e.key: e for e in actual}
want = {e.key: e for e in example}
for key, spec in want.items():
got = have.get(key)
if got is None:
if not spec.optional:
errors.append(f"missing required key {key}")
elif got.value == "" and not spec.optional:
errors.append(f"required key {key} is empty")
for key in have.keys() - want.keys():
msg = f"{key} is not in the example file (typo or undocumented?)"
(errors if strict else warnings).append(msg)
return sorted(errors), sorted(warnings)
def from_environ(example, environ=None):
environ = os.environ if environ is None else environ
return [Entry(e.key, environ[e.key], 0) for e in example if e.key in environ]
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--example", default=".env.example")
ap.add_argument("--env", default=".env")
ap.add_argument("--from-environ", action="store_true",
help="check os.environ instead of a .env file (CI)")
ap.add_argument("--strict", action="store_true",
help="treat keys missing from the example as errors")
args = ap.parse_args(argv)
try:
with open(args.example, encoding="utf-8") as f:
example, ex_err = parse(f.read())
if args.from_environ:
actual, env_err = from_environ(example), []
else:
with open(args.env, encoding="utf-8") as f:
actual, env_err = parse(f.read())
except OSError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
errors = [f"example: {e}" for e in ex_err] + [f"env: {e}" for e in env_err]
cmp_err, warnings = compare(example, actual, args.strict)
errors += cmp_err
for w in warnings:
print(f"WARN {w}")
for e in errors:
print(f"FAIL {e}")
source = "environment" if args.from_environ else args.env
print(f"{len({e.key for e in example})} keys in {args.example}, "
f"{len({e.key for e in actual})} in {source}: "
f"{len(errors)} error(s), {len(warnings)} warning(s)")
return 1 if errors else 0
if __name__ == "__main__":
sys.exit(main())
A few design decisions worth explaining:
- It never prints a value. Messages contain key names and line numbers only. The output of a config check ends up in CI logs, and CI logs get shared. There's a test that runs the demo and asserts none of the secret strings appear in the output.
#only starts a comment at the start of the value or after whitespace.KEY=a#bkeeps its#, and so does a URL fragment like/page#top. Many dotenv loaders behave the same way, but check yours.- Double-quoted values can span lines, which is how PEM keys usually end up in
.envfiles. Single-quoted values can't, and an unterminated quote is reported instead of swallowing the rest of the file. - Extra keys are warnings by default. A local
.envoften has personal debug flags.--strictturns them into errors for CI.
Running it
$ python3 check_env.py --example demo.env.example --env demo.env
WARN STRIPE_WEBOOK_SECRET is not in the example file (typo or undocumented?)
FAIL env: duplicate key STRIPE_WEBHOOK_SECRET (lines 4 and 5)
FAIL required key REDIS_URL is empty
6 keys in demo.env.example, 5 in demo.env: 2 error(s), 1 warning(s)
$ echo $?
1
SENTRY_DSN and LOG_LEVEL are missing from .env, but both are marked optional, so they don't fail the check. The typo is only a warning here; with --strict it becomes the third error:
$ python3 check_env.py --example demo.env.example --env demo.env --strict
FAIL STRIPE_WEBOOK_SECRET is not in the example file (typo or undocumented?)
FAIL env: duplicate key STRIPE_WEBHOOK_SECRET (lines 4 and 5)
FAIL required key REDIS_URL is empty
6 keys in demo.env.example, 5 in demo.env: 3 error(s), 0 warning(s)
In CI: check the real environment
In a pipeline there usually isn't a .env file. Secrets are injected as environment variables, and the bug you want to catch is "someone added a variable to the example and forgot to add the secret to the pipeline." --from-environ checks os.environ against the example file instead:
$ DATABASE_URL=x REDIS_URL=y STRIPE_SECRET_KEY=z \
python3 check_env.py --example demo.env.example --from-environ
FAIL missing required key STRIPE_WEBHOOK_SECRET
6 keys in demo.env.example, 3 in environment: 1 error(s), 0 warning(s)
It only looks at keys listed in the example, because a CI runner's environment is full of unrelated variables (PATH, HOME, runner metadata). As a GitHub Actions step, before the deploy job:
- name: Check required env vars
env:
DATABASE_URL: ${{ secrets.DATABASE_URL }}
REDIS_URL: ${{ secrets.REDIS_URL }}
STRIPE_SECRET_KEY: ${{ secrets.STRIPE_SECRET_KEY }}
STRIPE_WEBHOOK_SECRET: ${{ secrets.STRIPE_WEBHOOK_SECRET }}
run: python3 scripts/check_env.py --example .env.example --from-environ
Locally, the same script works as a pre-commit hook or as the first line of your dev start script, so a teammate who pulls a branch with a new variable gets a one-line message instead of a crash.
The tests
The test file (15 tests, python3 test_check_env.py) covers the parser edge cases (export, both quote styles, inline comments, a#b, multi-line values, malformed lines), the optional markers, missing/empty/extra/duplicate keys, the exit codes 0/1/2, and two subprocess runs of --from-environ with and without a required variable. The one I'd keep even if you delete the rest is the "never prints a value" test.
$ python3 test_check_env.py
...............
----------------------------------------------------------------------
Ran 15 tests in 0.040s
OK
Limits
This is a checker, not a loader, and it deliberately stays small:
- No variable expansion (
${OTHER_VAR}) and no escaped quotes inside quoted values. If your files use those, the checker still finds keys correctly in most cases, but don't use it to read values. - It checks presence, not format. If you want "must be a URL" or "must be an integer," add a small dict of validators keyed by name, and keep printing key names only.
- Dotenv dialects differ slightly between tools (Docker Compose, python-dotenv, Node's dotenv). The rules above are the common subset.
I write small, dependency-free checks like this for my own projects at infinityme.dev. Copy the script, change the convention to match your team, and let CI be the one that notices the drift.
Comments
Join the discussionNo comments yet. Be the first to comment.