Interview Prep/Python for DevOps/OS, filesystem, subprocess & CLIs

How do you read environment variables safely?

BeginnerConceptOS, filesystem, subprocess & CLIs
Answer
import os
region = os.environ.get("AWS_REGION", "us-east-1")   # optional with default
token = os.environ["GITHUB_TOKEN"]                    # required: KeyError if missing
debug = os.getenv("DEBUG", "false").lower() in {"1", "true", "yes"}

Environment values are always strings, so parse them explicitly (int(os.getenv("WORKERS", "4"))). Validate required variables at startup and fail fast with a clear message rather than deep inside the run. os.environ changes only affect the current process and its children.

All Python for DevOps questions Roadmap: Python for automation

More on OS, filesystem, subprocess & CLIs