01B.2 Environment Variables, Configuration and Secrets
Every program you will write in this path needs configuration: which model to call, where the API lives, how long to wait before giving up, which features are switched on, and the keys that prove you are allowed to spend money. Get this wrong and the failure is never subtle — a key committed to git, a production deploy pointing at the test model, a script that works on your laptop and dies on the server. This lesson teaches the whole discipline: what counts as configuration, how environment variables work in Python, how .env files and python-dotenv load them, how pydantic-settings turns them into a typed, validated Settings object, and how to handle secrets so they never reach code, logs, git or a screenshot.
What you'll learn
- The twelve-factor idea of "config in the environment", and how to tell configuration apart from code
- Reading and setting environment variables in Python (
os.environ,os.getenv,os.environ.setdefault), the everything-is-a-string traps, type conversion, required-vs-optional variables, and failing fast at start-up .envfiles withpython-dotenv:load_dotenv(),dotenv_values(),find_dotenv(), the file format rules, precedence between real environment variables and the file, and why you never commit.env- Typed settings with
pydantic-settings:BaseSettings,SettingsConfigDict, field validation,SecretStr,functools.lru_cache-backedget_settings(), nested settings,secrets_dir, and other config sources (tomllib, YAML, CLI flags) - Secrets discipline: what counts as a secret, the never-list (code, git, logs, errors, screenshots, chat prompts, URLs), redaction helpers, rotation, least-privilege keys, secret scanning, and secret managers
- The provider environment variable names used across the whole path (
OPENAI_API_KEY,ANTHROPIC_API_KEY,GEMINI_API_KEY,OPENROUTER_API_KEY) - The
aitoolkit.settingsmodule that every later lesson in this module builds on
What you don't need
- Any API keys. Everything here runs on environment variables, files and stdlib Python. Provider keys appear only as placeholders and in a table of variable names.
- Deep Pydantic knowledge — 01B.6 covers models in full. This lesson uses
BaseModel/BaseSettingsas tools, not as a topic. - Docker, Kubernetes or cloud consoles. Secret managers and CI secrets are explained as concepts with pointers to the lessons that apply them.
Setup
You need Python 3.11+ (3.13 is the version this path recommends; the current stable release is 3.15 as of November 2026 — check python.org/downloads for today's). If you haven't set up a project yet, do 01B.1 first — freshers' first uv add fails without a project — or create one now:
uv init aitoolkit --bare --python 3.13 && cd aitoolkit
uv add pydantic pydantic-settings python-dotenv
# or, without uv: pip install pydantic pydantic-settings python-dotenvThese samples were checked against pydantic 2.14, pydantic-settings 2.16 and python-dotenv 1.2 as of November 2026; a newer major version may change names or defaults, so check the package's changelog if something does not match. The --bare project above is enough for the demo scripts in Parts 2 to 5. Part 4.13 builds aitoolkit/settings.py, which later lessons import as aitoolkit.settings; if you already built the full aitoolkit skeleton in 01B.1, 7.4, work in that project instead and save the module as src/aitoolkit/settings.py (the demo scripts can live in scripts/ or any scratch folder). The .env file used throughout lives at the project root and is never committed:
# .env (never commit this file)
OPENAI_API_KEY=...
ANTHROPIC_API_KEY=...No API key needed for this lesson — the placeholders above are never sent anywhere.
Running the demos. Scripts that only use the standard library (env_basics.py, fail_fast.py, redact.py and the other python3 ... examples) run with any Python 3.11+. Scripts that import dotenv or pydantic_settings need the project's environment, so run them from the project folder with uv run python script.py (01B.1, 4.4), or activate the virtual environment first. Where a command below says python3 for such a script, use uv run python instead. One more trap when you experiment with the Settings classes in Part 4: a class with no field for a variable in your .env (for example no anthropic_api_key field while .env has ANTHROPIC_API_KEY=) is rejected by default, as 4.2 explains. Add extra="ignore" to the SettingsConfigDict while you experiment.
What you must be able to do after this lesson#
- Explain why configuration lives in the environment and not in code
- Read environment variables in Python and convert them to the right types
- Fail fast at start-up when a required variable is missing
- Load a .env file with python-dotenv and keep it out of git
- Build a typed settings class with pydantic-settings and SecretStr
- Keep secrets out of code, logs and error messages
Why this matters for an AI engineer#
| You'll hear... | You'll understand it after... |
|---|---|
| "Put it in an env var, don't hard-code it." | Part 1 |
| "Our staging and prod use different models." | 1.4 Per-environment configuration |
"os.getenv('DEBUG') returned the string 'false' and my feature stayed on." |
2.3 Everything is a string |
| "The app crashed three requests in because a variable was missing." | 2.5 Required vs optional: fail fast |
"I edited .env and nothing changed." |
3.5 Precedence: the environment beats the file |
"Why does load_dotenv() need to be the first import?" |
3.6 Loading once, at the entry point |
"SecretStr shows ********** in the logs — nice, but how do I actually use the key?" |
4.4 SecretStr: secrets that can't leak by accident |
"Which source wins: CLI flag, env var, .env, or default?" |
4.12 CLI flags and the full precedence table |
"A contractor's .env broke CI because it had an extra variable." |
4.2 extra and the dotenv strictness trap |
"How do I check .env is really ignored before I commit?" |
5.6 Secret scanning and the .gitignore check |
"Where do keys live in production if not in .env?" |
5.7 Secret managers and CI secrets |
Part 1: Configuration vs code#
1.1 The twelve-factor idea#
In 2011, Adam Wiggins published The Twelve-Factor App, a set of principles for building software that deploys cleanly across environments. Factor III, Config, says: store configuration in environment variables, strictly separated from code. Its litmus test is memorable: the codebase could be made open source at any moment, without compromising any credentials.
The principle is older than LLMs but it fits AI engineering perfectly, because LLM applications are unusually configuration-heavy: every provider has a different key, base URL and model name; timeouts and retry budgets are tuned per environment; feature flags gate expensive behaviours; and the cost of a misconfiguration is measured in dollars per minute.
1.2 What is configuration, what is code#
The test is simple: would this value change between deploys without changing the program's logic? If yes, it is configuration.
| Configuration (varies per deploy) | Code (same everywhere) |
|---|---|
| API keys, tokens, passwords | Algorithms and business rules |
| Base URLs, hostnames, ports | Data structures and schemas |
Model names (gpt-6-luna, claude-haiku-5-5) |
How you parse a response |
| Timeouts, retry counts, concurrency limits | What a retry means |
Feature flags (ENABLE_CACHE=true) |
The code the flag switches |
Log level, environment name (dev/prod) |
The logging format itself |
| Database/cache connection strings | The queries you run |
| Per-environment secrets | — |
The boundary is not always sharp — a default model name is arguably "code" until product decides it should be flippable without a deploy — but the discipline is: anything you might want to change without a code release is config, and config lives outside the code.
1.3 Why hard-coded values hurt#
Four failure modes, all of which you will meet:
- Secrets in source. A key typed into a
.pyfile ends up in git history forever. Deleting the line does not delete the commit. 5.5 covers the drill. - Environment-specific values baked in.
MODEL = "gpt-6-luna"in code means a test run hits the production model, or a cost experiment needs a redeploy. Configuration exists precisely so the same build runs everywhere. - Untunable knobs. A timeout of
30hard-coded means changing it requires a release. As an env var, ops can tune it during an incident. - Hidden dependencies. Code that reads
os.environ["OPENAI_API_KEY"]deep inside a function fails late — three requests in, on the server, at 2 a.m. Configuration should be read once, validated once, at start-up (2.5).
1.4 Per-environment configuration#
The twelve-factor text makes a subtle point worth stealing: don't group config into named "environments" (development, test, production bundles). Instead, every variable is an independent knob, set per deploy. In practice most teams do use per-environment files — .env, .env.production, .env.test — and that is fine for development; what matters is that each deploy gets exactly the values it needs, injected by whatever runs it (your shell locally, a secret manager in production). 5.7 shows where those values come from outside your laptop.
flowchart LR
subgraph sources ["Configuration sources (highest priority first)"]
cli["CLI flags"]
init["Explicit arguments<br/>(tests, scripts)"]
env["Real environment<br/>variables"]
dotenv[".env file<br/>(development)"]
files["Config files<br/>(TOML/YAML — opt-in<br/>via settings_customise_sources)"]
secrets["Secret files /<br/>secret manager"]
defaults["Defaults in code"]
end
sources --> settings["Settings object<br/>(validated once, at start-up)"]
settings --> app["Your application code<br/>(never reads os.environ directly)"]Part 2: Environment variables in Python#
2.1 What an environment variable is#
An environment variable is a named string the operating system hands to every process it starts. Open a terminal and type env (macOS/Linux) or gci env: (PowerShell) and you will see dozens: PATH, HOME, USER, LANG, plus whatever you exported. Your program inherits a copy of its parent's environment when it starts; changing os.environ inside Python affects that process and any children it spawns — never your shell or other programs.
The shell side — export, .zshrc, PATH, per-command prefixes like FOO=bar cmd — is 00.2, which ends exactly where this lesson begins: os.environ.
Two properties matter for everything that follows:
- Values are always strings. There are no ints, bools or lists —
"8080","true","[1,2]". - Missing and empty are different states. A variable that was never set reads as
None(or raisesKeyError); one set to nothing reads as"". Conflating them is the source of most config bugs.
2.2 os.environ: read, write, default#
os.environ is a mapping-like object (os._Environ, a MutableMapping) onto the process environment. Three ways to read:
# env_basics.py — run: python3 env_basics.py
import json
import os
os.environ["AITK_PORT"] = "8080"
os.environ["AITK_DEBUG"] = "false" # note: lowercase, and a string!
os.environ["AITK_HOSTS"] = '["a.example", "b.example"]'
os.environ["AITK_EMPTY"] = "" # set, but empty
# AITK_MISSING is deliberately never set.
print("subscript :", os.environ["AITK_PORT"])
print("get :", os.environ.get("AITK_MISSING"))
print("get default :", os.environ.get("AITK_MISSING", "3000"))
print("setdefault :", os.environ.setdefault("AITK_REGION", "eu-west-1"))
print("setdefault2 :", os.environ.setdefault("AITK_REGION", "us-east-1")) # unchanged
# --- membership and removal (the rest of the mapping API) ---------------------
print("in op :", "AITK_PORT" in os.environ, "| AITK_GONE:", "AITK_GONE" in os.environ)
removed = os.environ.pop("AITK_REGION") # setdefault created it above
print("pop :", removed, "-> get now:", os.environ.get("AITK_REGION"))
del os.environ["AITK_PORT"] # removes it entirely (KeyError if absent)
print("del port : 'AITK_PORT' in os.environ ->", "AITK_PORT" in os.environ)
os.environ["AITK_PORT"] = "8080" # restore for the next sectionsubscript : 8080
get : None
get default : 3000
setdefault : eu-west-1
setdefault2 : eu-west-1
in op : True | AITK_GONE: False
pop : eu-west-1 -> get now: None
del port : 'AITK_PORT' in os.environ -> Falseos.environ["NAME"]raisesKeyErrorif unset — use it when the variable must exist and you want the crash to say so.os.environ.get("NAME")returnsNoneif unset;.get("NAME", default)supplies a fallback.os.environ.setdefault("NAME", value)sets only if absent — handy for defaults a library shouldn't override, and it returns the effective value either way.os.getenv("NAME")is a thin alias foros.environ.get("NAME")— same thing, older spelling. You will see both in the wild; pickos.environ.getand be consistent. There is noos.getenvwith a different signature to memorise.- The rest of the mapping API matters too:
"NAME" in os.environtests presence without a default dance,os.environ.pop("NAME", None)removes and returns (theNonedefault makes it safe when absent),del os.environ["NAME"]removes unconditionally (KeyErrorif absent), and iteratingos.environyields the variable names — the standard way to scrub secrets before spawning a child (2.7).
2.3 Everything is a string#
The same script continues into the traps:
# (continued from env_basics.py)
# --- trap 1: everything is a string ------------------------------------------
port = os.environ["AITK_PORT"]
print("type of port:", type(port).__name__)
try:
port + 1
except TypeError as exc:
print("port + 1 ->", type(exc).__name__ + ":", exc)
# --- trap 2: 'false' is truthy -----------------------------------------------
if os.environ.get("AITK_DEBUG"):
print("debug flag is ON <- the trap: the string 'false' is truthy")
else:
print("debug flag is off")
# --- trap 3: missing vs empty are different things ---------------------------
print("missing is None :", os.environ.get("AITK_MISSING") is None)
print("empty is '' :", repr(os.environ.get("AITK_EMPTY")))
print("bool('') :", bool(os.environ.get("AITK_EMPTY", "")))
# --- conversion that works ----------------------------------------------------
print("int(port) :", int(os.environ["AITK_PORT"]) + 1)
hosts = json.loads(os.environ["AITK_HOSTS"])
print("json list :", hosts, type(hosts).__name__)type of port: str
port + 1 -> TypeError: can only concatenate str (not "int") to str
debug flag is ON <- the trap: the string 'false' is truthy
missing is None : True
empty is '' : ''
bool('') : False
int(port) : 8081
json list : ['a.example', 'b.example'] listThree lessons:
- Convert deliberately.
int(),float(),json.loads()at the boundary, once."8080" + 1is aTypeError; better to fail there than three frames deep. "false","0","no","off"are all truthy strings.bool(os.environ.get("X"))is wrong for anything but "was it set?". Parse booleans explicitly (value.lower() in {"1","true","yes","on"}) — or, better, let Pydantic do it (4.3).if os.environ.get("X")treats""as unset (empty string is falsy) — which is usually what you want, but know thatX=in a.envand an absentXboth land in the "falsy" branch while remaining distinguishable viais None.
2.4 Type conversion, done carefully#
Hand-rolled parsing works for a script; for anything real, convert at one boundary and validate:
import json
import os
def env_int(name: str, default: int) -> int:
raw = os.environ.get(name)
return int(raw) if raw else default # "" falls back to default
def env_bool(name: str, default: bool = False) -> bool:
raw = os.environ.get(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on"}
def env_list(name: str) -> list[str]:
raw = os.environ.get(name, "")
return json.loads(raw) if raw else [] # JSON array: '["a", "b"]'Note the raw is None vs falsy distinction in env_bool: DEBUG= (empty) returns False here because "" isn't in the truthy set — arguably correct, arguably a surprise; the lesson's point is that you choose the semantics once, in one place.
2.5 Required vs optional: fail fast at start-up#
The worst place to discover a missing variable is inside request handler number forty. Read required configuration at start-up, with a message that says exactly what to fix:
# fail_fast.py — the pattern every later lesson reuses
import os
import sys
def required_env(name: str) -> str:
"""Return the variable's value, or exit with a readable message."""
value = os.environ.get(name)
if not value: # covers both missing (None) and empty ("")
sys.exit(
f"error: required environment variable {name} is not set.\n"
f" Set it in your shell or in the project .env file "
f"(see .env.example for the names)."
)
return value
def optional_env(name: str, default: str) -> str:
value = os.environ.get(name)
return value if value else default
def main() -> None:
api_key = required_env("DEMO_API_KEY") # exits here if unset
timeout = int(optional_env("DEMO_TIMEOUT", "30"))
print(f"key loaded ({len(api_key)} chars, value not shown), timeout={timeout}")
if __name__ == "__main__":
main()Run it both ways:
$ python3 fail_fast.py
error: required environment variable DEMO_API_KEY is not set.
Set it in your shell or in the project .env file (see .env.example for the names).
$ echo "exit code: $?"
exit code: 1
$ DEMO_API_KEY=demo-key-123 DEMO_TIMEOUT=5 python3 fail_fast.py
key loaded (12 chars, value not shown), timeout=5Two habits worth copying: sys.exit(message) prints to stderr and exits non-zero — orchestrators and humans both read that correctly; and never print the value, only its length or a masked form (5.3 builds the real redactor).
2.6 Environment variables in tests#
Tests must not depend on the developer's real environment — CI has no .env, and a stray OPENAI_API_KEY on a laptop must never leak into a test run. Two stdlib patterns cover it; 01B.8 teaches monkeypatch.setenv, which is the pytest-native version of the same idea.
# test_override.py — unittest.mock.patch.dict restores os.environ afterwards
import os
from unittest.mock import patch
def endpoint() -> str:
return f"https://{os.environ.get('AITK_REGION', 'eu-west-1')}.example.com"
print("outside test :", endpoint())
with patch.dict(os.environ, {"AITK_REGION": "us-test-1"}):
print("inside patch :", endpoint())
print("after patch :", endpoint())outside test : https://eu-west-1.example.com
inside patch : https://us-test-1.example.com
after patch : https://eu-west-1.example.compatch.dict(os.environ, {...}) temporarily overlays values and restores the mapping on exit — including deleting keys you set that didn't exist before. For "pretend the variable is absent", use patch.dict(os.environ) then os.environ.pop("NAME", None) inside the block, or patch.dict(os.environ, clear=True) when you want a completely clean environment (useful for testing that your code fails correctly with nothing set).
2.7 Child processes inherit the environment#
When your Python program starts another program — subprocess, os.system, a linter, git — the child inherits a copy of os.environ unless you pass env=, in which case your mapping replaces the whole environment (the child then lacks PATH unless you include it):
# env_inherit.py
import os
import subprocess
import sys
os.environ["AITK_DEMO"] = "hello-from-parent"
child_code = "import os; print('child sees:', os.environ.get('AITK_DEMO'))"
out = subprocess.run(
[sys.executable, "-c", child_code],
capture_output=True, text=True, check=True,
)
print(out.stdout.strip())
# ...unless you pass a custom env= mapping, which REPLACES the whole environment:
out2 = subprocess.run(
[sys.executable, "-c", child_code],
capture_output=True, text=True,
env={"PATH": os.environ["PATH"], "AITK_DEMO": "only-this"},
)
print(out2.stdout.strip())child sees: hello-from-parent
child sees: only-thisWhy this matters for secrets: anything in your process environment is readable by every child process you spawn — including a compromised dependency that gets to run subprocess. It also means env= is a place secrets can leak to tools that log their environment (some do). Pass the minimum: build the child's env from os.environ minus secrets, or use the tools' own credential mechanisms.
Part 3: .env files with python-dotenv#
3.1 Why a .env file at all#
Exporting a dozen variables in every terminal is unusable, and baking them into your shell profile leaks them into every project. The standard development pattern is a .env file in the project root: KEY=value per line, loaded into os.environ when the program starts. It is for development — production injects real environment variables from a secret manager instead (5.7, and the warning in 03.1 §3.4).
3.2 load_dotenv() and friends#
uv add python-dotenv # already added in Setup# app.py — the canonical two lines
from dotenv import load_dotenv
load_dotenv() # copies variables from .env into os.environVerified against the python-dotenv 1.2.4 documentation (as of November 2026):
| Call | What it does |
|---|---|
load_dotenv() |
Finds .env next to the script or in a parent directory, loads pairs into os.environ. Does not override variables already set (override=False). Returns True/False for whether a file was found. |
load_dotenv(override=True) |
The file wins over existing environment variables — rarely what you want (see 3.5). |
load_dotenv("/path/to/.env") / dotenv_path= |
Explicit path — use it when the file is not next to the script. |
find_dotenv() |
The search load_dotenv() uses internally: it starts in the directory of the file that called it, walks up through each parent folder to the filesystem root, and returns the first .env it finds (or "" if there is none). In a REPL, notebook or debugger it starts from the current working directory instead, and usecwd=True forces that. Pass an explicit path in production code so the result never depends on where the process was launched. |
dotenv_values(".env") |
Parses the file and returns a dict without touching os.environ — for merging configs yourself ({**dotenv_values(".env.shared"), **os.environ}). |
load_dotenv(stream=...) |
Reads from any file-like object, not just the filesystem. |
>>> from dotenv import dotenv_values
>>> dotenv_values(".env")
{'OPENAI_API_KEY': 'sk-...', 'APP_ENV': 'dev', 'DEBUG': None}Note DEBUG → None: a bare DEBUG line (no =) parses as "no value", which load_dotenv then ignores but dotenv_values reports as None — different from DEBUG= which is the empty string "".
Two operational details from the docs worth keeping:
PYTHON_DOTENV_DISABLED=1disablesload_dotenv()entirely — the escape hatch for "I can't edit the call site" and for production, where you don't want a stray.envfile accidentally read.- The package also ships a
dotenvCLI (pip install "python-dotenv[cli]"):dotenv set KEY value,dotenv list,dotenv run -- python app.py.
3.3 The .env file format#
"Mostly Bash-like" is the honest description (the format is not formally specified and improves over time). The rules that matter:
# .env — comments start with #, blank lines ignored
APP_ENV=dev # unquoted value: everything after = is the value
QUOTED="hello world" # double quotes preserve spaces
SINGLE='literal $NOT_EXPANDED' # single quotes: no expansion, \ and \' escapes only
export EXPORTED_VAR=yes # leading 'export' is allowed, ignored
DOMAIN=example.org
ADMIN_EMAIL=admin@${DOMAIN} # ${VAR} expands; bare $VAR does NOT
MULTI="line one\nline two" # \n inside double quotes is a newline
EMPTY= # empty string
NO_VALUE # dotenv_values -> None; load_dotenv ignores it
TRAILING=some value # comment # inline comments after values- Spaces around
=, keys and values are trimmed; values may be followed by a comment. - Double-quoted values support escapes (
\n,\t,\\,\"); single-quoted only\\and\'. - Quoted values may span multiple physical lines.
${VAR}interpolation resolves in a defined order that depends onoverride: withoverride=True/dotenv_values, file value beats environment; with the defaultoverride=False, the environment wins — matching the precedence rule in 3.5.
3.4 .env vs .env.example vs .env.local#
| File | Committed? | Holds | Purpose |
|---|---|---|---|
.env |
Never | Real values incl. secrets | Your machine's actual configuration |
.env.example |
Yes | Variable names, empty or placeholder values | The contract: "copy me to .env and fill in" |
.env.local |
Usually not | Machine-specific overrides | Personal tweaks on top of .env (the Next.js convention; several tools honour it) |
.env.production, .env.test |
Depends | Per-environment values | Used by frameworks/12-factor-style loaders; secrets still belong in a secret manager, not a committed file |
The .gitignore rules for these are in 01B.1 (project layout) and verified concretely in 5.6.
3.5 Precedence: the environment beats the file#
This is the number-one "I edited .env and nothing changed" cause, and it is intentional: load_dotenv() defaults to override=False, so a variable already in your shell environment wins over the file. The logic: the real environment is more specific than a file on disk.
# precedence.py — behaviour verified in 03.1 §3.4; shown illustrative
import os
from dotenv import load_dotenv
os.environ["OPENAI_BASE_URL"] = "http://localhost:11434/v1" # e.g. exported earlier
load_dotenv() # .env says OPENAI_BASE_URL=https://api.openai.com/v1
print(os.environ["OPENAI_BASE_URL"]) # -> the SHELL value wins
load_dotenv(override=True) # file wins instead
print(os.environ["OPENAI_BASE_URL"]) # -> the .env valuehttp://localhost:11434/v1
https://api.openai.com/v1When is each right? Default (override=False) is right almost always — production environments and CI inject real variables that must not be clobbered by a .env that happens to be lying around (a stray .env in a container is a real incident class). override=True is for "the file is the source of truth in dev" setups, and even then only at start-up.
The same precedence appears one layer up in pydantic-settings (4.2): env vars beat dotenv entries there too.
3.6 Loading once, at the entry point#
load_dotenv() mutates os.environ, so where you call it decides what sees the values:
- Call it first thing in your entry point (
main.py,app.py, the FastAPI app module,conftest.pyfor tests) — before any code readsos.environor constructs SDK clients. - Calling it inside a library module is a bug: libraries shouldn't mutate global state, and import order makes the result depend on which module happened to be imported first.
- With
pydantic-settingsyou don't call it at all —BaseSettingsreads the.envitself (4.2).load_dotenv()remains useful for scripts and for making variables visible to non-Pydantic code and child processes. - Alternative that skips the call entirely:
uv run --env-file .env python app.pyloads the file before Python starts (documented in 03.1 §3.4;uvis 01B.1's topic).
3.7 Never commit .env#
The mechanics — .gitignore patterns, git check-ignore, the .env* + !.env.example idiom — are covered in 03.1 §3.4 and 00.3/00.4 (git). What this lesson adds is a verification step, because "I added it to .gitignore" is a claim, not a check — 5.6 gives you a script that proves it and scans tracked files for key-shaped strings.
3.8 direnv and other shell-side loaders#
direnv (verified November 2026) is a shell extension that loads/unloads environment variables per directory: you keep a .envrc file in the project, run direnv allow once, and the variables appear in your shell whenever you cd in — no export lines, no forgetting. It can also read .env files. It is shell-side: it sets real environment variables, so every tool (not just Python) sees them. Alternatives in the same space: autoenv, mise, dotenv-cli. For this path, .env + python-dotenv/pydantic-settings is the default; reach for direnv when you want the variables in your shell for non-Python tools too.
Part 4: Typed settings with pydantic-settings#
Hand-rolled os.environ.get chains work for a script; a real application wants one typed object that validates everything once at start-up. That is pydantic-settings (pydantic-settings==2.16.2, verified on PyPI as of November 2026; requires pydantic>=2.7 and python-dotenv>=1.2.2).
4.1 From getenv soup to a Settings class#
# Before: scattered reads, string types, late failures
api_key = os.environ.get("OPENAI_API_KEY")
port = int(os.environ.get("PORT", "8080")) # crashes here if PORT=abc
retries = os.environ.get("RETRIES", "3") # still a string downstream# After: one class, validated once
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
openai_api_key: str
port: int = 8080
retries: int = 3
debug: bool = False
settings = Settings() # reads env vars + .env, validates, coerces typesA BaseSettings field named openai_api_key is looked up in the environment as OPENAI_API_KEY — matching is case-insensitive by default on environment variables, so the Pythonic snake_case name maps to the conventional UPPER_SNAKE env var for free. Fields with defaults are optional; fields without are required and produce a ValidationError at construction if missing or unparseable.
4.2 BaseSettings and SettingsConfigDict#
model_config = SettingsConfigDict(...) controls where values come from. The options verified against the 2.16.2 docs:
| Option | Effect |
|---|---|
env_file=".env" / env_file=(".env", ".env.local") |
Dotenv file(s) to read; a tuple merges with later files taking priority. A relative path resolves against the current working directory — run from the project root, pass an absolute path, or set env_file_depth to search upward (unlike load_dotenv(), which walks up from the script) |
env_file=None at init (Settings(_env_file=None)) |
Disable dotenv loading for this instance |
env_file_encoding="utf-8" |
File encoding (default is OS-dependent) |
env_file_depth=2 |
Also search this many parent directories for the file |
env_prefix="AITK_" |
Require this prefix on every source name (env, dotenv, secrets) |
env_nested_delimiter="__" |
DB__HOST=x populates db.host in nested models (4.7) |
env_nested_max_split=1 |
Limit how deep __ splits go |
case_sensitive=True |
Match names exactly (see the Windows caveat below) |
extra="forbid" / "ignore" |
What to do with dotenv entries that match no field — "forbid" is the default for BaseSettings (unlike BaseModel, which ignores extras) |
secrets_dir="/run/secrets" |
Read each field's value from a file of that name — the Docker/Kubernetes secrets pattern (4.10) |
dotenv_filtering=True |
With env_prefix set, only load dotenv entries carrying the prefix |
env_parse_none_str="null" |
Which string literal parses to None |
env_ignore_empty=True |
Treat empty-string environment variables as unset, so field defaults apply instead of "" |
validate_default=False |
Skip validation of default values (default: they are validated — a rare BaseSettings/BaseModel difference) |
Two traps the docs call out explicitly, both worth a ⚠️:
extra="forbid"+ dotenv is strict. Every line in.envmust correspond to a field, or construction raisesValidationError. A.envshared with other tools (aDATABASE_URLfor a different app) will break your settings. Choose deliberately:extra="ignore"for shared files,"forbid"(the default) when.envis yours alone and you want typos caught.- Case sensitivity is OS-dependent.
case_sensitive=Trueworks for dotenv files everywhere, but on Windows environment variable names are normalised to upper-case by the OS, so the setting has no effect there.
4.3 Field types and validation#
Because BaseSettings is a Pydantic model, every field gets full validation and coercion — this is where "everything is a string" stops mattering:
from typing import Literal
from pydantic import Field, HttpUrl, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
app_env: Literal["dev", "test", "staging", "prod"] = "dev"
debug: bool = False # "true"/"1"/"yes"/"on" all parse
port: int = Field(default=8080, ge=1, le=65535) # range-checked
openai_api_key: SecretStr | None = None # never a plain str
openai_base_url: str | None = None # for proxies / compatible endpoints
openai_model: str = "gpt-6-luna" # model names are config too
request_timeout_seconds: float = Field(default=60.0, gt=0)
max_retries: int = Field(default=2, ge=0)
cors_origins: list[str] = ["http://localhost:3000"] # JSON in env: '["https://a"]'What each piece buys you:
Literal[...]restricts to exact strings —APP_ENV=productionfails fast instead of silently running "prod-ish" code.boolunderstandstrue/false/1/0/yes/no/on/off(case-insensitive) — no more"false"-is-truthy bug. This is Pydantic's bool parser, notbool(str).int/floatwithField(ge=..., le=...)coerce"8080"→8080and reject"abc"or70000with a clear error.str | None = Noneis the optional pattern: missing env →None, present → validatedstr.list[str]parses the env value as JSON —CORS_ORIGINS='["https://app.example.com"]'. A non-JSON value raisesSettingsError("error parsing value for field ..."), which is honest: env vars can't natively hold lists. If you want comma-separated instead, write afield_validatoror aBeforeValidator— the docs show both patterns.HttpUrl(andAnyUrl,PostgresDsn,RedisDsn, …) validate URL shape at start-up — a malformedDATABASE_URLfails before the first query, not inside it.SecretStr— next section.
4.3b One field, several environment variable names#
Sometimes the SDK accepts more than one variable name for the same credential — the google-genai SDKs read GEMINI_API_KEY or GOOGLE_API_KEY (5.8) — and your Settings field should see both, or it silently misses a key the SDK would happily use. The documented mechanism is validation_alias with AliasChoices:
# settings_alias.py
from pydantic import AliasChoices, Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env")
gemini_api_key: SecretStr | None = Field(
default=None,
validation_alias=AliasChoices("GOOGLE_API_KEY", "GEMINI_API_KEY"),
)How it behaves, per the pydantic-settings docs:
AliasChoicestries each name in order and uses the first one found — so the order above mirrors the SDK's precedence (GOOGLE_API_KEYwins when both are set). Reversing the order would make your settings object disagree with the SDK about which key is in play.- Setting
validation_aliasreplaces the default lookup: the field namegemini_api_keyalone would not be matched — every accepted spelling must be listed (here bothGOOGLE_API_KEYand theGEMINI_API_KEYenv-var form). - Aliases apply to every source, not just environment variables:
.enventries,secrets_dirfiles and init kwargs all resolve through the same names. Field(alias=...)would additionally rename the field for serialisation;validation_aliasonly changes what is read in — the right choice for a settings object you maymodel_dump().
4.4 SecretStr: secrets that can't leak by accident#
SecretStr (and SecretBytes) wrap a secret so the default representations hide it — verified against the Pydantic docs:
repr()/str()showSecretStr('**********')— safe in logs, tracebacks, f-strings-by-accident, and debugger output.model_dump()/model_dump_json()serialise it as the literal string"**********"— a settings object can be logged or returned in an API response without leaking.get_secret_value()is the only way to unwrap it — an explicit act you perform exactly where the SDK call needs the real string.- Two
SecretStrs compare with constant-timesecrets.compare_digest— no timing side-channel when checking a presented token.
# secret_demo.py
from pydantic import BaseModel, SecretStr
class Credentials(BaseModel):
username: str
password: SecretStr
user = Credentials(username="sam", password="hunter2")
print(user) # username='sam' password=SecretStr('**********')
print(user.password.get_secret_value()) # hunter2 <- the ONLY way out
print(user.model_dump()) # {'username': 'sam', 'password': SecretStr('**********')}
print(user.model_dump_json()) # {"username":"sam","password":"**********"}username='sam' password=SecretStr('**********')
hunter2
{'username': 'sam', 'password': SecretStr('**********')}
{"username":"sam","password":"**********"}The pattern for SDKs that take a plain string: client = OpenAI(api_key=settings.openai_api_key.get_secret_value() if settings.openai_api_key else None) — unwrap once, at the boundary, never store the unwrapped value back on the settings object.
4.5 The missing-variable error#
When a required field has no value in any source, Settings() raises ValidationError listing every problem at once — the professional version of fail_fast.py:
pydantic_core._pydantic_core.ValidationError: 2 validation errors for Settings
openai_api_key
Field required [type=missing, input_value={}, input_type=dict]
anthropic_api_key
Field required [type=missing, input_value={}, input_type=dict]Because construction happens once at start-up (or first get_settings() call), the process dies immediately with an actionable message — before serving request one. This is the "fail fast" of 2.5, upgraded from one-variable-at-a-time to all-at-once.
4.6 get_settings() and functools.lru_cache#
You want settings loaded once per process, not re-parsed on every call. The canonical pattern — used by FastAPI's dependency injection in 01B.7 — is a cached factory:
from functools import lru_cache
@lru_cache(maxsize=1)
def get_settings() -> Settings:
return Settings()lru_cache is standard library, so the caching mechanics can be shown without Pydantic:
# cache_demo.py — stdlib-only version of the same pattern
import os
from functools import lru_cache
@lru_cache(maxsize=1)
def get_config() -> dict:
print(" (building config from environment...)")
return {
"region": os.environ.get("AITK_REGION", "eu-west-1"),
"port": int(os.environ.get("AITK_PORT", "8080")),
}
for _ in range(3):
print("call ->", get_config())
print("cache info:", get_config.cache_info())
get_config.cache_clear() # tests reset this
os.environ["AITK_REGION"] = "test-region"
print("after clear ->", get_config()) (building config from environment...)
call -> {'region': 'eu-west-1', 'port': 8080}
call -> {'region': 'eu-west-1', 'port': 8080}
call -> {'region': 'eu-west-1', 'port': 8080}
cache info: CacheInfo(hits=2, misses=1, maxsize=1, currsize=1)
(building config from environment...)
after clear -> {'region': 'test-region', 'port': 8080}Three calls, one build (hits=2, misses=1). In tests, get_settings.cache_clear() (or better, app.dependency_overrides in FastAPI — 01B.7) resets it so a monkeypatch.setenv takes effect on the next call.
4.7 Nested settings#
Real config groups naturally — an HttpConfig inside Settings, a RetryConfig inside that. Two mechanisms, both verified in the docs:
from pydantic import BaseModel
from pydantic_settings import BaseSettings, SettingsConfigDict
class RetryConfig(BaseModel):
max_attempts: int = 3
backoff_seconds: float = 0.5
class Settings(BaseSettings):
model_config = SettingsConfigDict(env_file=".env", env_nested_delimiter="__")
retry: RetryConfig = RetryConfig()With env_nested_delimiter="__", RETRY__MAX_ATTEMPTS=5 populates settings.retry.max_attempts — the double underscore survives because env-var names can't contain the field's own dots. Without the delimiter, the nested model is populated from a single JSON env var instead: RETRY='{"max_attempts": 5}'. env_nested_max_split=1 caps the split depth for cases where field names themselves contain underscores. Nested env vars take precedence over the top-level JSON form when both are present.
4.8 Overriding settings in tests#
Three levels, cheapest first:
settings = Settings(_env_file=None) # ignore .env entirely
settings = Settings(openai_api_key="test-key") # init kwargs beat everything
settings = Settings().model_copy(update={"port": 1}) # copy of an existing instance; update values are NOT validatedInit kwargs have the highest source priority (after CLI args) — Settings(debug=True) wins over DEBUG=false in the environment. For "pretend env var X is set", the test-side tool is monkeypatch.setenv + get_settings.cache_clear() (01B.8); unittest.mock.patch.dict(os.environ, ...) works without pytest (2.6).
4.9 model_dump without secrets#
settings.model_dump() returns a plain dict for logging/debugging — and because secret fields are SecretStr, the dump contains SecretStr('**********'), not the key. Two corollaries:
- You can safely log
settings.model_dump()except that non-secret fields still print — check before dumping wholesale in production. - If you ever need the real values (e.g. writing a redacted config report), unwrap explicitly per field:
s.openai_api_key.get_secret_value() if s.openai_api_key else None— and feed it to the redactor in 5.3, never to a log line.
4.10 secrets_dir: Docker and Kubernetes secrets#
Containers don't have .env files; orchestrators mount secrets as files. secrets_dir tells BaseSettings to read each field's value from a file of the matching name:
class Settings(BaseSettings):
model_config = SettingsConfigDict(secrets_dir="/run/secrets")
openai_api_key: SecretStrWith /run/secrets/openai_api_key containing the key, Settings() picks it up — and per the docs, env vars and dotenv still take priority over the secrets dir, so local overrides keep working. Docker Swarm mounts secrets at /run/secrets by default; Kubernetes uses /var/run/secrets/... mounted volumes. Missing directories are ignored with a warning (configurable via secrets_dir_missing). This is the bridge between ".env on my laptop" and "secret manager in production" — the application code is identical; only the source of the variable changes. 5.7 covers the managers themselves.
4.11 Other config sources: tomllib, YAML, and friends#
Not everything is an env var. tomllib (stdlib since Python 3.11; TOML 1.1 support added in 3.15) reads TOML config files — the format pyproject.toml already uses:
# toml_demo.py — reads aitoolkit.toml (shown below), then lets an env var override one value
import os
import tomllib
with open("aitoolkit.toml", "rb") as fh: # binary mode is required
file_cfg = tomllib.load(fh)
print("toml loaded:", file_cfg["app"]["name"], "| retries:", file_cfg["retry"]["max_attempts"])
merged = dict(file_cfg["app"])
if os.environ.get("AITK_PORT"):
merged["port"] = int(os.environ["AITK_PORT"])
print("merged port:", merged["port"], "(env AITK_PORT wins over file)")
try:
tomllib.loads("port = [1,2")
except tomllib.TOMLDecodeError as exc:
print("bad toml ->", type(exc).__name__, "|", exc)The script expects this aitoolkit.toml in the same folder:
# aitoolkit.toml
[app]
name = "aitoolkit"
port = 8080
[retry]
max_attempts = 3
backoff_seconds = 0.5Run it as AITK_PORT=9090 python3 toml_demo.py (PowerShell: $env:AITK_PORT = "9090"; python toml_demo.py).
toml loaded: aitoolkit | retries: 3
merged port: 9090 (env AITK_PORT wins over file)
bad toml -> TOMLDecodeError | Unclosed array (at end of document)Without AITK_PORT the merged port is the file's 8080. The script prints the exception message because the lineno and colno attributes on TOMLDecodeError only exist from Python 3.14; on 3.11 to 3.13 the position is part of the message text only. tomllib only reads — writing TOML needs a third-party lib (tomli-w, tomlkit). YAML needs pyyaml (uv add pyyaml; the samples were checked against PyYAML 6.0.3): load it with yaml.safe_load (or yaml.CSafeLoader for speed) — never bare yaml.load, which in PyYAML 6.x requires a Loader argument and whose unsafe loaders can execute arbitrary code in a crafted file. JSON needs nothing (json.loads). pydantic-settings can also consume file sources — TomlConfigSettingsSource, YamlConfigSettingsSource and JsonConfigSettingsSource — but only by overriding settings_customise_sources, i.e. deliberate plumbing, not a config flag (the toml/yaml PyPI extras provide the parsers). When to use which:
| Source | Best for | Avoid for |
|---|---|---|
Env vars / .env |
Secrets, per-deploy knobs, 12-factor purity | Anything you want versioned or reviewed |
| TOML/JSON file | Structured non-secret config committed to the repo (endpoints, budgets, feature defaults) | Secrets — files get committed |
| YAML | Same, when the ecosystem expects it (K8s manifests, CI) | Same caveat; YAML's type coercion surprises (yes→bool) |
secrets_dir/secret manager |
Production secrets | Local dev ergonomics |
| CLI flags | One-off overrides, scripts | Anything that must persist |
4.12 CLI flags and the full precedence table#
A --port 9000 flag should beat PORT=8080 in the environment, which beats .env, which beats the default. Two ways to get flags:
argparse/typer(stdlib/typer): parsesys.argvyourself and pass results as init kwargs — which, per 4.8, already outrank env vars. The stdlib demo:
# argparse_demo.py
import argparse
import os
parser = argparse.ArgumentParser(description="demo: --timeout beats DEMO_TIMEOUT beats default")
parser.add_argument("--timeout", type=int, default=None)
args = parser.parse_args(["--timeout", "7"]) # simulate `prog --timeout 7`
os.environ["DEMO_TIMEOUT"] = "12"
timeout = args.timeout if args.timeout is not None else int(os.environ.get("DEMO_TIMEOUT", "30"))
print("timeout used:", timeout)Output: timeout used: 7
CliSettingsSource: pydantic-settings 2.x can generate CLI arguments from yourSettingsfields automatically (Settings(cli_parse_args=True)), making flags a first-class source. It's powerful; for this path, argparse→init-kwargs is easier to reason about and is what 01B.10's CLI lesson builds on.
The consolidated precedence (highest first), verified against the docs' "Field value priority" section:
| Rank | Source |
|---|---|
| 1 | CLI args (if cli_parse_args enabled) |
| 2 | Settings(...) init kwargs |
| 3 | Real environment variables |
| 4 | .env (dotenv) file |
| 5 | secrets_dir files |
| 6 | Field defaults |
Rule of thumb that survives every framework: explicit beats ambient; ambient beats file; file beats default.
4.13 The aitoolkit.settings module#
Every later lesson in this module imports this. It is deliberately flat (env var name = field name, upper-cased), strict (extra="forbid" so a stray .env line fails loudly — the trade-off is discussed in 4.2), and secret-safe:
# src/aitoolkit/settings.py — the module every later 01B lesson builds on
"""Typed application settings for aitoolkit.
One Settings object per process, built lazily by get_settings() and cached.
Secrets are SecretStr so they cannot leak through repr/logs/dumps.
Env var names are the field names in UPPER_SNAKE (case-insensitive match),
except where an SDK accepts aliases — see gemini_api_key below.
"""
from functools import lru_cache
from typing import Literal
from pydantic import AliasChoices, Field, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
"""All configuration, validated once at first use."""
model_config = SettingsConfigDict(
env_file=".env",
env_file_encoding="utf-8",
extra="forbid", # a .env line matching no field is a mistake: fail loudly
)
# --- environment -------------------------------------------------------
app_env: Literal["dev", "test", "staging", "prod"] = "dev"
log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
debug: bool = False
# --- provider credentials (all optional: use the providers you need) ----
openai_api_key: SecretStr | None = None
anthropic_api_key: SecretStr | None = None
# google-genai accepts GEMINI_API_KEY or GOOGLE_API_KEY (the latter wins if
# both are set) — AliasChoices mirrors that precedence. See 4.3b and 5.8.
gemini_api_key: SecretStr | None = Field(
default=None,
validation_alias=AliasChoices("GOOGLE_API_KEY", "GEMINI_API_KEY"),
)
openrouter_api_key: SecretStr | None = None
# --- provider endpoints and models (config, not code) -------------------
openai_base_url: str | None = None # proxies, OpenRouter-style gateways
openai_model: str = "gpt-6-luna"
anthropic_model: str = "claude-haiku-5-5"
gemini_model: str = "gemini-3.8-flash"
openrouter_model: str = "openai/gpt-6-luna"
# --- HTTP / resilience knobs (used by http.py and resilience.py) --------
request_timeout_seconds: float = Field(default=60.0, gt=0)
connect_timeout_seconds: float = Field(default=10.0, gt=0)
max_retries: int = Field(default=2, ge=0)
max_connections: int = Field(default=100, ge=1)
# --- service knobs (used by service.py in 01B.7) -------------------------
service_port: int = Field(default=8000, ge=1, le=65535)
cors_origins: list[str] = ["http://localhost:3000"]
@lru_cache(maxsize=1)
def get_settings() -> Settings:
"""The process-wide Settings. Cached: parsed once, reused everywhere."""
return Settings()The matching .env.example (committed) and .env (never committed):
# .env.example — names only, safe to commit
APP_ENV=dev
LOG_LEVEL=INFO
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
GEMINI_API_KEY=
# GOOGLE_API_KEY= # alternative name the google-genai SDK also reads (wins if both set)
OPENROUTER_API_KEY=
OPENAI_MODEL=gpt-6-luna
REQUEST_TIMEOUT_SECONDS=60
MAX_RETRIES=2
SERVICE_PORT=8000
CORS_ORIGINS=["http://localhost:3000"]Later lessons consume it exactly like this: settings = get_settings() once, then settings.openai_api_key.get_secret_value() only where a client is constructed (01B.5 builds http.py on request_timeout_seconds/max_connections; 01B.7 injects get_settings as a FastAPI dependency; 01B.9 reads max_retries).
Part 5: Secrets handling#
Everything so far was configuration. Secrets are the subset that must be treated differently — the API keys and tokens that authenticate you to providers and bill your account.
5.1 What counts as a secret#
| Secret | Examples |
|---|---|
| API keys / tokens | sk-... (OpenAI), sk-ant-... (Anthropic), Gemini auth keys, sk-or-... (OpenRouter), GitHub PATs |
| Passwords & private keys | DB passwords, -----BEGIN ... PRIVATE KEY----- blocks, signing keys |
| Connection strings with credentials | postgres://user:pass@host/db, redis://:pass@host |
| Session/signing material | JWT secrets, webhook secrets, cookie keys, encryption keys |
| Cloud credentials | Service-account JSON files, AWS access key pairs |
Not secrets: model names, base URLs, timeouts, feature flags, .env.example, public keys, non-sensitive identifiers. When in doubt: would exposure let someone spend money, read private data, or impersonate you? Then it is a secret.
5.2 The never-list#
A secret must never appear in:
- Source code — not even "temporarily", not even in a comment, not even "just for a test"
- Git — committed files and history (deleting the line doesn't delete the commit)
- Logs — including tracebacks that echo request headers or config objects; this is why
SecretStrexists - Error messages / exceptions —
raise ValueError(f"bad key {key}")ships the key to every log aggregator - Screenshots and screen shares — terminals,
.envin an editor,envoutput - Chat prompts and issue trackers — pasting a traceback that contains a header is a leak
- URLs —
?api_key=...lands in server logs, proxies, browser history and Referer headers; keys belong inAuthorizationheaders, never query strings - Notebooks — a cell that prints
os.environor an SDK client dumps every key into.ipynboutput, which is committed - CI logs — echoing env "to debug" publishes secrets to anyone who can read the build log
- AI assistants' context — coding assistants, IDE agents and chat tools can read whatever files you open or let them index, and they send that text to a model provider. Keep real keys out of any file an assistant may read: exclude
.envfrom the tool's indexing or ignore list where it offers one, never paste a.envor a fullos.environdump into a chat, and keep keys out of MCP and agent configuration files that live in the repository (reference an environment variable instead). Treat a key that was pasted into a chat as leaked (5.5)
5.3 Redaction helpers#
Defence in depth: even with SecretStr, raw strings leak through f-strings, third-party logs and tracebacks. A small redactor masks credential-shaped spans before text reaches a log:
# redact.py — stdlib only
import re
PATTERNS = [
# Vendor-shaped tokens. The shapes differ per vendor: most prefixes take a
# "-" or "_" separator, but classic Google API keys are "AIza" + ~35 chars
# with NO separator, and fine-grained GitHub PATs start "github_pat_".
(re.compile(r"(?i)\b(?:sk|pk|api|key|token|secret|bearer|ghp|gho|xox[baprs])[-_][A-Za-z0-9_\-]{6,}"), "<token>"),
(re.compile(r"\bAIza[A-Za-z0-9_\-]{20,}"), "<token>"),
(re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}"), "<token>"),
# KEY=value pairs named like credentials — the capture group feeds \1 below.
(re.compile(r"(?i)\b(api[_-]?key|api[_-]?secret|access[_-]?token|auth[_-]?token|password|passwd|secret|client[_-]?secret)\s*=\s*[^\s,;]+"), r"\1=<redacted>"),
(re.compile(r"(?i)\bauthorization\s*:\s*bearer\s+\S+"), "Authorization: Bearer <redacted>"),
]
def redact(text: str) -> str:
for pattern, repl in PATTERNS:
text = pattern.sub(repl, text)
return text
log_line = (
"POST /v1/chat 200 1.2s "
"OPENAI_API_KEY=sk-EXAMPLE-not-a-real-key-123 "
"gemini_key=AIzaSyEXAMPLE0000000000000000000000000000000000 "
"github_token=github_pat_EXAMPLE00000000000000000000 "
"Authorization: Bearer sk-EXAMPLE-not-a-real-key-123 "
"password=hunter2 retries=3"
)
print("raw :", log_line)
print("redact:", redact(log_line))raw : POST /v1/chat 200 1.2s OPENAI_API_KEY=sk-EXAMPLE-not-a-real-key-123 gemini_key=AIzaSyEXAMPLE0000000000000000000000000000000000 github_token=github_pat_EXAMPLE00000000000000000000 Authorization: Bearer sk-EXAMPLE-not-a-real-key-123 password=hunter2 retries=3
redact: POST /v1/chat 200 1.2s OPENAI_API_KEY=<token> gemini_key=<token> github_token=<token> Authorization: Bearer <redacted> password=<redacted> retries=3This is a pattern-based net — useful, never sufficient. The stronger pattern is structural: log an allow-list of safe headers (as 03.10 §2.3 does for HTTP hooks) and SecretStr for config, so secrets are never in the string you redact in the first place. 03.10 §4.5 builds the production version.
5.4 Rotation and least-privilege keys#
Two habits that make leaks survivable:
- Least privilege. Give each key the narrowest scope that works — one project/workspace per app and environment, service-account keys for applications, short expiries where offered. A leaked dev key should not be able to touch prod. The provider-side detail is 03.1 §3.2; 12.7 §3 covers it as a security control.
- Rotate before you need to. Know the drill: create replacement → deploy → revoke old → verify. Practise it once so it's boring when it matters. 03.1 §3.6 and 11C.1 §4.3 have the zero-downtime sequence.
5.5 When a key leaks: the first hour#
Assume it will happen. The drill, from 03.1 §3.7 (which owns the provider-side detail):
- Revoke first, investigate second — a revoked key can't be abused while you look.
- Deploy the replacement everywhere the old one was used.
- Audit provider usage filtered to the leaked key; note when abuse started.
- Check spend limits are set (03.1 §3.3) — they are your circuit breaker.
- Deleting the commit is not enough — git history, forks, CI logs and caches keep copies. Rotation is what actually fixes it; then find why it leaked and close the gap.
5.6 Secret scanning and the .gitignore check#
Three layers of scanning, in increasing strength:
.gitignorecorrectness — verify, don't assume. The script below (stdlib plus thegitcommand only) checks that.envvariants are ignored and that no tracked file contains a key-shaped string:
# check_secrets_hygiene.py — run from a git repo root
import re
import subprocess
import sys
from pathlib import Path
CANDIDATES = [".env", ".env.local", ".env.production", ".env.development", ".env.example"]
ALLOWLIST = {".env.example"} # may be committed — but its CONTENTS are still scanned
SECRET_RES = [
# Vendor-shaped tokens. Most prefixes take a "-" or "_" separator; classic
# Google API keys are "AIza" + ~35 chars with NO separator; fine-grained
# GitHub PATs start "github_pat_". ghp/gho/ghu/ghs/ghr are the other GitHub token kinds.
re.compile(r"\b(?:sk|pk|api|key|token|secret|bearer|ghp|gho|ghu|ghs|ghr|xox[baprs])[-_][A-Za-z0-9_\-]{12,}"),
re.compile(r"\bAIza[A-Za-z0-9_\-]{20,}"),
re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}"),
re.compile(r"(?i)\b(?:api[_-]?key|api[_-]?secret|access[_-]?token|auth[_-]?token|password|client[_-]?secret)\s*=\s*['\"]?[^\s'\"]{8,}"),
re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),
]
SKIP_SUFFIXES = {".png", ".jpg", ".jpeg", ".gif", ".pdf", ".lock", ".woff", ".woff2"}
def git(*args):
return subprocess.run(["git", *args], capture_output=True, text=True)
def is_tracked(path):
return git("ls-files", "--error-unmatch", "--", path).returncode == 0
def main() -> int:
problems = []
if not Path(".gitignore").exists():
problems.append("no .gitignore at repository root")
else:
for name in CANDIDATES:
tracked = is_tracked(name)
ignored = git("check-ignore", "-q", name).returncode == 0
if name in ALLOWLIST:
if ignored:
problems.append(f"{name} is ignored but should be committed (add a ! negation)")
elif tracked:
problems.append(f"{name} is TRACKED by git — a .env file must never be committed")
elif not ignored:
problems.append(f"{name} is NOT ignored by .gitignore")
tracked_files = git("ls-files").stdout.splitlines()
for path in tracked_files:
# ALLOWLIST exempts .env.example from the gitignore checks above only —
# its contents are still scanned: a real key in an "example" is a leak.
if not path or Path(path).suffix in SKIP_SUFFIXES:
continue
try:
text = Path(path).read_text(encoding="utf-8", errors="replace")
except OSError:
continue
for lineno, line in enumerate(text.splitlines(), 1):
if any(rx.search(line) for rx in SECRET_RES):
problems.append(f"{path}:{lineno}: possible secret (value masked)")
if problems:
print("SECRET HYGIENE CHECK: FAILED")
for p in problems:
print(" -", p)
return 1
print(f"SECRET HYGIENE CHECK: clean ({len(tracked_files)} tracked files scanned)")
return 0
if __name__ == "__main__":
sys.exit(main())Set up a scratch repo and run it — note the .env contents matter: the second problem line only appears when the file holds a credential-shaped value:
scratch=$(mktemp -d) && cd "$scratch" && git init -q
printf '.env*\n!.env.example\n' > .gitignore
printf 'OPENAI_API_KEY=\n' > .env.example # placeholder: name only, empty value
printf 'OPENAI_API_KEY=sk-EXAMPLE-not-a-real-key-123\n' > .env # real-shaped value, never committed
printf '# scratch\n' > README.md
cp /path/to/check_secrets_hygiene.py .
git add .gitignore .env.example README.md check_secrets_hygiene.py
python3 check_secrets_hygiene.py # clean: .env is ignored AND untracked
git add -f .env # force-add the file that must never be committed
python3 check_secrets_hygiene.py # now it must fail(Windows: run the same steps in PowerShell or WSL — git behaves identically.)
=== clean repo ===
SECRET HYGIENE CHECK: clean (4 tracked files scanned) # exit 0
=== after `git add -f .env` ===
SECRET HYGIENE CHECK: FAILED
- .env is TRACKED by git — a .env file must never be committed
- .env:1: possible secret (value masked) # exit 1One subtlety: git check-ignore reports a tracked file as "not ignored" (tracked files are exempt from ignore rules), which is why the script tests tracked-ness first — a .env that got committed is the worst case and must be named as such.
- File permissions —
.envshould be owner-only (chmod 600 .env) on any machine other people can log into; a world-readable.envleaks every key to every local account. On shared servers, prefer mounted secret files or a secret manager over a loose.env(5.7). - Pre-commit / CI scanners: gitleaks (
gitleaks gitscans history; has a pre-commit hook) and git-secrets are the standard open-source options; GitHub's push protection rejects pushes containing known key formats at the remote. 03.1 §3.7 surveys them; 11C.2 wires scanning into CI; 12.7 §5 covers it as supply-chain defence. - Run the hygiene script in CI on every PR — it costs nothing and catches the
.env-committed-by-mistake class permanently.
5.7 Secret managers and CI secrets#
.env ends at your laptop. The production ladder, from least to most isolated:
| Mechanism | Where | Notes |
|---|---|---|
.env file |
Local dev only | Never in images, repos, or on servers |
| Platform env vars | PaaS/containers | Injected at deploy; still visible to the process and its children |
| Mounted secret files | Docker/K8s (secrets_dir) |
Files, not env vars; rotated by remount/restart |
| Secret managers | AWS Secrets Manager, GCP Secret Manager, Azure Key Vault, HashiCorp Vault | Encrypted store, access control, audit log, rotation API; your code fetches at start-up or the platform injects |
| Workload identity / keyless | Cloud IAM, OIDC federation | No long-lived secret exists to leak — the best option where offered (03.1 §3.2) |
The application code is identical in every row — that is the point of reading config from the environment: only the source changes. 03.1 §3.8 owns the provider-side detail of secret managers and keyless auth; CI systems have their own secrets store (GitHub Actions secrets, GitLab CI variables) that injects variables into jobs — with the caveat that PRs from forks don't get secrets, a feature not a bug (11C.2 §4.2 relies on it). Deployment-depth treatment: 11C.1 Part 4; the security review: 12.7 Part 3.
5.8 The provider environment variable names#
The SDKs read their keys from the environment automatically — verified against each SDK's docs as of November 2026:
| Provider | Key env var(s) | Notes |
|---|---|---|
OpenAI (openai) |
OPENAI_API_KEY (required); OPENAI_BASE_URL, OPENAI_ORG_ID, OPENAI_PROJECT_ID, OPENAI_LOG, OPENAI_AUTH_MODE |
OpenAI() with no args picks them all up |
Anthropic (anthropic) |
ANTHROPIC_API_KEY |
Anthropic() likewise; workspace header is separate config |
Gemini (google-genai) |
GEMINI_API_KEY or GOOGLE_API_KEY — if both set, GOOGLE_API_KEY wins; enterprise mode reads GOOGLE_GENAI_USE_ENTERPRISE, GOOGLE_CLOUD_PROJECT, GOOGLE_CLOUD_LOCATION |
Set only one of the two key vars; aitoolkit.settings accepts both via AliasChoices (4.3b) |
| OpenRouter | OPENROUTER_API_KEY |
Used with the openrouter SDK, or passed as api_key to the openai SDK with base_url="https://openrouter.ai/api/v1" |
Each SDK reads further variables beyond the key ones — auth tokens, alternate base URLs, cloud-provider variants (AZURE_OPENAI_*, Bedrock/Vertex settings, ANTHROPIC_AUTH_TOKEN, ANTHROPIC_BASE_URL, …). Check each SDK's README or client source for the full list; the table lists the variables you will actually set.
Model names and base URLs are also configuration — which is why aitoolkit.settings carries openai_model, openai_base_url and friends as fields (4.13). Rotating a model is then an env-var change, not a deploy. 03.1 §3.4 shows the .env these names live in; 03.10 §3.5 is the "stray variable changed where my calls go" debugging section worth reading after this lesson.
5.9 Failure gallery#
The six failures this lesson exists to prevent — what each looks like when it happens, and the fix.
1. .env committed to git
Trigger: git add .env, or git add -A before .gitignore covered it.
$ git ls-files | grep -i env
.env # <- tracked: the leak is already in the index/history
.env.exampleFix: git rm --cached .env, confirm the ignore rule, then rotate the key — removing the file does not remove the commit (5.5). The hygiene script (5.6) catches exactly this.
2. Key dumped from a notebook
Trigger: a cell that inspects the environment or an SDK client — the .ipynb file stores cell outputs, so the dump is committed with the notebook:
# notebook cell — the output below is now inside the committed .ipynb
import os
print({k: v for k, v in os.environ.items() if "KEY" in k}){'OPENAI_API_KEY': 'sk-...', 'ANTHROPIC_API_KEY': 'sk-ant-...'}Fix: print names only (sorted(os.environ)), mask values before printing, and treat notebooks as code in review — they hold outputs, not just inputs.
3. load_dotenv() called too late
Trigger: the call sits in a module imported after whatever reads the environment — settings construction, SDK client creation, os.environ.get:
# WRONG ORDER — settings.py is imported first, .env loads after it
from aitoolkit.settings import get_settings # Settings() built before .env existed
from dotenv import load_dotenv
load_dotenv() # too late: nothing re-reads os.environSymptom: a variable that is in .env still reports missing — with fail_fast.py you get error: required environment variable OPENAI_API_KEY is not set.; with BaseSettings you get the ValidationError of 4.5. Fix: load once, first thing, in the entry point (3.6) — or skip load_dotenv() entirely and let env_file=".env" do it inside Settings().
4. "False" string being truthy
Trigger: DEBUG=false exported or in .env, then a hand-rolled check:
if os.environ.get("DEBUG"): # 'false' is a non-empty string -> truthy -> ON
enable_debug_mode()debug flag is ON <- the trap: the string 'false' is truthyFix: parse explicitly (raw.lower() in {"1", "true", "yes", "on"}) or declare debug: bool on BaseSettings and let Pydantic coerce (2.3, 4.3).
5. Placeholder or default "secrets"
Trigger: a field default that looks like a key, or .env.example values copied verbatim into .env:
class Settings(BaseSettings):
openai_api_key: SecretStr = "sk-..." # a "default" that is not a keyTwo failures in one: the placeholder can itself be a real-looking string that leaks intent, and is not None checks can never distinguish "no key configured" from "key configured". Fix: SecretStr | None = None, check is not None at the client boundary, and delete-or-fill every KEY= line when copying .env.example (4.3b).
6. Logging the settings object
Trigger: logger.info("config: %s", settings) or print(settings) on a class whose key fields are plain str:
app_env='prod' openai_api_key='sk-live-realkeyvalue' port=8000 max_retries=2Fix: declare secrets as SecretStr so the default repr/dump shows **********, and never log the result of get_secret_value() — model_dump() is safe to log because the wrappers mask (4.4, 4.9). If the object was built from os.environ directly rather than Settings, there is no wrapper at all — another reason to centralise config.
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Env vars are for secrets only." | They are for all per-deploy configuration — timeouts, model names, flags. Secrets are just the subset needing the most care. |
"os.getenv('DEBUG') tells me if debug is on." |
It returns the string 'false', which is truthy. Parse booleans explicitly or use Pydantic. |
| "Missing and empty env vars are the same." | None/KeyError vs "" are different states; if os.environ.get("X") conflates them (usually fine, sometimes not). |
".env is loaded automatically." |
Only if you call load_dotenv(), use pydantic-settings, or uv run --env-file. Python itself never reads .env. |
"The .env value wins because it's the file." |
No — real environment variables beat .env by default (override=False). That is why "I edited .env and nothing changed" happens. |
"Committing .env.example with real-looking keys is fine." |
It is fine only if values are empty or obvious placeholders — scanners and humans both flag sk--shaped strings even in "examples". |
"SecretStr makes the key safe everywhere." |
It makes the default repr/dump safe. get_secret_value() still returns the raw string, and keys in URLs, query params or child-process envs bypass it entirely. |
| "Deleting the commit removes the leaked key." | Git history, forks, CI logs and caches keep copies. Rotate the key — that is the fix; scrubbing is cosmetic. |
"A .env in the repo root is automatically ignored." |
Only if .gitignore says so — verify with git check-ignore or the hygiene script; .env* patterns need a !.env.example negation. |
"extra="forbid" is always the right settings default." |
For BaseSettings it is the default and catches typos — but it makes every .env line mandatory-match, so a .env shared with other tools breaks you. Choose extra="ignore" for shared files. |
| "Environment variables are secret storage." | They are readable by the process and its children (/proc, ps eww), visible in crash dumps and env output. Secret managers and keyless auth are the production answer. |
Key takeaways#
- Config varies per deploy; code doesn't. Keys, URLs, model names, timeouts, flags — all environment-injected, never hard-coded.
os.environis strings-only. Convert at one boundary;"false"is truthy; missing (None) ≠ empty ("").- Fail fast at start-up with
sys.exitor — better — apydantic.ValidationErrorlisting every missing field. .envis a dev convenience:load_dotenv()/pydantic-settingsread it, env vars beat it by default, and it is never committed (.env*+!.env.examplein.gitignore, verified).pydantic-settingsis the professional form: typed fields, validation,SecretStr,get_settings()+lru_cache, precedence CLI > init > env > dotenv > secrets_dir > defaults.- Secrets obey the never-list: no code, git, logs, errors, screenshots, chat, URLs, notebooks or CI echoes — and you verify
.gitignorerather than assume it. - Production swaps the source, not the code: env vars → mounted secret files → secret managers → keyless workload identity.
Where you'll use this in the AI path#
| Skill from this lesson | Used in |
|---|---|
.env + provider key names |
03.1 §3.4 keys in a project — the .env every API lesson uses |
get_settings() / pydantic-settings |
11C.1 §2.2 settings with pydantic-settings — the production llm_service |
| Env vars vs secrets in deploys | 11C.1 Part 4 configuration and secrets |
| Secrets in CI | 11C.2 §4.2 eval workflow, 03.10 §12.3 |
| Key hygiene as security | 12.7 Part 3 API keys, 12.10 |
| Settings consumed by clients | 01B.5 httpx client, 01B.7 FastAPI, 01B.9 retries — all read aitoolkit.settings |
| Env in tests | 01B.8 pytest (monkeypatch.setenv), 03.10 §3.5 |
| Config as code at scale | 07.11 §7.1 environments and configuration as code |
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Environment variable | A named string the OS passes to every process; the carrier for config and secrets |
os.environ |
Python's mutable mapping onto the process environment |
.env file |
A KEY=value file loaded into the environment at start-up; development only, never committed |
python-dotenv |
The library that parses .env files (load_dotenv, dotenv_values, find_dotenv) |
.env.example |
The committed template listing variable names without values |
pydantic-settings / BaseSettings |
Settings class that validates env vars + .env into typed fields |
SettingsConfigDict |
The model_config options controlling sources, prefixes, nesting, extra |
SecretStr / SecretBytes |
Pydantic wrappers whose repr/dump shows **********; unwrap via get_secret_value() |
get_settings() |
The lru_cache-backed factory returning the process-wide Settings |
secrets_dir |
Directory of per-name secret files (Docker/K8s mounts) read as a settings source |
| Source priority | CLI > init kwargs > env vars > dotenv > secrets_dir > defaults |
env_nested_delimiter |
__ separator mapping A__B env vars into nested models |
validation_alias / AliasChoices |
Field-level list of accepted input names; first found wins — how one field reads several env-var spellings |
| Fail fast | Validating required config at start-up so errors surface before request one |
| Redaction | Masking credential-shaped spans before text reaches logs or errors |
| Key rotation | Replacing a key with a new one without downtime, then revoking the old |
| Least-privilege key | A credential scoped to the narrowest project/workspace/environment that works |
| Secret manager | Encrypted store with access control, audit log and rotation (AWS/GCP/Azure/Vault) |
| Workload identity | Keyless auth exchanging a cloud identity token for short-lived credentials |
tomllib |
Stdlib TOML parser (3.11+); load needs a binary file object |
direnv |
Shell extension loading per-directory env vars from .envrc |
PYTHON_DOTENV_DISABLED |
Env var that disables load_dotenv() entirely |
PYDANTIC_SETTINGS_DEBUG |
Env var making pydantic-settings log every source's values in priority order |
All terms are also collected in the glossary.
Exercises#
- Env basics. In a scratch dir, write a script that prints whether
HOME-style vars you set are strings, then demonstrateos.environ.setdefaultreturning the existing value on a second call. (stdlib — runnable)
Solution
# ex1.py — run: python3 ex1.py
import os
os.environ["DEMO_MODE"] = "on"
print("value is a str:", isinstance(os.environ["DEMO_MODE"], str))
print("first :", os.environ.setdefault("EX1_REGION", "eu-west-1"))
os.environ["EX1_REGION"] = "us-east-1" # someone changed it afterwards
print("second:", os.environ.setdefault("EX1_REGION", "ap-south-1")) # keeps existing
print("final :", os.environ["EX1_REGION"])value is a str: True
first : eu-west-1
second: us-east-1
final : us-east-1setdefault only writes when the name is absent — the second call returns the existing us-east-1, not the new default.
- The
"false"trap. SetFEATURE_FLAG=falsein the environment and showif os.environ.get("FEATURE_FLAG")takes the wrong branch; fix it with an explicit parse and re-run.
Solution
# ex2.py — run: python3 ex2.py
import os
os.environ["FEATURE_FLAG"] = "false"
def env_bool(name: str, default: bool = False) -> bool:
raw = os.environ.get(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on"}
print("naive if ->", "ON (wrong)" if os.environ.get("FEATURE_FLAG") else "off")
print("parsed ->", "ON" if env_bool("FEATURE_FLAG") else "off")naive if -> ON (wrong)
parsed -> offThe string "false" is truthy; only an explicit parse (or debug: bool on BaseSettings) gets it right.
- Fail fast. Extend
fail_fast.pyso two missing variables are reported in one run (hint: collect errors, thensys.exit). Compare with whatSettings()gives you for free in 4.5.
Solution
# ex3.py — collect every missing name, then exit once
import os
import sys
def collect_required(names: list[str]) -> dict:
missing = [n for n in names if not os.environ.get(n)]
if missing:
sys.exit("error: missing required env vars: " + ", ".join(missing))
return {n: os.environ[n] for n in names}
cfg = collect_required(["DEMO_API_KEY", "DEMO_PROJECT_ID"])
print("both present ->", sorted(cfg))Both variables missing — one run reports both:
$ python3 ex3.py
error: missing required env vars: DEMO_API_KEY, DEMO_PROJECT_ID
$ echo "exit code: $?"
exit code: 1With both set (DEMO_API_KEY=k1 DEMO_PROJECT_ID=p9 python3 ex3.py):
both present -> ['DEMO_API_KEY', 'DEMO_PROJECT_ID']Settings() does the same collect-then-report automatically — its ValidationError lists every missing field at once, which is why 4.5 calls it the professional version of this pattern.
.envprecedence. Create.envwithAITK_PORT=1111, exportAITK_PORT=2222in the shell, and showload_dotenv()leaves2222in place; then showoverride=Trueflips it. (needspython-dotenv)
Solution
# ex4.py — needs: pip install python-dotenv
import os
from dotenv import load_dotenv
os.environ["AITK_PORT"] = "2222" # stands in for `export AITK_PORT=2222`
load_dotenv() # .env says AITK_PORT=1111
print("default :", os.environ["AITK_PORT"])
load_dotenv(override=True)
print("override=True:", os.environ["AITK_PORT"])default : 2222
override=True: 1111The real environment beats the file by default; override=True inverts that — almost never what you want outside a deliberate dev setup.
- dotenv format. Write a
.envexercising quotes,export,${VAR}expansion, a bareNOVALUEline andEMPTY=; predictdotenv_values()output for each, then check it. (needspython-dotenv)
Solution
# .env
export EXPORTED=yes
SINGLE='literal $NOT_EXPANDED'
DOMAIN=example.org
ADMIN=admin@${DOMAIN}
MULTI="line one\nline two"
EMPTY=
NOVALUE# ex5.py — needs: pip install python-dotenv
from dotenv import dotenv_values
for k, v in dotenv_values(".env").items():
print(f"{k} = {v!r}")EXPORTED = 'yes'
SINGLE = 'literal $NOT_EXPANDED'
DOMAIN = 'example.org'
ADMIN = 'admin@example.org'
MULTI = 'line one\nline two'
EMPTY = ''
NOVALUE = NoneKey predictions to check: export is stripped; single quotes block expansion while ${DOMAIN} expands inside double quotes and unquoted values; EMPTY= is '' while bare NOVALUE is None.
- pydantic-settings. Build a
Settingswithport: int,debug: bool,cors_origins: list[str]and aSecretStrkey. Set each via env var (including a JSON list) and via.env; break one value (PORT=abc) and read theValidationError. (needspydantic-settings)
Solution
# ex6.py — needs: pip install pydantic-settings
from pydantic import SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
class Settings(BaseSettings):
# extra="ignore": the Setup .env also holds ANTHROPIC_API_KEY, which this class has no
# field for, and the default extra="forbid" would reject it (see 4.2).
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
port: int = 8080
debug: bool = False
cors_origins: list[str] = []
openai_api_key: SecretStr | None = NonePORT=9090 DEBUG=true CORS_ORIGINS='["https://app.example.com"]' \
OPENAI_API_KEY=sk-EXAMPLE uv run python -c "from ex6 import Settings; s = Settings(); print(s.port, s.debug, s.cors_origins, s.openai_api_key)"
# .env alternative: same names as KEY=value lines in .env
PORT=abc uv run python -c "from ex6 import Settings; Settings()"9090 True ['https://app.example.com'] **********
pydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
port
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='abc', input_type=str]Every source coerces through the same validators: env var, .env line and init kwarg all land on the same typed fields, and a bad value fails at construction — before request one.
get_settings()caching. Prove the cache works: callget_settings()twice,cache_clear(), change an env var, call again — show the new value appears only after the clear.
Solution
The real get_settings() needs pydantic-settings, but the caching mechanics are pure stdlib — this replica (same @lru_cache(maxsize=1) shape as 4.6) runs for real:
# ex7.py — stdlib replica of the get_settings() pattern
import os
from functools import lru_cache
@lru_cache(maxsize=1)
def get_config():
print(" (rebuilding from environment...)")
return {"region": os.environ.get("AITK_REGION", "eu-west-1")}
print(get_config())
print(get_config()) # cache hit: no rebuild
os.environ["AITK_REGION"] = "test-region"
print("before clear:", get_config()) # still the OLD cached value
get_config.cache_clear()
print("after clear :", get_config()) # rebuilt with the new env var (rebuilding from environment...)
{'region': 'eu-west-1'}
{'region': 'eu-west-1'}
before clear: {'region': 'eu-west-1'}
(rebuilding from environment...)
after clear : {'region': 'test-region'}Two calls, one build; the env change is invisible until cache_clear() — exactly the behaviour get_settings() has, which is why tests must clear it (or use app.dependency_overrides) after monkeypatch.setenv.
- Redaction. Feed
redact()a log line containing anAuthorization: Bearer ...header, anapi_key=...pair, anAIza...Google key, agithub_pat_...token and a clean word likemonkey. Which spans survive? Then add a pattern for a vendor the list misses — Groq-stylegsk_...keys are a good choice — and test it.
Solution
# ex8.py — imports PATTERNS/redact from the lesson's redact.py, then extends it
import re
# (paste PATTERNS and redact() from §5.3 here, or import them)
line = (
"req id=7 api_key=sk-EXAMPLE-abcdef123456 "
"Authorization: Bearer sk-EXAMPLE-abcdef123456 "
"google=AIzaSyEXAMPLE0000000000000000000000000000000000 "
"gh=github_pat_EXAMPLE00000000000000000000 word=monkey"
)
print("in :", line)
print("out:", redact(line))
# Groq keys start gsk_ — not in the vendor list, so add one:
PATTERNS.insert(0, (re.compile(r"\bgsk_[A-Za-z0-9]{20,}"), "<token>"))
print("gsk :", redact("groq_key=gsk_EXAMPLE0000000000000000000000 tail"))in : req id=7 api_key=sk-EXAMPLE-abcdef123456 Authorization: Bearer sk-EXAMPLE-abcdef123456 google=AIzaSyEXAMPLE0000000000000000000000000000000000 gh=github_pat_EXAMPLE00000000000000000000 word=monkey
out: req id=7 api_key=<redacted> Authorization: Bearer <redacted> google=<token> gh=<token> word=monkey
gsk : groq_key=<token> tailEvery credential-shaped span is masked; word=monkey survives because monkey is not a credential name and key inside it has no =-pair or vendor prefix. The gsk_ addition shows the pattern: know each vendor's shape, not just its name.
- Hygiene script. In a scratch git repo, run
check_secrets_hygiene.pythree ways: clean,.envcommitted viagit add -f, and a fakesk-...string in a tracked.py. Paste all three outputs.
Solution
Follow the scratch-repo setup from 5.6, then add app.py containing FAKE = "sk-EXAMPLEdeadbeef1234567890" and git add app.py for the third run.
=== clean repo ===
SECRET HYGIENE CHECK: clean (4 tracked files scanned) # exit 0
=== after `git add -f .env` ===
SECRET HYGIENE CHECK: FAILED
- .env is TRACKED by git — a .env file must never be committed
- .env:1: possible secret (value masked) # exit 1
=== fake sk- in tracked app.py (.env ignored) ===
SECRET HYGIENE CHECK: FAILED
- app.py:1: possible secret (value masked) # exit 1The third run is the subtle one: .env stays ignored and untracked, yet the scanner still catches the key-shaped string in a normal source file — that is the whole point of scanning contents, not just filenames.
- Precedence table. For each row of the 4.12 table, write one sentence describing a realistic situation where that source should win.
Solution
- CLI args —
prog --timeout 5during an incident: the operator's explicit choice must beat everything persisted. - Init kwargs — a test constructing
Settings(openai_api_key="test-key"): the override is deliberate and must not be clobbered by a developer's real.env. - Env vars — CI injecting
OPENAI_BASE_URLfor a staging proxy: the deploy environment is more specific than any file on disk. .envfile — local development, where the file is the developer's chosen configuration and the shell has nothing set.secrets_dir— a Kubernetes pod where the orchestrator mounted/var/run/secrets/openai_api_key: the platform's secret beats code defaults but loses to an explicit env override.- Defaults — a fresh clone with no config at all:
port=8080,max_retries=2let the app boot so aValidationErrornames only what is genuinely missing.
The pattern behind all six: the more deliberate and local the source, the higher it ranks — explicit beats ambient, ambient beats file, file beats default.
- Provider vars. Write the
.envblock a learner needs for all four providers (names only, placeholder values) and explain whyGOOGLE_API_KEYandGEMINI_API_KEYshould not both be set.
Solution
# .env — names only, safe to commit as .env.example; fill real values in .env
OPENAI_API_KEY=
ANTHROPIC_API_KEY=
GEMINI_API_KEY=
# GOOGLE_API_KEY= # alternative name google-genai also reads
OPENROUTER_API_KEY=GOOGLE_API_KEY and GEMINI_API_KEY should not both carry different values: the SDK gives GOOGLE_API_KEY precedence when both are set, so a stale GOOGLE_API_KEY in your shell profile silently wins over the fresh GEMINI_API_KEY you just added to .env — calls keep using the old key and the new one looks broken. Pick one name (GEMINI_API_KEY is the explicit choice); aitoolkit.settings accepts either via AliasChoices (4.3b), mirroring the SDK's precedence.
- Config file vs env. Argue both sides: when would you put
max_retriesinaitoolkit.tomlinstead of an env var? What breaks if ops needs to change it during an incident?
Solution
For the file: max_retries is a behavioural knob, not a secret — it is identical across environments, benefits from being versioned and reviewed in git, and a TOML file keeps related tuning (retry.max_attempts, retry.backoff_seconds) grouped readably. Non-secret, stable, shared config belongs in a committed file; env vars are the wrong tool for values you want code-reviewed.
Against the file: a config file is baked into the deploy artifact — changing max_retries means editing the file, committing, rebuilding and redeploying. During an incident (provider rate-limiting you, needing more retries now), ops cannot touch a file inside a running container; they can set an env var or a platform setting in seconds. The twelve-factor answer: anything you might need to change without a release is env-injected; anything stable and non-secret can live in the repo. A pragmatic split: defaults and structure in aitoolkit.toml, per-deploy overrides (and all secrets) in the environment — with env winning over file, exactly the precedence rule of 4.12.
Check yourself#
- What are the two properties of
os.environvalues that cause most config bugs?Everything is a string (needs deliberate conversion), and missing (None/KeyError) is different from empty (""). - Why is
bool(os.environ.get("DEBUG"))wrong for aDEBUG=falsevariable?"false"is a non-empty string, hence truthy — the feature stays on. Parse explicitly or use Pydantic's bool coercion. - Name three places a missing-variable error should not first surface, and where it should.Not inside request handlers, mid-request, or in production at 2 a.m. — it should surface at start-up, before serving traffic.
- What does
load_dotenv()do by default when a variable exists in both the shell and.env?The shell/environment value wins (override=False); the file only fills gaps. - How do you make
load_dotenv()never load anything?SetPYTHON_DOTENV_DISABLED=1, or don't callload_dotenv()/ pass_env_file=NonetoBaseSettings. - What's the difference between a bare
FOOline andFOO=in a.envfile?FOO→dotenv_valuesgivesNoneandload_dotenvignores it;FOO=→ empty string"". - Why is
extra="forbid"theBaseSettingsdefault, and when does it hurt?It catches typos/stray.envlines — but makes every dotenv entry mandatory-match, so a.envshared with other tools breaksSettings(); useextra="ignore"there. - How does a
SecretStrfield behave inmodel_dump_json(), and how do you get the real value?It serialises as"**********";get_secret_value()unwraps the real string — the only way. - List the source priority order and give the one-line rule behind it.CLI args > init kwargs > env vars > dotenv > secrets_dir > defaults. Explicit beats ambient; ambient beats file; file beats default.
- What does
secrets_dirread, and which sources still beat it?Per-field files in a directory (Docker/K8s secret mounts); env vars and dotenv still take priority. - Name four places a secret must never appear.Code, git (incl. history), logs/error messages, screenshots/screen shares, chat prompts, URLs/query strings, notebooks, CI logs.
- Why is deleting a leaked key's commit insufficient, and what actually fixes the leak?History, forks, CI logs and caches retain copies — rotating the key is the fix; scrubbing is cosmetic.
git check-ignoresays a tracked.envis "not ignored" — why, and how should a checker handle it?Tracked files are exempt from ignore rules, so check-ignore returns non-zero; testgit ls-files --error-unmatchfirst and report "TRACKED".- Which env vars do the four provider SDKs read automatically?
OPENAI_API_KEY,ANTHROPIC_API_KEY,GEMINI_API_KEY/GOOGLE_API_KEY(latter wins if both),OPENROUTER_API_KEY.
Further resources#
- The Twelve-Factor App — Config: the principle this lesson operationalises.
- python-dotenv documentation (PyPI version 1.2.4 as of November 2026): file format,
load_dotenv/dotenv_values/find_dotenv,PYTHON_DOTENV_DISABLED. - Pydantic Settings documentation (PyPI version 2.16.2 as of November 2026):
SettingsConfigDict, source priority,secrets_dir,CliSettingsSource, file sources,PYDANTIC_SETTINGS_DEBUG. - Pydantic types — SecretStr: masking,
get_secret_value(), constant-time comparison. tomllibandos.environ— stdlib references.- direnv and gitleaks — shell-side env loading and secret scanning.
- 03.1 Part 3: provider accounts, scoped keys, spend limits and the leak drill this lesson links to rather than repeats.
- 12.7 Part 3: keys and secret security as a security-engineering topic.
← 01B.1 — Project Setup with uv: Environments, Dependencies and Tooling | Module 01B overview | 01B.3 — Async Python: async/await and the Event Loop →