Skip to content
Automation

Env File Validator Script: Catch Missing Keys & Secret Leaks in Python (2027)

Copy-paste a zero-dependency Python env file validator script to catch missing .env keys, broken quotes, secret leaks, and CI drift with --dry-run in 2027.

Updated: 11 min read 1 views
Share: Facebook X LinkedIn WhatsApp

A zero-dependency env file validator script stops broken deployments, missing configuration keys, and accidental credential leaks in .env.example before code ever reaches production. Every engineering team runs into the same silent failure loop: a developer adds a new API key to their local .env file, pushes the feature branch, and forgets to update .env.example—or worse, pastes a real Stripe or AWS token into the example template by mistake.

Runtime schema validators like Pydantic or Zod catch missing variables only after a container boots and crashes. Built for Linux, macOS, and CI runners using Python 3.10+, the single-file script below compares .env against .env.example, detects duplicate keys and unterminated quotes, flags real-looking secrets inside tracked example files, verifies .gitignore coverage via git check-ignore, supports a safe --dry-run self-test and --json output, and emits native GitHub Actions annotations.

Key Takeaways & Script Specs

  • Runtime & Dependencies: Python 3.10+ standard library only (re, pathlib, subprocess, argparse, json)—zero pip packages required.
  • Validation Checks: Key parity (missing/extra keys), duplicate key definitions, unterminated quotes, secret-pattern leaks in .env.example, and Git ignore verification.
  • Output Formats: Human-readable terminal report, machine-readable --json, and --format github inline PR annotations.
  • Safety Controls: Never prints raw secret values to stdout/logs (masks all findings), supports --example-only for CI runners, and includes a built-in --dry-run test.

Why Runtime Env Validation Alone Fails Teams in 2027

Most applications validate environment variables at startup using libraries like pydantic-settings, envalid, or Zod. While runtime validation protects production pods from booting with an undefined DATABASE_URL, it operates far too late in the software lifecycle. It cannot warn a developer during a local commit that they forgot to document a new feature flag in .env.example, nor can it catch an unterminated single quote that causes python-dotenv and Docker Compose to parse two completely different values from the same line.

Even more dangerous is secret leakage through template files and misconfigured ignore rules. If someone commits .env.local or .env.production because .gitignore only listed .env, Git tracks the credentials permanently in history. By combining strict syntax linting with Git’s native git-check-ignore documentation and gitignore pattern precedence rules, a pre-commit and CI validator catches both configuration drift and secret exposure in under 50 milliseconds.

Architecture and Validation Pipeline

Our validator runs a deterministic five-stage inspection pipeline without ever printing sensitive secret values to terminal logs or CI output:

+-------------------------------------------------------------------+

|  1. Parse .env.example & Optional .env (unless --example-only)    |
|---|
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|  2. Diff Key Parity                                               |
|     - In .env.example but missing from .env -> ERROR              |
|     - In .env but undocumented in .env.example -> WARNING/ERROR   |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|  3. Scan .env.example for Live Credential Patterns                |
|     - AWS AKIA..., GitHub ghp_/github_pat_, Stripe sk_live_, etc. |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|  4. Verify Git Ignore Status (git check-ignore / git ls-files)    |
|     - Fail immediately if .env is tracked or unignored in Git     |
+---------------------------------+---------------------------------+
                                  |
                                  v
+-------------------------------------------------------------------+
|  5. Emit Text, --json, or GitHub ::error:: Annotations (Exit 0/1) |
+-------------------------------------------------------------------+

This pre-flight check slots cleanly into GitHub Actions CI/CD pipelines right before your build and test steps. If your repository deploys via a Python GitHub webhook listener, validating .env.example on every pull request guarantees your production host never pulls code expecting an undocumented environment variable.

Comparing .env Validation Approaches in 2027

Before adding a new linter to your repository, compare how the four standard environment validation options handle key drift, syntax bugs, and CI integration.

Validation MethodChecks .env vs .env.exampleDetects Secret LeaksChecks .gitignoreZero Dependencies
Runtime Zod / PydanticNo (app boot only)NoNoNo (app package)
dotenv-linter (Rust CLI)Partial (schema compare)NoNoNo (external binary)
Gitleaks / TruffleHogNoYes (full repo scan)NoNo (Go binary)
Python Env Validator ScriptYes (bidirectional parity)Yes (example-file scan)Yes (git check-ignore)Yes (Python stdlib)

You can still pair this lightweight script with dedicated free developer CLI tools like gitleaks for deep commit-history scanning, while relying on Python’s zero-dependency validator for fast pre-commit and pull-request gates.

Prerequisites and Repository Setup

Because the script uses only Python 3.10+ standard library modules, you do not need a virtual environment or pip install. Place the script inside your project’s scripts/ directory (or a shared ~/bin/ folder) so both local developers and CI runners can invoke it directly:

mkdir -p scripts
# Save env_validator.py inside scripts/env_validator.py

Note that in GitHub Actions or GitLab CI, your real .env file is intentionally absent from the repository—so pass --example-only in CI to lint .env.example for duplicates, syntax errors, and accidental live credentials.

