Part 10 / Stage 3
Configuration and deployment
Goal: Run the same code safely in dev, staging and production — configuration from the environment, validated at startup, packaged in containers, deployed into the customer's infrastructure with secrets handled properly. Time: ~3 hours · Needs: Python 3.14+, the course venv
What you will learn
- Configuration from the environment: one build, many environments
- Validating config at startup: fail fast with clear errors
- Containers: Dockerfiles, images, and what belongs in them
- Deploying into customer infrastructure: their cloud, on-prem, restricted networks
- Secrets management: stores, rotation, never in images or git
- CI/CD: automated tests and controlled releases
Topics in this part
Practice
Work in the course venv. Check each answer by running it; compare with solutions/ only after trying.
Exercise 1: Extend the settings
Add two fields to the lesson's Settings: log_level (one of DEBUG/INFO/WARNING/ERROR, default INFO) and timeout_s (float, 0.1–120, default 10). Show a good load and a bad one (LOG_LEVEL=VERBOSE, TIMEOUT_S=0) with named errors.
Show the solution to Exercise 1
# Exercise 1: two more validated settings
from pydantic import BaseModel, Field, ValidationError
class Settings(BaseModel):
acme_api_url: str = Field(pattern=r"^https://")
acme_api_token: str = Field(min_length=10)
log_level: str = Field(default="INFO", pattern=r"^(DEBUG|INFO|WARNING|ERROR)$")
timeout_s: float = Field(default=10, ge=0.1, le=120)
def load(env):
return Settings(acme_api_url=env.get("ACME_API_URL", ""), acme_api_token=env.get("ACME_API_TOKEN", ""),
log_level=env.get("LOG_LEVEL", "INFO"), timeout_s=env.get("TIMEOUT_S", 10))
good = load({"ACME_API_URL": "https://api.acme.example", "ACME_API_TOKEN": "x" * 24})
print("loaded:", good.log_level, good.timeout_s)
try:
load({"ACME_API_URL": "https://api.acme.example", "ACME_API_TOKEN": "x" * 24,
"LOG_LEVEL": "VERBOSE", "TIMEOUT_S": "0"})
except ValidationError as e:
for err in e.errors():
print("config error:", err["loc"][0], "-", err["msg"])
Exercise 2: Secrets never print
Give Settings a __repr__/model_dump safe for logs: the token appears as **** + its last 4 characters. Print the safe dump and assert the real token is absent from it.
Show the solution to Exercise 2
# Exercise 2: settings that are safe to log
from pydantic import BaseModel, Field
class Settings(BaseModel):
acme_api_url: str
acme_api_token: str = Field(min_length=10)
def safe_dump(self):
d = self.model_dump()
d["acme_api_token"] = "****" + self.acme_api_token[-4:]
return d
s = Settings(acme_api_url="https://api.acme.example", acme_api_token="super-secret-token-abcd")
dump = s.safe_dump()
print("safe for logs:", dump)
assert "super-secret" not in str(dump)
print("real token absent: True")
Exercise 3: One more rule
Add a rule to the environment check: "staging and prod use HTTPS URLs". Break staging's URL to http:// and show the named problem; fix it and show none.
Show the solution to Exercise 3
# Exercise 3: a new deploy rule catches an http URL in staging
ENVIRONMENTS = {
"dev": {"replicas": 1, "log_level": "DEBUG", "acme_api_url": "https://sandbox.acme.example"},
"staging": {"replicas": 2, "log_level": "INFO", "acme_api_url": "http://sandbox.acme.example"},
"prod": {"replicas": 3, "log_level": "INFO", "acme_api_url": "https://api.acme.example"},
}
RULES = [
("prod has at least 2 replicas", lambda n, c: n != "prod" or c["replicas"] >= 2),
("no DEBUG logging outside dev", lambda n, c: n == "dev" or c["log_level"] != "DEBUG"),
("staging and prod use HTTPS", lambda n, c: n == "dev" or c["acme_api_url"].startswith("https://")),
]
def problems():
return [(env, rule) for env, cfg in ENVIRONMENTS.items() for rule, check in RULES if not check(env, cfg)]
print("before fix:", problems())
ENVIRONMENTS["staging"]["acme_api_url"] = "https://sandbox.acme.example"
print("after fix:", problems() or "none")
Exercise 4: Startup gate
Write main() for a service that loads settings first and exits with code 1 and a clear message when config is invalid (never a traceback). Demonstrate both paths with subprocess calls to this same file (pass the env explicitly).
Show the solution to Exercise 4
# Exercise 4: refuse to start on bad config, with a message not a traceback
import os, subprocess, sys
from pydantic import BaseModel, Field, ValidationError
class Settings(BaseModel):
acme_api_token: str = Field(min_length=10)
def main():
try:
Settings(acme_api_token=os.environ.get("ACME_API_TOKEN", ""))
except ValidationError as e:
for err in e.errors():
print(f"config error: {err['loc'][0]} - {err['msg']}", file=sys.stderr)
sys.exit(1)
print("service starting")
sys.exit(0)
if os.environ.get("AS_SERVICE"):
main()
else:
base = {k: v for k, v in os.environ.items()}
ok = subprocess.run([sys.executable, __file__], capture_output=True, text=True,
env=base | {"AS_SERVICE": "1", "ACME_API_TOKEN": "x" * 24})
bad = subprocess.run([sys.executable, __file__], capture_output=True, text=True,
env=base | {"AS_SERVICE": "1", "ACME_API_TOKEN": ""})
print("good config -> exit", ok.returncode, "|", ok.stdout.strip())
print("bad config -> exit", bad.returncode, "|", bad.stderr.strip())
assert "Traceback" not in bad.stderr
Mini-project: Deployable service
The Part 9 Shipments API made deployable: validated Settings (environment, API key, log level), a Dockerfile written to solutions/ as Dockerfile.example text, and a per-environment config check (dev/staging/prod as data + rules) that would run in CI. One script demonstrates: settings load, rules pass, service answers /healthz via TestClient.
A solution is in solutions/mini_deployable_service.py.
Stretch: deploy to a real staging environment with secrets from a secret manager and a one-command rollback.
Common mistakes
| Mistake | Why it hurts | Fix |
|---|---|---|
if env == "prod" in app logic |
Three codebases pretending to be one | Differences live in config, not code |
| Config read lazily, deep in the code | Fails hours later, confusingly | Validate everything at startup; refuse to start |
| Secrets baked into images or git | A leak with version history | Secret manager / injected env vars; rotate |
| Running containers as root | One container escape owns the host | USER nobody |
| Deploy plans ignoring customer constraints | On-prem has no internet; prod has data residency | Discover constraints in week one |
| Releases without rollback | Every bad deploy is an incident | Versioned images, one-command rollback |
Quick recap
- One build, many environments; the environment supplies what differs.
- Validate configuration at startup, reporting every error at once, by name, and refusing to start.
- Images carry the code and its dependencies; the runtime injects configuration and secrets.
- The customer's infrastructure sets the rules; find them in week one.
- For secrets, a secret manager beats injected environment variables, and git, images and logs are never acceptable; rotate secrets and scope them.
- CI checks config as data; releases are versioned, reversible, and runnable by the customer.
Checklist
- I ran the settings example and matched all four config errors.
- I can list what belongs in config vs code vs secrets.
- I can write the Part 9 service's Dockerfile from memory.
- I wrote one new environment rule and watched it catch a bad config.
- I can explain why the image never contains the token.
Read more: The twelve-factor app: config · Docker: Dockerfile reference