Python "KeyError" loading config in CI
Indexing a dict with config[key] raises KeyError when that key is absent. In CI the failure often appears because a config file, environment variable, or secret that exists on a developer machine is missing on the runner.
What this error means
A test or startup step fails with "KeyError: 'DATABASE_URL'" (or similar) inside a config-loading function. It passes locally and fails only in CI.
python
File "app/config.py", line 22, in load
dsn = config["DATABASE_URL"]
KeyError: 'DATABASE_URL'Common causes
A required key is not provided in CI
The key lives in a local .env or shell profile that the CI runner does not have, so the dict lacks it.
A typo or case mismatch in the key name
The config file uses one spelling and the code another; the lookup misses and raises.
How to fix it
Use .get() with a default or an explicit check
- Replace
config[key]withconfig.get(key)where a default is acceptable. - For required keys, validate presence up front and raise a clear message naming the missing key.
- Set the missing value in the CI job env or secrets so the key is present.
Python
dsn = config.get("DATABASE_URL")
if dsn is None:
raise RuntimeError("DATABASE_URL is not configured in this environment")How to prevent it
- Validate the full config schema at startup with a single helpful error.
- Document every required env var and set it in CI alongside local.
- Keep a checked-in example config listing all keys.
Related guides
Python "ValueError: too many values to unpack" in CIFix "ValueError: too many values to unpack (expected 2)" in CI - a sequence had more elements than the target…
Python "KeyError" from os.environ - Missing Env Var in CIFix "KeyError: 'VAR'" from os.environ[...] in CI - a required environment variable isn’t set in the job. Set…
Python "configparser.NoSectionError" in CIFix "configparser.NoSectionError" in CI - configparser was asked for a section that the loaded .ini file does…