💻 Automated .env Cleanup Script
Detect unused and undocumented environment variables in your project
#!/usr/bin/env python3
import os
import re
from pathlib import Path
def find_env_sins(project_root='.', env_file='.env'):
"""
Find unused environment variables in your codebase.
Returns: List of potentially unused variables
"""
# Load current environment variables
env_path = Path(project_root) / env_file
if not env_path.exists():
return []
with open(env_path, 'r') as f:
env_content = f.read()
# Extract variable names (handles comments and empty lines)
env_vars = set()
for line in env_content.split('\n'):
line = line.strip()
if line and not line.startswith('#'):
match = re.match(r'^([A-Z_][A-Z0-9_]*)=', line)
if match:
env_vars.add(match.group(1))
# Search for usage in code files
used_vars = set()
code_extensions = {'.py', '.js', '.ts', '.java', '.go', '.rb', '.php'}
for file_path in Path(project_root).rglob('*'):
if file_path.suffix in code_extensions and file_path.is_file():
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
for var in env_vars:
# Look for os.getenv, process.env, or direct variable usage
patterns = [
f'os\.getenv\(["\']{var}["\']\)',
f'process\.env\.{var}',
f'\${var}\b',
f'env\["{var}"\]'
]
if any(re.search(pattern, content) for pattern in patterns):
used_vars.add(var)
except:
continue
# Return unused variables
unused_vars = env_vars - used_vars
return sorted(unused_vars)
# Usage example:
if __name__ == "__main__":
unused = find_env_sins()
if unused:
print("Potentially unused environment variables:")
for var in unused:
print(f" - {var}")
else:
print("No unused variables found!")
The Problem: Your .env File is a Lie
Let's be honest. Your .env file started with the best intentions. "I'll keep this clean," you said. "I'll document everything," you promised. Then came the third-party service integration that needed `API_KEY` and `API_SECRET`. Then the staging environment required `STAGING_DB_URL`. Then Bob from DevOps left the company, but his legacy variable `BOBS_SPECIAL_FLAG=true` remains, haunting your codebase like a ghost in the machine.
Why does this happen? Because deleting an environment variable feels like defusing a bomb. You're never quite sure if some obscure cron job or legacy microservice is still using `REDIS_HOST_OLD`. So you leave it. You accumulate. Your .env file becomes an archaeological dig of your project's history, with layers of deprecated variables forming sedimentary rock atop your actual configuration.
The absurdity peaks during onboarding. "Just copy the .env.example," you tell the new hire, knowing full well the real .env has 47 additional variables that are "sort of important." They spend their first day asking, "What's `LEGACY_AUTH_ENDPOINT`?" and you respond, "Oh, we don't use that anymore. Probably. Just leave it there." This is how configuration debt is born—not with a bang, but with a whispered "probably."
The Solution: Automated Absolution
I built .env Confession Booth to solve this exact problem. It's not just another linter—it's an intervention for your configuration files. The tool approaches your messy .env with the solemnity of a priest hearing confession, but with the practical output of a senior developer who's tired of your nonsense.
Here's how it works at a high level: The tool scans your .env files (and optionally your codebase) to identify three categories of sins: Duplicates (the same variable defined multiple times), Unused Variables (variables that aren't referenced in your code), and Deprecated Patterns (like variables with `_OLD` or `_LEGACY` suffixes that scream "danger"). It doesn't judge you—well, it does a little—but it provides actionable, automated cleanup suggestions.
Despite the humorous framing, this is genuinely useful. The "confessional report" gives you a clear, prioritized list of issues. The "penance options" are actually sensible cleanup commands. And the "forgiveness mode" is just smart engineering: it creates backups before making changes, because even automated absolution should come with a safety net.
How to Use It: Your Path to Redemption
Getting started is simpler than explaining to your team why the staging environment is down because of a missing `SLACK_WEBHOOK_URL` variable from 2018. First, install it globally via npm:
npm install -g env-confession-boothThen, navigate to your project and run the confession command:
env-confess scanYou'll be presented with a report of your sins. Here's a snippet from the actual scanning logic that identifies duplicate variables:
// From the scanner module
function findDuplicates(envVars) {
const seen = new Map();
const duplicates = [];
envVars.forEach(variable => {
const key = variable.key.toUpperCase();
if (seen.has(key)) {
duplicates.push({
key: variable.key,
locations: [seen.get(key), variable.lineNumber]
});
} else {
seen.set(key, variable.lineNumber);
}
});
return duplicates;
}Check out the full source code on GitHub to see how it handles unused variable detection and the interactive confession interface.
Key Features: Your Configuration Therapy Session
- Scans .env files for duplicates and unused variables: It reads your .env files and optionally parses your codebase to find variables that are defined but never used. No more guessing if `TWILIO_SID` is still relevant.
- Generates a 'confessional report' of your configuration sins: Get a beautifully formatted (and slightly judgmental) report that categorizes your sins by severity. Duplicate variables are "venial sins," while completely unused production database URLs are "mortal sins."
- Auto-suggests cleanup commands with humorous penance options: After confession comes penance. The tool suggests specific commands to fix issues, like `env-confess clean --duplicates` or `env-confess forgive --backup-first`. The humor makes the medicine go down easier.
- Optional 'forgiveness mode' that backs up before making changes: Enable forgiveness mode, and the tool will create timestamped backups of your .env files before making any changes. Because even salvation should have a rollback plan.
Conclusion: Cleanse Your Codebase
In the end, .env Confession Booth isn't just about cleaning up variables—it's about reclaiming your project's sanity. Every deprecated variable you remove is one less mystery for the next developer. Every duplicate you eliminate is one less source of subtle, hair-pulling bugs. The tool brings visibility to the dark corners of your configuration and gives you the power to fix what you find.
So try it out: https://github.com/BoopyCode/env-var-confession-booth-1767417473. Run it on your oldest, most neglected project. Confess your configuration sins. And may your penance be light and your .env files forever clean.
Remember: A clean .env file is a sign of a developer who has their life together. Or at least, is good at faking it.
Quick Summary
- What: .env Confession Booth is a CLI tool that scans your .env files for duplicates, unused variables, and other configuration sins, then helps you clean them up with automated suggestions and backups.
💬 Discussion
Add a Comment