Config, secrets and cloud basics¶
What you'll be able to do¶
- Load and validate configuration predictably across development, staging, and production.
- Keep credentials out of code and logs, and respond correctly when one leaks.
- Choose basic cloud resources and review access, infrastructure changes, and costs.
Configuration is an input to the program¶
Code describes how an app behaves; configuration selects its database, port, model, and feature settings per deployment. Rebuilding an image just to change a database address couples it to one environment. The twelve-factor approach puts deploy-specific configuration in the environment and keeps development and production similar.
Environment variables are strings supplied to a process at startup. A config file can hold local defaults; CLI flags can override one run. This lesson uses defaults < file < environment < CLI. Thus environment PORT=8080 beats file PORT=8000, while --port 9000 wins over both. Production must not silently use development credentials.
import os
from dataclasses import dataclass
@dataclass(frozen=True)
class Config:
port: int
port = int(os.environ.get("PORT", "8000"))
if not 1 <= port <= 65535:
raise ValueError("PORT must be between 1 and 65535")
config = Config(port=port)
Merging is a loop from lowest to highest precedence, followed by explicit parsing. The text "false" is a non-empty string, so bool("false") is True:
sources = [
{"PORT": "7000", "DEBUG": "false"}, # defaults
{"PORT": "8000"}, # file
{"DEBUG": "yes"}, # environment
{}, # CLI
]
merged = {}
for source in sources:
merged.update(source) # later sources win
flags = {"true": True, "yes": True, "false": False, "no": False}
port = int(merged["PORT"])
debug = flags[merged["DEBUG"].lower()]
assert (port, debug) == (8000, True)
Startup validation rejects bad values before accepting traffic. Collect parsed values in a typed config object, such as a dataclass, so later code sees integers and booleans, not strings. Name missing settings in errors without printing their values. Run the same code and deployment shape in development, staging, and production, with separate resources and credentials. Staging can use smaller capacity.
Secrets need a different lifecycle¶
API keys, tokens, database passwords, and private keys are secrets because possession can grant access. A port usually is not. Keep credentials out of git, images, logs, notebooks, URLs, and chat. URLs can appear in browser and server logs; notebook outputs persist after cells change. A local .env file must be excluded from version control and protected.
A secret manager stores credentials and controls retrieval. Give each service identity access only to its own secrets. Prefer short-lived credentials where supported, limiting an exposed key's useful life. Rotation replaces a credential and updates its users; coordinate the cutover to avoid outages. Pre-commit and CI scanners catch common patterns, but miss some credentials and flag innocent text.
If a key leaks, contain it immediately. Issue a replacement, update its users, and revoke the old key as quickly as the exposure and service continuity allow; when abuse is likely, revoke at once and accept the interruption. Then inspect usage and remove exposed copies from code and artifacts. Rewriting git history cannot revoke a key or erase copies already pulled. One shared administrator key turns one leak into broad access.
Redact structured logs and validation errors before they are written:
SECRET_KEYS = {"api_key", "password", "database_url"}
event = {"model": "demo", "api_key": "not-a-real-key"}
safe = {k: "[REDACTED]" if k.lower() in SECRET_KEYS else v
for k, v in event.items()}
assert safe == {"model": "demo", "api_key": "[REDACTED]"}
assert event["api_key"] == "not-a-real-key" # input unchanged
This checks only top-level key names. Also walk nested data and inspect values: a password can hide in a URL such as postgresql://user:password@host/db.
The cloud is a set of building blocks¶
Providers use different product names, but the underlying choices are similar:
| Need | Common primitive | What it supplies |
|---|---|---|
| Run code | VM, container service, serverless function | CPU, memory, sometimes GPU |
| Store data | Object, block, or file storage | Objects via API, disk-like volumes, or shared files |
| Connect services | Private network, subnet, firewall, load balancer, DNS | Reachability, traffic filtering, routing, names |
| Avoid operating a component | Managed database or queue | A provider-operated service with your data and settings |
A region is a geographic service area; an availability zone is a failure domain within it. Spreading replicas across zones helps with a zone failure; a region failure needs a separate plan. See failover and disaster recovery. Private networks and subnets shape reachability; firewalls or security groups allow required connections. DNS names endpoints; load balancers distribute requests.
Charges may depend on provisioned compute time, stored bytes, requests, and data transfer; check each service's billing units. Idle machines still cost money, and data leaving a provider can incur egress charges. Check what stays provisioned between requests.
Identity and responsibility are part of the design¶
IAM controls actions on resources. An identity is a person or service account. A role groups permissions; a policy names actions and resources. Start from default deny and grant the smallest useful scope. A model reader should not delete buckets. In the simplified policy model used by this lab, a matching explicit Deny beats a matching Allow, even a wildcard one; without a matching Allow, access is denied. Real evaluation rules differ between providers and policy types, so check yours before relying on this.
Under shared responsibility, the provider operates underlying facilities; you configure identities, network exposure, data access, code, and often backups. The division varies by service. A managed database does not decide who may query your data. Authentication identifies app users; IAM governs cloud resources.
Choose compute by the work it must do¶
A VM gives operating-system control and supports long-running jobs, with more maintenance. A container service runs packaged apps while managing hosts; see Docker and containers. A serverless function fits short, event-driven work, but startup delay, execution limits, and hardware may matter. Kubernetes controls scheduling across a container fleet, with more operations work.
Compare traffic, startup tolerance, host control, job duration, GPU availability, and operations burden. A function with cold starts may suit an occasional batch trigger but miss a tight latency target. Estimate active and idle time: a GPU machine used 2 hours daily but left on all day consumes 24 machine-hours, 12 times the intended 2 hours.
Record infrastructure and guard the bill¶
Infrastructure as code describes desired resources in files; Terraform and CloudFormation are examples. Before changing anything, the tool compares current and desired state. Review the proposed changes (a Terraform plan or a CloudFormation change set) and their create, update, and delete actions before applying them. Reapplying the same definition should be idempotent, without duplicate resources. Console changes cause drift from the definition. Version-control definitions and review plans.
Tag owner, environment, and purpose. Set budgets and alerts; alerts do not automatically cap spending. Shut down idle GPUs and use storage lifecycle rules for old checkpoints. Separate development and production resources.
For AI engineers¶
For AI engineers
Your training script may read a dataset from object storage and call an LLM API. A notebook with a pasted key can leak through outputs or a public repository; leaked keys can be abused quickly. Use separate service identities and keys for development and production, with the narrowest permissions and spending limits available. Give a pipeline service account read access to its private data bucket and write access only to its output location, instead of using your personal credentials. Check that the bucket is not public. When a GPU job ends, stop its machine or let an automated job do it; a forgotten idle instance can dominate a small project's bill.
Common mistakes¶
- Hard-coding deployment settings: use one precedence rule and validate the final typed values at startup.
- Sharing one administrator key: issue separate credentials per environment and service, with narrow policies.
- Granting
*to make a job work: find the exact missing action and resource, then grant those only. - Baking secrets into images or build logs: retrieve them at runtime and keep them out of build output.
- Leaving data buckets public or sharing dev and prod resources: check exposure and isolate environments.
- Creating resources without a record or budget alert: review infrastructure definitions and monitor spend.
Check yourself¶
A file sets PORT=8000, the environment sets PORT=8080, and a CLI flag sets PORT=9000. What should the app use, and when should it reject PORT=abc?
It should use 9000 because CLI has highest precedence. Parse and validate the final value at startup, before serving requests; reject abc if it is the winning value.
A committed API key is removed from the latest commit. Is the incident over?
No. Old commits and copied repositories may still contain it. Contain its use immediately, move consumers to a replacement, and revoke the old key as quickly as exposure and continuity allow. Then investigate its use and remove exposed copies.
A policy allows * actions on a bucket, but another matching statement denies deletion. Can this identity delete objects?
Not under the lab's simplified model: the matching explicit deny wins over the allow, and without any matching allow, default deny applies. With a real provider, confirm its evaluation rules.
A GPU training machine runs a two-hour job and remains on for 22 more hours. What would you change?
Stop or automatically shut down the machine when the job ends, and set a budget alert. The machine ran 24 hours for 2 hours of useful work, a 12-fold difference in machine-hours.
Lab¶
Build a small configuration and cloud-safety toolkit in code/config-secrets-cloud/. Load typed settings with defaults < file < environment < CLI and reject missing required values. Redact nested log data and scan text for likely credentials without echoing their values. Evaluate a tiny IAM policy with explicit and default deny. Plan create, update, and delete actions from current and desired resources. Run: cd code/config-secrets-cloud && PYTHONPATH=starter python -m pytest tests -q
Go deeper¶
- The Twelve-Factor App for configuration and environment parity.
- MIT Missing Semester for shells and environment basics.
- Designed to Scale: authorization for permission design.
- Your Software Engineering Handbook: ch. 12 "Bảo mật API" and ch. 13 "CI/CD cơ bản".
See it in the wild¶
Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.



