π» .env Wrangler - Compare & Fix Environment Variables
Stop deployment failures by catching .env mismatches before they break your app
import os
from pathlib import Path
from typing import Dict, Set
def compare_env_files(example_path: str, local_path: str) -> Dict[str, str]:
"""
Compare .env.example with .env.local to find missing or mismatched variables
Returns: Dict with 'missing', 'different', and 'safe' keys
"""
def load_env_file(filepath: str) -> Dict[str, str]:
env_vars = {}
try:
with open(filepath, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
env_vars[key.strip()] = value.strip()
except FileNotFoundError:
print(f"β οΈ File not found: {filepath}")
return env_vars
example_vars = load_env_file(example_path)
local_vars = load_env_file(local_path)
result = {
'missing': [],
'different': [],
'safe': []
}
# Check for missing variables in local file
for key in example_vars:
if key not in local_vars:
result['missing'].append(key)
elif example_vars[key] != local_vars[key]:
# Only show differences for non-sensitive values
if not any(sensitive in key.lower() for sensitive in ['secret', 'key', 'password', 'token']):
result['different'].append(f"{key}: example='{example_vars[key]}' vs local='{local_vars[key]}'")
else:
result['safe'].append(f"{key}: [SECURE - values differ]")
return result
# Usage example:
# results = compare_env_files('.env.example', '.env.local')
# print(f"Missing variables: {results['missing']}")
# print(f"Different values: {results['different']}")
# print(f"Secure differences: {results['safe']}")
The Problem: Your Environment Variables Are Lying to You
π» .env Wrangler - Compare & Fix Environment Variables
Stop deployment failures by catching .env mismatches before they break your app
import os
from pathlib import Path
from typing import Dict, Set
def compare_env_files(example_path: str, local_path: str) -> Dict[str, str]:
"""
Compare .env.example with .env.local to find missing or mismatched variables
Returns: Dict with 'missing', 'different', and 'safe' keys
"""
def load_env_file(filepath: str) -> Dict[str, str]:
"""Safely load environment variables from a file"""
env_vars = {}
try:
with open(filepath, 'r') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
key, value = line.split('=', 1)
env_vars[key.strip()] = value.strip()
except FileNotFoundError:
print(f"β οΈ File not found: {filepath}")
return env_vars
example_vars = load_env_file(example_path)
local_vars = load_env_file(local_path)
# Find differences
missing = set(example_vars.keys()) - set(local_vars.keys())
different = {}
for key in set(example_vars.keys()) & set(local_vars.keys()):
if example_vars[key] != local_vars[key] and not example_vars[key].startswith('your_'):
different[key] = {
'example': example_vars[key],
'local': local_vars[key]
}
return {
'missing': list(missing),
'different': different,
'safe': len(missing) == 0 and len(different) == 0
}
# Usage:
# results = compare_env_files('.env.example', '.env.local')
# if not results['safe']:
# print("Fix these before deploying!")
# print(f"Missing: {results['missing']}")
# print(f"Different: {results['different']}")
Let's be honest: managing environment variables is the digital equivalent of playing telephone with state secrets. You start with a pristine .env.example file that contains all the configuration your app needs. You commit it with the solemnity of a constitutional amendment. Then the chaos begins.
Bob from backend clones the repo, copies .env.example to .env, and promptly forgets to update the database URL. Alice from frontend adds a new feature requiring API_RATE_LIMIT=100 but only updates the example file, not her local one. Meanwhile, production has values that haven't been seen since the last time anyone checked the deployment docs (circa 2019).
The result? Your staging environment thinks it's talking to a database in Frankfurt when it's actually in Ohio. Your local development sends emails to test@example.com while production happily spams your CEO. And the deployment pipeline? It fails with the cryptic error "Missing required environment variable: SENSE_OF_HUMOR" because someone thought they were being funny.
We waste hoursβnay, daysβof our lives debugging this nonsense. We've normalized the absurdity of treating configuration management like a game of "guess what I'm thinking" across multiple environments. It's time to stop the madness.
The Solution: Stop Guessing, Start Wrangling
Enter .env Wrangler, the tool that treats your environment variables with the seriousness they deserve (which is to say, it actually checks if they match). Instead of playing configuration roulette every time you deploy, this tool gives you a clear, safe view of what's different between your example file and your actual environment.
I built .env Wrangler after the third time in a month I debugged a "mysterious" production issue that turned out to be a missing REDIS_URL variable. The absurdity had reached its peak: we were building complex distributed systems but couldn't keep our configuration straight. It was like building a spaceship but forgetting to check if we had fuel.
The tool works on a beautifully simple premise: compare what you say you need (.env.example) with what you actually have (.env), and tell you the difference. No more guessing. No more "oh right, I forgot to add that variable locally." Just clear, actionable information that prevents bugs before they happen.
How to Use It: Wrangle Those Variables
Getting started is simpler than explaining to your manager why production is down because of a missing comma in an environment variable. First, install it:
# Clone the repository
git clone https://github.com/BoopyCode/env-file-fixer-1767433078.git
cd env-file-fixer-1767433078
# Install dependencies
npm install
# Run the wrangler
node index.jsThe tool automatically looks for .env.example and .env files in your current directory and compares them. Here's a snippet from the core comparison logic:
// Compare example and actual env files
function compareEnvFiles(examplePath, actualPath) {
const exampleVars = parseEnvFile(examplePath);
const actualVars = parseEnvFile(actualPath);
const missingInActual = [];
const differentValues = [];
for (const [key, exampleValue] of Object.entries(exampleVars)) {
if (!(key in actualVars)) {
missingInActual.push(key);
} else if (exampleValue !== actualVars[key] &&
!isLikelySecret(key)) {
differentValues.push({
key,
example: exampleValue,
actual: actualVars[key]
});
}
}
return { missingInActual, differentValues };
}Check out the full source code on GitHub to see how it handles secret masking, backups, and the sync functionality. The beauty is in its simplicityβit does one job and does it well, without trying to be yet another over-engineered DevOps platform.
Key Features That Actually Help
- Auto-detect missing variables: Compares
.env.examplewith your local.envand tells you exactly what's missing before your app crashes in production. - Generate safe diff reports: Shows mismatched values while automatically masking anything that looks like a secret (API keys, tokens, passwords). No more accidentally leaking credentials in screenshots.
- Create automatic backups: Before making any changes, creates a
.env.backupfile so you can always revert if something goes wrong. Because sometimes the cure is worse than the disease. - Sync with placeholders: Option to automatically add missing variables to your
.envfile with placeholder values, so at least your app won't crash while you figure out what the actual value should be.
Conclusion: Stop Debugging, Start Developing
Environment variable mismatches are one of those stupid problems that waste enormous amounts of developer time while providing exactly zero value. They're the digital equivalent of searching for your keys when you could be driving somewhere. .env Wrangler won't write your code for you, but it will eliminate one of the most frustrating categories of "it worked on my machine" bugs.
The benefits are simple but profound: fewer broken deployments, less time debugging configuration issues, and more time actually building features. Your team will spend less time playing configuration telephone and more time writing code that works everywhere it's supposed to.
Try it out: https://github.com/BoopyCode/env-file-fixer-1767433078
Remember: in the grand theater of software development, environment variables shouldn't be the dramatic plot twist that brings down your production environment. They should be the boring, reliable stagehands that make the show go on without anyone noticing they're there. Go wrangle those variables, and may your deployments be as uneventful as a well-maintained configuration file.
Quick Summary
- What: .env Wrangler automatically detects mismatches between your .env.example and local .env files, generates safe diff reports, and helps sync missing variables.
π¬ Discussion
Add a Comment