Rename environment variables without breaking deploys¶
Use this recipe when you need to rename environment variables (or combine and convert legacy variables into a new format) without requiring code and infrastructure to switch in the exact same minute.
BaseAppSettings reads deprecated names directly from the process
environment and .env, emits a DeprecationWarning and a structured boot
log whenever a fallback populates a field, refuses conflicting values without
printing secrets, and supports strict mode (ENV_ALIASES_STRICT=true) so you
can prove every environment is clean before removing the bridge.
1:1 renames with DEPRECATED_ENV_ALIASES¶
Use when the value format stays the same and only the variable name changes
(such as MINIO_* → STORAGE_* on StorageSettings). Declare
DEPRECATED_ENV_ALIASES on your Settings class without touching field
declarations or repeating AliasChoices:
import os
import warnings
from collections.abc import Mapping
from typing import ClassVar
from tempest_fastapi_sdk import BaseAppSettings, StorageSettings
class Settings(StorageSettings, BaseAppSettings):
"""Service settings with a 1:1 legacy variable rename."""
DEPRECATED_ENV_ALIASES: ClassVar[Mapping[str, str]] = {
"APP_PUBLIC_URL": "PUBLIC_BASE_URL",
}
PUBLIC_BASE_URL: str = "http://127.0.0.1:8000"
def main() -> None:
"""Read the deprecated variable and print the resolved canonical field."""
os.environ["APP_PUBLIC_URL"] = "https://api.example.com"
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter("always")
settings: Settings = Settings()
print(settings.PUBLIC_BASE_URL)
print(recorded[0].message)
if __name__ == "__main__":
main()
Running the example above prints to standard output (stdout):
https://api.example.com
Environment variable 'APP_PUBLIC_URL' is deprecated; migrate to 'PUBLIC_BASE_URL'.
And, on stderr, the line from the tempest_fastapi_sdk.settings logger (the
example does not configure logging, so only the message comes out, with no
level or timestamp):
- Reads both process env and
.env. Process environment variables take precedence over.env, and explicit constructor kwargs (Settings(PUBLIC_BASE_URL=...)) beat both without emitting a warning. - Collected across the MRO.
Settings(StorageSettings, BaseAppSettings)inheritsStorageSettings'sMINIO_*→STORAGE_*pairs automatically and merges yourAPP_PUBLIC_URL→PUBLIC_BASE_URLon top. - Structured boot log. Whenever a fallback populates a field, the
tempest_fastapi_sdk.settingslogger emits aWARNINGwithextra={"event": "deprecated_env_alias", "deprecated_env": ..., "canonical_env": ...}— never printing the value.
Non-1:1 migrations with DEPRECATED_ENV_CONVERTERS¶
Use when the migration changes units (days → seconds) or combines several
legacy variables into a single URL (such as REDIS_HOST/REDIS_PORT/
REDIS_DB/REDIS_PASSWORD → REDIS_URL).
Each entry in DEPRECATED_ENV_CONVERTERS maps the canonical new name to
an EnvAliasConverter callable ((Mapping[str, str]) -> str | None). It
receives a read-only view of the merged environment (process env overrides
.env) and returns the converted string — or None when none of the legacy
variables are set:
import os
import warnings
from collections.abc import Mapping
from typing import ClassVar
from urllib.parse import quote
from tempest_fastapi_sdk import (
BaseAppSettings,
EnvAliasConverter,
JWTSettings,
RedisSettings,
)
def expire_days_to_seconds(env: Mapping[str, str]) -> str | None:
"""Convert ACCESS_TOKEN_EXPIRE_DAYS into JWT_ACCESS_TTL_SECONDS.
Args:
env (Mapping[str, str]): Merged environment variables.
Returns:
str | None: TTL in seconds as a string, or ``None`` when unset.
"""
raw_days: str | None = env.get("ACCESS_TOKEN_EXPIRE_DAYS")
if raw_days is None:
return None
return str(int(raw_days) * 86_400)
def redis_parts_to_url(env: Mapping[str, str]) -> str | None:
"""Build REDIS_URL from REDIS_HOST, PORT, DB and PASSWORD.
Args:
env (Mapping[str, str]): Merged environment variables.
Returns:
str | None: ``redis://...`` URL with escaped password, or ``None``.
"""
keys: tuple[str, ...] = ("REDIS_HOST", "REDIS_PORT", "REDIS_DB", "REDIS_PASSWORD")
if not any(key in env for key in keys):
return None
host: str = env.get("REDIS_HOST", "localhost")
port: str = env.get("REDIS_PORT", "6379")
db: str = env.get("REDIS_DB", "0")
password: str | None = env.get("REDIS_PASSWORD")
escaped_password: str = quote(password, safe="") if password else ""
auth: str = f":{escaped_password}@" if escaped_password else ""
return f"redis://{auth}{host}:{port}/{db}"
class Settings(JWTSettings, RedisSettings, BaseAppSettings):
"""Settings accepting legacy JWT and Redis env shapes during rollout."""
DEPRECATED_ENV_CONVERTERS: ClassVar[Mapping[str, EnvAliasConverter]] = {
"JWT_ACCESS_TTL_SECONDS": expire_days_to_seconds,
"REDIS_URL": redis_parts_to_url,
}
def main() -> None:
"""Demonstrate days-to-seconds and split-Redis-to-URL conversions."""
os.environ["ACCESS_TOKEN_EXPIRE_DAYS"] = "7"
os.environ["REDIS_HOST"] = "redis.internal"
os.environ["REDIS_PORT"] = "6380"
os.environ["REDIS_DB"] = "2"
os.environ["REDIS_PASSWORD"] = "p@ss/w:o?r#d"
with warnings.catch_warnings(record=True) as recorded:
warnings.simplefilter("always")
settings: Settings = Settings()
print(settings.JWT_ACCESS_TTL_SECONDS)
print(settings.REDIS_URL)
for item in recorded:
print(item.message)
if __name__ == "__main__":
main()
Measured standard output (stdout):
604800
redis://:p%40ss%2Fw%3Ao%3Fr%23d@redis.internal:6380/2
Deprecated environment variable(s) 'ACCESS_TOKEN_EXPIRE_DAYS' converted to 'JWT_ACCESS_TTL_SECONDS'; migrate to 'JWT_ACCESS_TTL_SECONDS'.
Deprecated environment variable(s) 'REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASSWORD' converted to 'REDIS_URL'; migrate to 'REDIS_URL'.
On stderr, one line from the tempest_fastapi_sdk.settings logger per
conversion:
Deprecated environment variable(s) ACCESS_TOKEN_EXPIRE_DAYS converted to JWT_ACCESS_TTL_SECONDS; migrate to JWT_ACCESS_TTL_SECONDS
Deprecated environment variable(s) REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASSWORD converted to REDIS_URL; migrate to REDIS_URL
- Escape credentials. Always use
urllib.parse.quote(password, safe="")when assembling a URL with a password: characters such as@,/,:,?and#break URL parsing if interpolated raw. - Tracked names, never values. The SDK observes which keys the converter
looked up in
envso warnings, structured boot logs and strict-mode tables name the exact legacy variables without ever echoing their values.
Conflicts between old and new names¶
Use this section to understand what happens when both the old and new variables exist during a rollout window.
- Same value: accepted without a warning (lets deploys introduce the new variable before deleting the old one).
- Different values: startup fails immediately with
SettingsError, even when one value sits in the process environment and the other in.env:
Conflicting environment variables: PUBLIC_BASE_URL and APP_PUBLIC_URL. Each pair is one setting under its current and its deprecated name, set to different values. Remove the deprecated name (the second of each pair) from the environment and the .env file.
The same rule applies to converters: setting JWT_ACCESS_TTL_SECONDS=3600
alongside ACCESS_TOKEN_EXPIRE_DAYS=7 (which converts to 604800) raises
SettingsError, whereas JWT_ACCESS_TTL_SECONDS=604800 with
ACCESS_TOKEN_EXPIRE_DAYS=7 is accepted.
No value is ever echoed
Conflict errors, DeprecationWarning messages, structured boot logs and
strict-mode errors only mention variable names — never passwords or
tokens.
Strict mode: ENV_ALIASES_STRICT=true¶
Use at the end of a migration window (in staging or CI) to verify that no
container or .env still carries deprecated variables before you delete
DEPRECATED_ENV_ALIASES and DEPRECATED_ENV_CONVERTERS from the codebase.
When ENV_ALIASES_STRICT is set to any truthy value (1, true, yes,
on, t, y, case-insensitive), any matched alias or converter stops
startup with a migration table:
Deprecated environment variables are disallowed (ENV_ALIASES_STRICT is enabled):
- ACCESS_TOKEN_EXPIRE_DAYS -> JWT_ACCESS_TTL_SECONDS
- APP_PUBLIC_URL -> PUBLIC_BASE_URL
- REDIS_HOST, REDIS_PORT, REDIS_DB, REDIS_PASSWORD -> REDIS_URL
Migrate each variable to its canonical name and remove the deprecated one.
Even when the canonical variable is also present with the same value, strict mode still flags the leftover deprecated variable so stale entries cannot linger unnoticed.
Overriding settings_customise_sources
If your Settings class overrides settings_customise_sources, call
super().settings_customise_sources(...) or include
DeprecatedEnvAliasesSettingsSource(settings_cls, (env_settings, dotenv_settings))
in the returned tuple. With EnvironmentSettings and ENV=test coming
from the environment or constructor, .env stays excluded from aliases
and converters as well.
Recap¶
- 1:1 renames: declare
DEPRECATED_ENV_ALIASES: ClassVar[Mapping[str, str]]({"OLD_NAME": "NEW_NAME"}) — reads from process env and.env, noAliasChoicesneeded. - Conversions: declare
DEPRECATED_ENV_CONVERTERS({"NEW_NAME": fn}) with(Mapping[str, str]) -> str | None. - Safety: conflicts raise
SettingsError; secret values never appear in errors, warnings or logs. - Cutover: enable
ENV_ALIASES_STRICT=trueto fail fast on any remaining legacy variable before deleting the migration map.
See also: Settings (mixins and composition order),
Storage (MinIO/S3),
settings reference.