Configuration & Secrets: Twelve-Factor Python

Configuration & Secrets: Twelve-Factor Python in Python: Every application needs to behave differently in development, staging, and production — different…

Concept Explanation

Every application needs to behave differently in development, staging, and production — different databases, different log levels, different API keys. The question is where that difference lives.

The wrong answer is in the code. A hard-coded connection string means you cannot deploy the same artifact twice, and a hard-coded API key means the key is in your Git history forever.

The Twelve-Factor Rule

Store configuration in the environment. Config is everything that varies between deploys; code is everything that does not.

The test: could you open-source this repository right now without leaking anything? If not, you have secrets in your code.

Configuration vs Secrets

They are related but not the same, and conflating them is how leaks happen.

ConfigurationSecrets
ExamplesLog level, page size, feature flags, timeoutsAPI keys, passwords, private keys, tokens
Safe in Git?Yes, defaults are fineNever
Where it livesEnv vars, committed defaultsEnv vars from a secret manager
RotationRarelyRegularly, and on every suspected leak

Reading the Environment

import os

# os.environ raises KeyError if missing -- good for required values
database_url = os.environ["DATABASE_URL"]

# os.getenv returns a default -- good for optional values
log_level = os.getenv("LOG_LEVEL", "INFO")
port = int(os.getenv("PORT", "8000"))          # always a string; cast it

Two things bite people here. Environment variables are always strings, so os.getenv("DEBUG") returns "False" — which is truthy. And a typo in a variable name silently gives you the default instead of failing loudly.

The Boolean Trap

# WRONG: the string "False" is truthy
DEBUG = bool(os.getenv("DEBUG", "False"))      # always True!

# RIGHT
DEBUG = os.getenv("DEBUG", "false").lower() in {"1", "true", "yes", "on"}

This is the single most common configuration bug in Python, and it usually ships debug mode to production.

Validate at Startup, Not at Use

A missing DATABASE_URL should crash the process on boot, with a clear message — not throw a KeyError inside a request handler forty minutes later. Pydantic's BaseSettings does this in a few lines:

from pydantic import Field
from pydantic_settings import BaseSettings


class Settings(BaseSettings):
    database_url: str                              # required
    log_level: str = "INFO"                        # optional with a default
    max_workers: int = Field(default=4, ge=1, le=64)
    debug: bool = False                            # parses "true"/"1"/"yes"

    model_config = {"env_file": ".env", "extra": "forbid"}


settings = Settings()      # raises ValidationError immediately if anything is wrong

This gives you type coercion, range validation, a real boolean parser, and one place that documents every knob the application has.

.env Files Are for Development Only

A .env file is convenient locally. It must be in .gitignore, and it must not be how production gets its secrets — production should inject environment variables from a secret manager.

Commit a .env.example with the names and dummy values so a new developer knows what to set:

DATABASE_URL=postgresql://localhost/myapp_dev
API_KEY=replace-me
LOG_LEVEL=DEBUG

Secret Managers

PlatformService
AWSSecrets Manager, Parameter Store
GCPSecret Manager
AzureKey Vault
KubernetesSecrets (base64, not encryption — enable encryption at rest)
Self-hostedHashiCorp Vault

They all provide the same three things a .env file cannot: access control, an audit log of who read what, and rotation without a redeploy.

If a Secret Leaks

Rotate it. Removing the line and committing does nothing — the value is still in the Git history and in every clone. The order is: rotate first, then clean history if you must, and assume the old value is compromised.

Never Log Secrets

logger.info("connecting", extra={"url": database_url})   # leaks the password

Connection strings usually contain credentials. Redact before logging, and be careful with exception tracebacks — many frameworks print local variables.


Code Example #1 (Basic)

Reading, casting, and validating configuration correctly.

import os

# Pretend these were injected by the deployment platform
os.environ.setdefault("DATABASE_URL", "postgresql://user:s3cret@db.internal/app")
os.environ.setdefault("PORT", "8080")
os.environ.setdefault("DEBUG", "false")
os.environ.setdefault("ALLOWED_HOSTS", "example.com,api.example.com")


# --- The boolean trap ---
wrong = bool(os.getenv("DEBUG", "false"))
print("=== The boolean trap ===")
print(f"  DEBUG env value:        {os.getenv('DEBUG')!r}")
print(f"  bool(os.getenv(...)):   {wrong}   <- WRONG, non-empty strings are truthy")


def env_bool(name: str, default: bool = False) -> bool:
    raw = os.getenv(name)
    if raw is None:
        return default
    return raw.strip().lower() in {"1", "true", "yes", "on"}


print(f"  env_bool('DEBUG'):      {env_bool('DEBUG')}   <- correct\n")


# --- Required vs optional ---
print("=== Required vs optional ===")
try:
    database_url = os.environ["DATABASE_URL"]        # KeyError if absent
    print(f"  DATABASE_URL present ({len(database_url)} chars)")
except KeyError:
    raise SystemExit("FATAL: DATABASE_URL is not set")

