patternpythonMajorpending
Environment Variable Management Across Environments
Viewed 0 times
environment variablesenv filesconfigurationsecretstwelve-factordotenv
Problem
Configuration values (API keys, database URLs, feature flags) are hardcoded, committed to git, or inconsistent across development/staging/production environments.
Solution
Layered environment variable management:
1. Local development: .env files
2. Loading with validation
3. Production: use your platform's secret manager
4. .gitignore essentials
1. Local development: .env files
# .env.example (committed to git - no secrets!)
DATABASE_URL=postgresql://localhost:5432/myapp_dev
REDIS_URL=redis://localhost:6379
API_KEY=your-api-key-here
LOG_LEVEL=debug
# .env (NOT committed - in .gitignore)
DATABASE_URL=postgresql://localhost:5432/myapp_dev
API_KEY=sk-actual-key-here2. Loading with validation
# Python with pydantic
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
database_url: str
redis_url: str = 'redis://localhost:6379'
api_key: str
log_level: str = 'info'
debug: bool = False
class Config:
env_file = '.env'
settings = Settings() # Validates on startup!// TypeScript with zod
import { z } from 'zod';
const envSchema = z.object({
DATABASE_URL: z.string().url(),
API_KEY: z.string().min(1),
PORT: z.coerce.number().default(3000),
NODE_ENV: z.enum(['development', 'production', 'test']),
});
export const env = envSchema.parse(process.env);
// Fails fast at startup if config is invalid3. Production: use your platform's secret manager
- AWS: SSM Parameter Store or Secrets Manager
- GCP: Secret Manager
- K8s: Secrets (+ external-secrets-operator)
- Vercel/Netlify: Environment Variables UI
4. .gitignore essentials
.env
.env.local
.env.*.local
*.pem
*.keyWhy
Twelve-factor app principle: config that varies between environments belongs in environment variables, not code. This separates config from code and prevents secret leakage.
Gotchas
- .env files are NOT secure for production - they're for local dev only
- Docker ARG is build-time, ENV is runtime - don't put secrets in ARG
Context
Managing application configuration across environments
Revisions (0)
No revisions yet.