Python Environment Variables for App Config
How to keep settings and credentials out of Python code with environment variables, check them at startup and handle them safely.

Manage config with Python environment variables: keep secrets out of code, validate settings at startup, use clear names and avoid leaking values in logs.
Hard-coded settings are one of the most common problems in business automation scripts. An API key pasted into the code, a database password in a configuration file committed to Git, a production URL that has to be edited by hand before every test run. Each one is a security risk and a source of mistakes. Python environment variables offer a simple alternative: the script reads its settings from the environment it runs in, so the same code can run on a laptop, a test server and production with different values and no secrets in the repository. This guide explains how to use environment variables well, how to check them at startup and how to keep their values from leaking.
Why settings belong outside the code
The Twelve-Factor App, a methodology for building software-as-a-service apps, requires strict separation of config from code and stores config in environment variables (The Twelve-Factor App: Config). It offers a useful test: could the codebase be made open source at any moment without compromising any credentials? If the answer is no, settings and secrets are mixed into the code.
Separating them brings practical benefits for scripts:
- The same code runs in development, test and production with different values
- Secrets stay out of version control, code reviews and shared screenshots
- Rotating a password or key does not require a code change
- Each environment can have its own limited credentials
How Python environment variables work
Python reads the process environment through os.environ, a mapping of names to string values. The Python documentation notes that this mapping is captured the first time the os module is imported, typically during startup, and that later changes to the environment made outside Python are not reflected unless os.environ itself is modified (Python: os). In practice, that means a script reads the values it was started with.
Two details catch people out. First, every value is a string, so numbers, booleans and lists must be converted. Second, a missing variable raises an error when accessed directly but returns None or a default when read with get. Choose deliberately: required settings should fail loudly, while optional ones can have safe defaults.
Validate settings at startup
Read and check every setting once, at the start of the script, and stop with a clear message if anything is wrong. This prevents the worst kind of failure: a script that runs for an hour and then crashes, or silently uses a wrong value, because a setting was missing. A good startup check:
- Lists all required settings and reports every missing one at once, not just the first
- Converts types and checks ranges, such as a batch size that must be a positive number
- Checks formats, such as a URL that must start with https
- Logs which settings were loaded, without logging the secret values themselves
Put this in one small module or function and have the rest of the script use the validated values, rather than reading os.environ in many places.
Name variables clearly
Use consistent, descriptive names in capitals with underscores, prefixed by the application or integration, such as CRM_API_BASE_URL, CRM_API_TOKEN or REPORT_BATCH_SIZE. Avoid generic names like KEY or URL that clash with other tools. Document every variable in a README or an example file that lists the names with placeholder values, so a new team member knows what to set.
Worked example: a hypothetical settings plan
The table below is a hypothetical settings plan for a script that syncs orders to a CRM. It shows how to classify settings, not values to use.
VariableRequiredSecretType and checkDefaultCRM_API_BASE_URLYesNoURL starting with httpsNoneCRM_API_TOKENYesYesNon-empty stringNoneORDERS_DB_URLYesYesConnection stringNoneSYNC_BATCH_SIZENoNoPositive integer100DRY_RUNNoNotrue or falsefalseLOG_LEVELNoNoOne of the standard levelsINFO
Keep secret values from leaking
Environment variables keep secrets out of code, but they can still leak. Common ways include printing the whole environment while debugging, logging configuration objects that contain tokens, error reports that capture local variables, and child processes that inherit the environment. Protect against these:
- Never print or log os.environ as a whole
- Mask secret values when logging loaded settings
- Check what your error reporting tool captures
- Pass only the variables a child process needs
For local development, many teams keep values in a file that a library loads into the environment. If you do this, add the file to .gitignore and commit only an example file with placeholders.
Use a secrets manager where it makes sense
On servers and in containers, environment variables are usually set by the platform: a scheduler, a container orchestrator or a deployment pipeline. For sensitive credentials, consider a secrets manager that stores values encrypted, controls who can read them and records access. The platform can then inject values as environment variables at runtime. Our guide to service accounts covers how to give integrations their own limited credentials and rotate them safely.
Separate environments properly
Give each environment its own values, especially credentials. Test scripts should never hold production tokens. Where possible, make the environment explicit with a variable such as APP_ENV, and have the script refuse to run destructive operations unless it is set as expected. A dry-run setting that logs intended changes without making them is also useful when trying new data or configuration.
Review settings over time
Settings accumulate. Variables that were added for a one-off migration stay set long after the code that read them was removed, and tokens created for a former colleague's test remain valid. Review the settings for each script regularly: remove variables no longer read by the code, rotate secrets on the schedule your security policy sets and confirm that each credential still has only the permissions it needs. A short list of documented, current settings is far easier to secure than a long list nobody fully understands.
Fit settings into the wider script design
Environment variables are one part of making scripts dependable. Our guide to Python automation scripts covers timeouts, retries, logging and scheduling, which work together with clean configuration to make unattended jobs safe to run.
Frequently Asked Questions
Why use environment variables instead of a config file?
They keep secrets out of the repository and let the same code run in different environments with different values. Config files can still hold non-secret settings, as long as secrets are kept separately.
What happens if a variable is missing?
Reading it directly from os.environ raises an error, while reading it with get returns a default. Check required settings at startup and stop with a clear message if any are missing.
Are environment variables safe for secrets?
They are much safer than code, but values can leak through logs, error reports or child processes. Mask secrets in logs and consider a secrets manager for sensitive credentials.
How should I handle local development values?
Keep them in a local file excluded from version control, and commit only an example file with placeholder values.
Keep configuration clean and secure
We restructure Python automation so settings and secrets are handled safely across environments. See our custom app development services, or talk to us about Python environment variables.
About the Author
Manav Sharma is the founder of Insyrge and a CRM solutions architect. He works across Zoho, Salesforce, HubSpot, Odoo and more, designing the CRM setups, integrations and automations that keep sales and operations teams working from the same data.
Need Help Implementing This in Your Business?
Our certified Zoho consultants and automation experts can help you design and deploy custom workflows tailored to your operations.
Book Free Consultation