log_level = os.getenv("LOG_LEVEL", "INFO")           # optional
print(f"  LOG_LEVEL defaulted to  {log_level!r}")


# --- Casting, with a clear failure ---
def env_int(name: str, default: int) -> int:
    raw = os.getenv(name)
    if raw is None:
        return default
    try:
        return int(raw)
    except ValueError:
        raise SystemExit(f"FATAL: {name} must be an integer, got {raw!r}")


port = env_int("PORT", 8000)
print(f"  PORT parsed as int:     {port} ({type(port).__name__})")


# --- Lists ---
hosts = [h.strip() for h in os.getenv("ALLOWED_HOSTS", "").split(",") if h.strip()]
print(f"  ALLOWED_HOSTS as list:  {hosts}\n")


# --- Never log the raw value ---
def redact_url(url: str) -> str:
    """Hide the password in a connection string before it reaches a log."""
    if "@" not in url or "://" not in url:
        return url
    scheme, rest = url.split("://", 1)
    creds, host = rest.split("@", 1)
    user = creds.split(":", 1)[0]
    return f"{scheme}://{user}:***@{host}"


print("=== Redaction before logging ===")
print(f"  raw:      {database_url}")
print(f"  redacted: {redact_url(database_url)}")
print("  Log the second one. Connection strings carry credentials.")

The env_bool helper is three lines and prevents the most expensive configuration bug there is. Write it once per project.

Code Example #2 (Intermediate)

A validated settings object, per-environment overrides, and a secret-manager fetch with caching.

import os
import time
from functools import lru_cache
from typing import Literal

from pydantic import Field, field_validator, computed_field
from pydantic_settings import BaseSettings, SettingsConfigDict


# ==================== One validated place for every knob ====================
class Settings(BaseSettings):
    """Every configurable value in the application, validated at startup."""

    model_config = SettingsConfigDict(
        env_file=".env",                # development convenience only
        env_file_encoding="utf-8",
        env_prefix="APP_",              # APP_DATABASE_URL -> database_url
        extra="forbid",                 # a typo'd variable is an error, not a shrug
        case_sensitive=False,
    )

    # --- Required: no default means the process refuses to start without it ---
    database_url: str
    secret_key: str = Field(min_length=32)

    # --- Optional with validated defaults ---
    environment: Literal["development", "staging", "production"] = "development"
    log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
    port: int = Field(default=8000, ge=1024, le=65535)
    max_workers: int = Field(default=4, ge=1, le=64)
    request_timeout: float = Field(default=10.0, gt=0, le=120)
    debug: bool = False                 # pydantic parses "true"/"1"/"yes" correctly
    allowed_hosts: list[str] = Field(default_factory=list)

    @field_validator("database_url")
    @classmethod
    def must_be_postgres(cls, v: str) -> str:
        if not v.startswith(("postgresql://", "postgresql+asyncpg://")):
            raise ValueError("database_url must be a PostgreSQL DSN")
        return v

    @field_validator("allowed_hosts", mode="before")
    @classmethod
    def split_csv(cls, v):
        # Env vars are strings; accept "a.com,b.com" as well as a real list
        return [h.strip() for h in v.split(",") if h.strip()] if isinstance(v, str) else v

    @computed_field
    @property
    def is_production(self) -> bool:
        return self.environment == "production"

    def safe_dump(self) -> dict:
        """Everything except the secrets -- safe to log at startup."""
        data = self.model_dump()
        for key in ("database_url", "secret_key"):
            data[key] = "***redacted***"
        return data


@lru_cache
def get_settings() -> Settings:
    """Cached so the file and environment are read exactly once per process."""
    return Settings()


# Simulate injected environment
os.environ.update({
    "APP_DATABASE_URL": "postgresql://svc:hunter2@db.internal:5432/app",
    "APP_SECRET_KEY": "x" * 40,
    "APP_ENVIRONMENT": "production",
    "APP_PORT": "9000",
    "APP_DEBUG": "false",
    "APP_ALLOWED_HOSTS": "example.com, api.example.com",
})

settings = get_settings()
print("=== Validated settings ===")
for key, value in settings.safe_dump().items():
    print(f"  {key:<18} {value!r}")
print(f"  is_production:     {settings.is_production}")
print(f"  debug parsed as:   {settings.debug} ({type(settings.debug).__name__})\n")


# ==================== Validation failures happen at boot ====================
print("=== Startup validation catches mistakes immediately ===")
for label, override in [
    ("port out of range", {"APP_PORT": "80"}),
    ("bad environment", {"APP_ENVIRONMENT": "prod"}),
    ("short secret_key", {"APP_SECRET_KEY": "tooshort"}),
    ("unknown variable", {"APP_TYPO_SETTING": "oops"}),
]:
    saved = {k: os.environ.get(k) for k in override}
    os.environ.update(override)
    get_settings.cache_clear()
    try:
        Settings()
        print(f"  {label:<20} accepted (unexpected)")
    except Exception as exc:
        first = str(exc).splitlines()[1] if len(str(exc).splitlines()) > 1 else str(exc)
        print(f"  {label:<20} rejected: {first.strip()[:52]}")
    for k, v in saved.items():
        if v is None:
            os.environ.pop(k, None)
        else:
            os.environ[k] = v