Complete Production Python Env File Validator Script

Save the following script as scripts/env_validator.py. It parses dotenv syntax strictly, checks bidirectional key parity, scans .env.example against common credential regexes (AWS, GitHub, Stripe, OpenAI/Anthropic-style keys, private key headers), verifies .gitignore protection, and includes a built-in --dry-run self-test.

#!/usr/bin/env python3
"""
Production Env File Validator Script (2027)
Zero-dependency Python CLI that checks .env vs .env.example parity,
detects duplicate keys and broken quotes, flags real secrets in example
files, verifies .gitignore coverage, and emits GitHub Actions annotations.
"""

import argparse
import json
import logging
import re
import subprocess
import sys
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Dict, List, Optional, Tuple

logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger("env_validator")

KEY_RE = re.compile(r"^(?:export\s+)?([A-Za-z_][A-Za-z0-9_])\s=\s*(.*)$")

SECRET_PATTERNS: List[Tuple[str, re.Pattern]] = [
("AWS Access Key", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
("GitHub Token", re.compile(r"\b(?:ghp|gho|ghu|ghs)[A-Za-z0-9]{20,}\b")),
("GitHub Fine-Grained PAT", re.compile(r"\bgithub_pat[A-Za-z0-9_]{20,}\b")),
("Stripe Live Secret", re.compile(r"\bsk_live_[A-Za-z0-9]{16,}\b")),
("OpenAI/API Secret Key", re.compile(r"\bsk-(?:proj-)?[A-Za-z0-9_-]{24,}\b")),
("Private Key Header", re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----")),
]

@dataclass
class Finding:
severity: str  # error | warning
file: str
line: int
code: str
message: str

def parse_env_file(path: Path) -> Tuple[Dict[str, Tuple[int, str]], List[Finding]]:
"""Parse a .env file, flagging syntax errors, unclosed quotes, and duplicates."""
entries: Dict[str, Tuple[int, str]] = {}
findings: List[Finding] = []
fname = str(path)

for idx, raw_line in enumerate(path.read_text(encoding="utf-8", errors="replace").splitlines(), start=1):
    stripped = raw_line.strip()
    if not stripped or stripped.startswith("#"):
        continue

    match = KEY_RE.match(stripped)
    if not match:
        findings.append(
            Finding("error", fname, idx, "invalid-syntax", "Line does not match KEY=VALUE syntax.")
        )
        continue

    key, raw_val = match.group(1), match.group(2).strip()
    if key in entries:
        prev_line = entries[key][0]
        findings.append(
            Finding("error", fname, idx, "duplicate-key", f"Duplicate key '{key}' (first defined on line {prev_line}).")
        )

    # Check quote balance
    if raw_val.startswith(("'", '"')):
        quote_char = raw_val[0]
        if len(raw_val) < 2 or not raw_val.endswith(quote_char):
            findings.append(
                Finding("error", fname, idx, "unterminated-quote", f"Key '{key}' opens a {quote_char} quote without closing it.")
            )
    elif " " in raw_val and "#" not in raw_val:
        findings.append(
            Finding("warning", fname, idx, "unquoted-spaces", f"Key '{key}' contains spaces without quotes.")
        )

    entries[key] = (idx, raw_val)

return entries, findings

def check_example_secrets(path: Path, entries: Dict[str, Tuple[int, str]]) -> List[Finding]:
"""Ensure .env.example does not contain real credentials."""
findings: List[Finding] = []
fname = str(path)
for key, (line_no, val) in entries.items():
for label, pattern in SECRET_PATTERNS:
if pattern.search(val):
findings.append(
Finding(
"error",
fname,
line_no,
"secret-in-example",
f"Key '{key}' in {fname} matches {label} pattern. Replace with a placeholder.",
)
)
break
return findings

def check_git_safety(env_path: Path) -> List[Finding]:
"""Verify .env is neither tracked by Git nor unignored."""
findings: List[Finding] = []
if not (Path(".git").exists() or subprocess.run(["git", "rev-parse", "--git-dir"], capture_output=True).returncode == 0):
return findings

fname = str(env_path)
tracked = subprocess.run(
    ["git", "ls-files", "--error-unmatch", fname],
    capture_output=True,
    text=True,
    check=False,
)
if tracked.returncode == 0:
    findings.append(
        Finding("error", fname, 1, "tracked-env-file", f"'{fname}' is tracked by Git! Run 'git rm --cached {fname}'.")
    )
    return findings

if env_path.is_file():
    ignored = subprocess.run(
        ["git", "check-ignore", "-q", fname],
        capture_output=True,
        check=False,
    )
    if ignored.returncode != 0:
        findings.append(
            Finding("warning", fname, 1, "unignored-env-file", f"'{fname}' is not matched by .gitignore.")
        )
return findings

def validate(
env_path: Path,
example_path: Path,
example_only: bool,
strict: bool,
) -> List[Finding]:
"""Run all validation checks and return sorted findings."""
findings: List[Finding] = []
if not example_path.is_file():
return [Finding("error", str(example_path), 1, "missing-example", f"Example file '{example_path}' not found.")]

example_entries, ex_findings = parse_env_file(example_path)
findings.extend(ex_findings)
findings.extend(check_example_secrets(example_path, example_entries))

if example_only:
    return findings

if not env_path.is_file():
    findings.append(
        Finding("error", str(env_path), 1, "missing-env", f"Local env file '{env_path}' not found (pass --example-only in CI).")
    )
    return findings

env_entries, env_findings = parse_env_file(env_path)
findings.extend(env_findings)
findings.extend(check_git_safety(env_path))

for key, (line_no, _) in example_entries.items():
    if key not in env_entries:
        findings.append(
            Finding("error", str(env_path), 1, "missing-key", f"Key '{key}' (from {example_path}:{line_no}) is missing in {env_path}.")
        )

for key, (line_no, _) in env_entries.items():
    if key not in example_entries:
        sev = "error" if strict else "warning"
        findings.append(
            Finding(sev, str(env_path), line_no, "undocumented-key", f"Key '{key}' in {env_path} is missing from {example_path}.")
        )

return findings

def run_dry_run() -> int:
"""Validate synthetic in-memory samples to verify rules without touching project files."""
import tempfile

sample_example = "APP_URL=http://localhost:3000\nAPI_KEY=your-key-here\n"
sample_env = "APP_URL=http://localhost:3000\nEXTRA_FLAG=1\n"
with tempfile.TemporaryDirectory() as tmp:
    tmp_dir = Path(tmp)
    ex = tmp_dir / ".env.example"
    env = tmp_dir / ".env"
    ex.write_text(sample_example, encoding="utf-8")
    env.write_text(sample_env, encoding="utf-8")
    results = validate(env, ex, example_only=False, strict=False)
    logger.info("[DRY-RUN] Simulated %d finding(s):", len(results))
    for item in results:
        logger.info("[DRY-RUN] %s [%s] %s", item.severity.upper(), item.code, item.message)
return 0

def emit_output(findings: List[Finding], fmt: str) -> None:
"""Print findings in text, JSON, or GitHub Actions annotation format."""
if fmt == "json":
print(json.dumps([asdict(f) for f in findings], indent=2))
return

if fmt == "github":
    for f in findings:
        level = "error" if f.severity == "error" else "warning"
        print(f"::{level} file={f.file},line={f.line},title={f.code}::{f.message}")
    return

if not findings:
    print("OK: All environment checks passed.")
    return

for f in findings:
    print(f"[{f.severity.upper()}] {f.file}:{f.line} ({f.code}) - {f.message}")

def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Validate .env vs .env.example parity, syntax, and secret safety."
)
parser.add_argument("--env", default=".env", help="Path to local .env file (default: .env)")
parser.add_argument("--example", default=".env.example", help="Path to .env.example template")
parser.add_argument(
"--example-only",
action="store_true",
help="Validate only .env.example (recommended for CI runners)",
)
parser.add_argument(
"--strict",
action="store_true",
help="Treat warnings (such as undocumented keys in .env) as errors",
)
parser.add_argument(
"--format",
choices=("text", "json", "github"),
default="text",
help="Output format (default: text)",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Run a self-contained validation simulation without reading project files",
)
return parser.parse_args()

def main() -> int:
args = parse_args()
if args.dry_run:
return run_dry_run()

findings = validate(
    env_path=Path(args.env),
    example_path=Path(args.example),
    example_only=args.example_only,
    strict=args.strict,
)
emit_output(findings, args.format)
has_errors = any(f.severity == "error" for f in findings)
has_warnings = any(f.severity == "warning" for f in findings)
if has_errors or (args.strict and has_warnings):
    return 1
return 0

if name == "main":
sys.exit(main())

Test the validator’s synthetic detection rules immediately with --dry-run, then run a live check against your repository:

chmod +x scripts/env_validator.py
python3 scripts/env_validator.py --dry-run
python3 scripts/env_validator.py --env .env --example .env.example --strict

Integrating With Pre-Commit Hooks and GitHub Actions

Because local Git hooks can be bypassed with --no-verify, enforce validation in both places. Add a local hook in .pre-commit-config.yaml and a CI gate using the GitHub Actions workflow syntax:

# .github/workflows/env-check.yml
name: Validate Environment Template
on:
  pull_request:
    paths:
      - ".env*"
      - "scripts/env_validator.py"
  push:
    branches: ["main"]

jobs:
  env-lint:
runs-on: ubuntu-latest
steps

Team MyScrpts

Team MyScrpts is the editorial and engineering collective behind myscrpts.com — publishing tested PHP, JavaScript, Python, and Bash scripts, automation workflows, WordPress templates, and AI developer tools.

Leave a Reply

Your email address will not be published. Required fields are marked *

Stay ahead of the curve. Zero spam.

Get our weekly curation of tested scripts, DevOps blueprints, and new dev tools.