Configuration and Secrets Across Environments
Give one artifact different configuration in every environment: declare and validate settings with pydantic-settings so a bad deploy fails at start-up, keep secret values out of errors and logs, inject secrets at run time as environment variables or mounted files, and scan every commit for leaked credentials.
Contentsand lesson path
On this page
- The problem
- Step 1: Declare and validate the settings
- Step 2: Keep secret values out of errors and output
- Step 3: Local development with a .env file
- Step 4: Inject the secret when the container starts
- Step 5: Scan every commit for secrets
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of App Deployment
- From Source to Deployable Artifact Concept · 15 min
- Configuration and Secrets Across Environments Worked example · 20 min
- Lab: Deploy Behind a Custom Domain with HTTPS and Health Checks Lab · 30 min
- Lab: Preview Deploys, Zero-Downtime Release and Rollback Lab · 30 min
- Example: Pinning and Rolling Back Model and Prompt Versions Worked example · 10 min
- Check: Production Readiness Review Knowledge check · 8 questions
What you will learn
- Supply environment-specific configuration and inject secrets at runtime, with no secrets in source code, artifacts or logs.
Prerequisites: Containerization
01. The problem
The notes API needs five settings. Four are plain configuration that differs by environment: APP_ENV, LOG_LEVEL, the base URL of the model provider and the model id. The fifth, LLM_API_KEY, is a secret. A first version often looks like this:
import os
LLM_API_KEY = "paste-the-real-key-here" # now in Git history and in every image
LOG_LEVEL = os.getenv("LOG_LEVEL", "DEBUG") # a typo in the name silently gives DEBUG
LLM_MODEL = os.getenv("LLM_MODEL") # None until the first request crashes on itThe hard-coded key is now in every clone, fork and image layer built from the repository. The default hides a misspelt variable name. And the missing model id is found by the first user who calls the summary endpoint, not by the deploy.
The goal, following the Twelve-Factor App's strict separation of config from code: one artifact, configuration and secrets supplied by each environment at run time, validated when the process starts, and secret values that never appear in source code, images or logs. A good test: could you publish the repository right now without leaking a credential?
You need Python 3.12 or later and Docker; this example was tested with pydantic 2.14 and pydantic-settings 2.16. Create the project folder that the rest of the skill builds on:
mkdir notes-api && cd notes-api && git init -q
python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "pydantic-settings==2.16.0"
mkdir app && touch app/__init__.py
python -c "import pydantic_settings; print(pydantic_settings.__version__)"2.16.002. Step 1: Declare and validate the settings
pydantic-settings reads a class's fields from environment variables, matching names without regard to case, and validates them with ordinary Pydantic types:
from functools import lru_cache
from pathlib import Path
from typing import Literal
from pydantic import Field, HttpUrl, SecretStr
from pydantic_settings import BaseSettings, SettingsConfigDict
SECRETS_DIR = Path("/run/secrets") # where Docker, Compose and Kubernetes mount secrets
class Settings(BaseSettings):
"""Runtime configuration, read once from the environment at start-up."""
model_config = SettingsConfigDict(
env_file=".env", # local development only; skipped when absent
secrets_dir=SECRETS_DIR if SECRETS_DIR.is_dir() else None,
hide_input_in_errors=True, # never echo a rejected value into the logs
)
app_env: Literal["dev", "preview", "staging", "prod"]
log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR"] = "INFO"
llm_base_url: HttpUrl
llm_model: str
llm_api_key: SecretStr = Field(min_length=20)
warmup_seconds: float = Field(default=0, ge=0, le=120)
@lru_cache
def get_settings() -> Settings:
return Settings()LiteralandHttpUrlreject values such asAPP_ENV=productionor a URL without a scheme; a field without a default is required.SecretStrprints as asterisks; the real value comes out only through.get_secret_value(), at the one place that sends the key to the provider.hide_input_in_errors=Truekeeps rejected values out of error messages (step 2).secrets_dirreads a field from a file of the same name, such as/run/secrets/llm_api_key, which is how Docker, Compose and Kubernetes deliver secrets (step 4). The check avoids a warning where the folder does not exist.get_settings()builds the object once and caches it; the service calls it at start-up.
Services usually log their effective configuration at start-up, which helps when a deploy behaves oddly. This script does what that log line will do; run it with nothing configured:
"""Print the effective configuration, as the service will log it at start-up."""
from app.settings import get_settings
for name, value in get_settings():
print(f"{name:<15} {value!r}")python show_config.pyTraceback (most recent call last):
...
pydantic_core._pydantic_core.ValidationError: 4 validation errors for Settings
app_env
Field required [type=missing]
For further information visit https://errors.pydantic.dev/2.14/v/missing
llm_base_url
Field required [type=missing]
For further information visit https://errors.pydantic.dev/2.14/v/missing
llm_model
Field required [type=missing]
For further information visit https://errors.pydantic.dev/2.14/v/missing
llm_api_key
Field required [type=missing]
For further information visit https://errors.pydantic.dev/2.14/v/missingOne error lists every missing field at once. When the service calls get_settings() during start-up, a deploy with incomplete configuration stops right here: the new instance never becomes ready, and a platform that waits for readiness keeps the previous version serving. Failing fast at start-up turns a 3 a.m. incident into a failed deploy.
03. Step 2: Keep secret values out of errors and output
Supply everything, but with a key that is too short:
export APP_ENV=prod LLM_BASE_URL=https://llm.example.com LLM_MODEL=claude-sonnet-5-5
LLM_API_KEY=sk-test-123 python show_config.py
unset APP_ENV LLM_BASE_URL LLM_MODELpydantic_core._pydantic_core.ValidationError: 1 validation error for Settings
llm_api_key
Value should have at least 20 items after validation, not 11 [type=too_short]
For further information visit https://errors.pydantic.dev/2.14/v/too_shortThe message gives the field and the problem but not the value. Without hide_input_in_errors, the same line would end with input_value='sk-test-123', and error messages are exactly what ends up in log aggregators, CI output and bug reports. A key that is merely mistyped is often still a valid key for something.
04. Step 3: Local development with a .env file
Typing five variables for every run is tedious, so env_file=".env" lets developers keep local values in a file. Commit a template with safe placeholder values, and make Git ignore the real file before it exists:
# Copy to .env for local development. Never commit .env.
APP_ENV=dev
LOG_LEVEL=DEBUG
LLM_BASE_URL=http://127.0.0.1:9000
LLM_MODEL=claude-sonnet-5-5
LLM_API_KEY=replace-me-with-a-dev-key-000printf '.env\n.venv/\n__pycache__/\nsecrets/\n' > .gitignore
cp .env.example .env
python show_config.py
LOG_LEVEL=WARNING python show_config.py | grep log_levelapp_env 'dev'
log_level 'DEBUG'
llm_base_url HttpUrl('http://127.0.0.1:9000/')
llm_model 'claude-sonnet-5-5'
llm_api_key SecretStr('**********')
warmup_seconds 0.0
log_level 'WARNING'The key prints as asterisks, so this output is safe to paste into a ticket. The last line shows the order of precedence: a real environment variable beats .env. pydantic-settings looks in this order: arguments passed in code, then environment variables, then the .env file, then the secrets folder, then defaults. That has a practical consequence. A stale LLM_API_KEY left in a platform's environment settings silently overrides the rotated key you mounted as a file, so use one mechanism per secret.
.env is a convenience for laptops only. It must never be copied into an image (the .dockerignore in lesson 3 excludes it) or used as the production mechanism.
05. Step 4: Inject the secret when the container starts
In a container, a secret reaches the process in one of two ways: as an environment variable or as a mounted file. Create a local stand-in key in a folder that only you can open, then try both. The file itself must be readable by the container's user, because Compose mounts it with the owner and mode it has on the host.
mkdir -m 700 secrets
python -c "import secrets; print('dev-' + secrets.token_urlsafe(24))" \
> secrets/llm_api_key
chmod 644 secrets/llm_api_key
docker run -d --name env-demo -e LLM_API_KEY="$(cat secrets/llm_api_key)" \
python:3.12-slim sleep 600
docker inspect env-demo --format '{{range .Config.Env}}{{println .}}{{end}}' | grep LLM_
docker rm -f env-democ1790c85a1b79c5dac89b1c17fd3db87fd55685817ee4590e811d64d7c4a3400
LLM_API_KEY=dev-RsHnsZVad22ss5GDDi_IIHLiIPD_CseB
env-demoAn environment variable works, and it is what most platforms offer, but notice where it shows up: in docker inspect (and in anything that prints it, such as a support script), in /proc/<pid>/environ inside the container, and in the environment of every child process the service starts. Crash reporters often capture the environment as well.
A mounted file has a smaller footprint. Compose secrets mount a file at /run/secrets/<name>, and secrets_dir in the settings class reads it:
services:
demo:
image: python:3.12-slim
command: ["sleep", "600"]
user: "10001" # a non-root user, as in the real image
secrets:
- llm_api_key
secrets:
llm_api_key:
file: ./secrets/llm_api_keydocker compose -f secrets-demo.yaml up -d
docker compose -f secrets-demo.yaml exec demo ls -l /run/secrets
docker inspect notes-api-demo-1 \
--format '{{range .Config.Env}}{{println .}}{{end}}' | grep -c LLM_
docker compose -f secrets-demo.yaml down Container notes-api-demo-1 Started
total 4
-rw-r--r-- 1 1000 1000 37 Oct 19 14:25 llm_api_key
0
Container notes-api-demo-1 Removed
Network notes-api_default RemovedThe key is in the container as a file and absent from its configuration (grep -c found 0 matches). The file keeps your host user as its owner (1000 here), hence mode 644 so that user 10001 can read it, while the secrets folder stays closed to other users of the machine. In lesson 3 the service reads it through secrets_dir.
On a managed platform, the secret store replaces ./secrets. You create the secret once, in the platform's store or a cloud secret manager (AWS Secrets Manager, Google Secret Manager, Azure Key Vault, HashiCorp Vault), grant read access to the service's identity only, and reference the secret by name and version in the deployment. The platform injects it as a variable or a file when an instance starts, and audits every read. On Google Cloud Run, for example:
gcloud run deploy notes-api \
--image=europe-west1-docker.pkg.dev/my-project/notes/notes-api@sha256:078e1f7b… \
--set-env-vars=APP_ENV=prod,LOG_LEVEL=INFO,LLM_MODEL=claude-sonnet-5-5 \
--set-secrets=LLM_API_KEY=llm-api-key:3The image is the same digest as in staging; only the variables and the secret reference differ. Naming secret version 3 rather than latest makes rotation explicit: you add version 4, deploy with :4, check it and then disable version 3. Use a separate key per environment, so a preview deployment never holds production's key and one leak does not compromise every environment.
06. Step 5: Scan every commit for secrets
Ignore files and reviews catch most mistakes, not all. A scanner such as gitleaks checks the full Git history for strings that look like credentials. Try it on a throwaway repository in which someone committed a key and then deleted the file:
cd .. && mkdir leak-demo && cd leak-demo && git init -q
python -c "import secrets; print(f'LLM_API_KEY = \"{secrets.token_urlsafe(32)}\"')" \
> debug_settings.py
git add debug_settings.py && git commit -qm "Add debug settings"
git rm -q debug_settings.py && git commit -qm "Remove debug settings"
docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:v8.30.1 \
git /repo --redact --no-banner -vFinding: LLM_API_KEY = "REDACTED"
Secret: REDACTED
RuleID: generic-api-key
Entropy: 4.861970
File: debug_settings.py
Line: 1
Commit: 7f8c7e775013e45d6c886390898b13c5cd6a21a7
Author: Lab
Email: [email protected]
Date: 2026-10-19T14:25:42Z
Fingerprint: 7f8c7e77…:debug_settings.py:generic-api-key:1
2:25PM INF 1 commits scanned.
2:25PM INF scanned ~75 bytes (75 bytes) in 218ms
2:25PM WRN leaks found: 1Deleting the file did not help: the key is still in history, and gitleaks exits with status 1, which fails a CI job. --redact keeps the scanner itself from printing the secret into the CI log. Run the same container as a CI step on every push, with the full history checked out, and add gitleaks as a pre-commit hook so most leaks never leave a laptop. GitHub's push protection adds a server-side check for known key formats.
secret-scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
fetch-depth: 0 # the whole history, not just the last commit
- name: Scan for secrets
run: >-
docker run --rm -v "$PWD:/repo" zricethezav/gitleaks:v8.30.1
git /repo --redact -vGo back to the project with cd ../notes-api and commit what you have: git add -A && git commit -m "Validated settings from the environment". git status should not list .env or secrets/.
07. Common mistakes
08. Check your understanding
09. Apply it
In your practice project:
- Move every setting into a validated settings class, with secrets as
SecretStrandhide_input_in_errorson, and commit a.env.examplewith placeholders. - Create the secrets in your platform's secret store, one per environment, with a low-privilege key for previews.
- Confirm that
docker history --no-truncanddocker inspectof your image show no secret values. - Add the gitleaks step to CI and watch it fail once on a throwaway branch with a fake key.
- Write a five-line rotation runbook: where the key lives, how to add, deploy and verify a new version, and when to revoke the old one.
10. Review prompt
Without looking back, answer in your own words:
- Why validate configuration at start-up rather than when a setting is first used, and what does a platform do with an instance that fails?
- What do
SecretStrandhide_input_in_errorseach protect against? - Where can a secret passed as an environment variable be read, and what changes when it is a mounted file instead?
- In what order does pydantic-settings look for a value, and how can that order cause trouble during key rotation?
- What does a secret scanner check that
.gitignorecannot, and why must the scan cover the whole history?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.