get_settings.cache_clear()
print()


# ==================== Fetching from a secret manager ====================
class SecretManagerStub:
    """Stands in for AWS Secrets Manager / Vault / GCP Secret Manager."""

    _store = {"prod/db/password": "hunter2", "prod/stripe/key": "sk_live_abc123"}

    def __init__(self):
        self.api_calls = 0

    def get_secret(self, name: str) -> str:
        self.api_calls += 1
        time.sleep(0.02)                       # a real network round trip
        try:
            return self._store[name]
        except KeyError:
            raise RuntimeError(f"secret {name!r} not found") from None


_manager = SecretManagerStub()


@lru_cache(maxsize=32)
def secret(name: str) -> str:
    """Cached: secret managers are rate-limited and charge per call."""
    return _manager.get_secret(name)


print("=== Secret manager with caching ===")
start = time.perf_counter()
for _ in range(50):
    secret("prod/db/password")
    secret("prod/stripe/key")
elapsed = time.perf_counter() - start
print(f"  100 lookups in {elapsed * 1000:.1f} ms")
print(f"  actual API calls: {_manager.api_calls} (cached the rest)")
print(f"  value length: {len(secret('prod/db/password'))} chars -- never printed\n")

try:
    secret("prod/missing/key")
except RuntimeError as exc:
    print(f"  missing secret fails loudly: {exc}")

print("\nRotation note: lru_cache means a rotated secret is not picked up until")
print("restart. Use a TTL cache, or handle the auth failure by clearing the cache")
print("and retrying once -- that turns rotation into a blip instead of an outage.")

The extra="forbid" line earns its place: without it, APP_TYPO_SETTING is silently ignored, and you spend an afternoon wondering why your override had no effect.


Common Mistakes

  1. Hard-coding secrets: an API key in the source is in the Git history permanently. Rotate anything that has been committed.
  2. bool(os.getenv("DEBUG")): the string "False" is truthy, so this enables debug mode everywhere.
  3. Forgetting env vars are strings: os.getenv("PORT") + 1 raises; int() every numeric value.
  4. Committing .env: add it to .gitignore before the first commit, and commit .env.example instead.
  5. Reading config at use-time instead of startup: a missing variable should crash on boot, not mid-request.
  6. Logging connection strings: they contain the password. Redact first.
  7. Assuming a removed secret is safe: deleting the line does not remove it from history or from anyone's clone.
  8. Using .env files in production: no access control, no audit trail, no rotation.
  9. Silently accepting unknown variables: without extra="forbid", a typo'd override does nothing and you debug the wrong thing.
  10. One shared secret across all environments: a staging leak becomes a production incident.
  11. Caching secrets forever: rotation then requires a restart. Use a TTL, or clear and retry on an auth failure.
  12. Base64 mistaken for encryption: Kubernetes Secrets are encoded, not encrypted, unless you enable encryption at rest.
  13. Different config mechanisms in different modules: one Settings object, imported everywhere.

Best Practices

  • Config comes from the environment; the same artifact deploys to every environment unchanged.
  • Validate everything at startup with pydantic-settings, and fail loudly with a message naming the variable.
  • One Settings class, cached with @lru_cache, imported wherever config is needed.
  • Required values get no default. If the app cannot run without it, do not paper over its absence.
  • Use extra="forbid" so a typo'd variable is an error rather than a silent no-op.
  • Never write your own bool() cast on an env var — let pydantic parse it, or use an env_bool helper.
  • .gitignore your .env, commit .env.example with names and dummy values.
  • Redact secrets before logging, and check that your error reporter is not capturing local variables.
  • Use a real secret manager in production for access control, audit logs, and rotation.
  • Separate secrets per environment, and rotate on a schedule as well as on suspicion.
  • Add a secret scanner to CI (gitleaks, detect-secrets) so a committed key fails the build.
  • Log the safe subset of config at startup — it makes "which config was this pod running?" answerable.
  • Handle rotation gracefully: on an auth failure, clear the cache and retry once before giving up.

Practice Exercises

  1. The Boolean Bug: Set DEBUG=false in the environment and show that bool(os.getenv("DEBUG")) returns True. Write an env_bool helper that handles "true", "1", "yes", and "on" case-insensitively, and prove it returns False.
  2. The Validated Settings: Build a pydantic-settings Settings class with a required database_url, a port constrained to 1024–65535, and extra="forbid". Show it rejecting a port of 80, an unknown variable, and a missing database_url — each at construction time.
  3. The Redactor: Write a redact_url function that turns postgresql://user:password@host/db into postgresql://user:***@host/db, and a safe_dump method on your settings that masks every secret field. Print both the raw and safe versions to show the difference.