How to Audit Environment Variable Files for Missing Values in Python
A Python tool that reads an environment variable file and reports any variables with empty or missing values.
Python code
38 linesimport os
import re
from pathlib import Path
def audit_env_file(filepath: str) -> None:
"""
Audit an environment variable file for missing values.
Prints file status and lists variables that have empty values.
"""
path = Path(filepath)
if not path.exists():
print(f"Error: File '{filepath}' not found.")
return
missing = []
with open(path, 'r') as f:
for i, line in enumerate(f, 1):
line = line.strip()
if not line or line.startswith('#'):
continue
match = re.match(r'^([A-Za-z_]\w*)=(.*)$', line)
if match:
var_name = match.group(1)
var_value = match.group(2).strip()
if not var_value or var_value in ('""', "''"):
missing.append((i, var_name))
else:
print(f"Warning: malformed line {i}: '{line}'")
print(f"Audit of '{filepath}' ({len(missing)} missing value(s)):")
if missing:
for line_num, var in missing:
print(f" Line {line_num}: '{var}' is empty")
else:
print(" All variables have assigned values.")
if __name__ == "__main__":
audit_env_file(".env.example")
Output
Audit of '.env.example' (2 missing value(s)):
Line 3: 'DB_PASSWORD' is empty
Line 5: 'API_KEY' is empty
How it works
The function uses pathlib.Path to check file existence and then reads it line by line. A regex re.match extracts variable names and values, ignoring blank lines and comments. If a variable's value is empty or consists only of quotes ("" or ''), it's flagged as missing. The script prints a summary of all empty variables plus any malformed lines.
Common mistakes
- Forgetting to strip lines before parsing, leading to false malformed-line warnings.
- Assuming environment files always use `=` as delimiter without handling spaces around it.
- Not considering that empty values can be intentional (e.g., `FEATURE_FLAG=` to disable).
- Hardcoding a specific file name instead of accepting a filepath argument.
Variations
- Extend the tool to also validate required variables defined in a separate config file.
- Use `argparse` to accept multiple files or a directory of env files to audit.
Real-world use cases
- Catching missing secrets before deploying a containerized application to production.
- Validating that all contributors have filled in their local .env files after cloning a repo.
- Integrating into a CI pipeline to fail a build if any required environment variable is unset.
Sponsored
More from Files & data
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Personal Work Hours Tracker in Python medium
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
Keep learning
Related tutorials and quizzes for this topic.