Skip to content
Latchkey

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

  1. Replace config[key] with config.get(key) where a default is acceptable.
  2. For required keys, validate presence up front and raise a clear message naming the missing key.
  3. 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

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →