Sub topic 7
Moving secrets out of code and into the environment
This chapter assumes you know basic Git and the command line, what an API key or password is used for, and how environment variables work. It covers how to keep credentials out of source files, which is the most reliable way to keep them out of an AI assistant's context.
Why source code is the wrong place for a secret
An AI coding assistant reads the files you open, the files in your project, and often the files it searches on its own. Anything written in those files can end up in a prompt sent to a provider. Source control adds a second problem. A secret committed once stays in the Git history, even after you delete the line.
Hard-coded secrets therefore leak in three ways:
- The assistant reads the file and includes the value in a prompt.
- The value is committed, pushed, and copied into clones, forks, and CI logs.
- The assistant copies the value into new code it writes, such as a test or a sample script.
The fix is to separate configuration (values that change between environments) from code. The code names a setting. The environment supplies the value at runtime.
The basic pattern
An environment variable is a named value that the operating system passes to a process when it starts. The program reads it by name.
import os
api_key = os.environ["PAYMENTS_API_KEY"]This code reads the credential at runtime. If the variable is missing, Python raises a KeyError, so the program fails immediately instead of running with a blank or default credential. The secret never appears in the source file that an assistant may read.
Prefer os.environ["NAME"] over os.environ.get("NAME", "default") for secrets. A default value hides a configuration mistake, and developers sometimes paste a real key in as the default "just for now".
Failing with a clear message
A bare KeyError is correct but terse. For a larger program, check all required settings at startup and report every missing one in a single message.
import os
import sys
REQUIRED = ["PAYMENTS_API_KEY", "DATABASE_URL"]
missing = [name for name in REQUIRED if not os.environ.get(name)]
if missing:
sys.exit("Missing required settings: " + ", ".join(missing))The message lists variable names only. Never print the values, because logs are another path by which secrets reach an assistant, a ticket, or a chat window.
Local development with `.env` files
Typing exports into every terminal gets tedious. A common convention is a .env file in the project root, with one NAME=value per line. Many tools and libraries load it into the environment at startup.
PAYMENTS_API_KEY=sk_test_replace_me
DATABASE_URL=postgres://app:replace_me@localhost:5432/appA .env file holds real secrets, so it needs two protections:
- Keep it out of Git. Add it to
.gitignore. - Keep it out of AI context. Add it to your assistant's ignore file, if the tool supports one.
The following rules cover both purposes. The file name and syntax support for AI-tool ignore files depend on the tool, so check its documentation.
.env
.env.*
!.env.example
*.pem
*.key
terraform.tfstate
terraform.tfstate.*The !.env.example line is a negation. It keeps a template file tracked even though .env.* would otherwise match it.
The `.env.example` file
Commit a template that lists the required names with fake values:
PAYMENTS_API_KEY=changeme
DATABASE_URL=postgres://user:password@localhost:5432/appThis documents what the application needs. A new teammate copies it to .env and fills in real values. The assistant can read the template safely, which is useful when you ask it to help with setup.
A limit of `.gitignore`
.gitignore only affects untracked files. If .env was committed before you added the rule, Git keeps tracking it. Check with:
git ls-files | grep -E '(^|/)\.env'If this prints a real .env, remove it from the index with git rm --cached .env. That stops tracking it going forward, but the old commits still contain the values. Treat those secrets as exposed and rotate them (see the chapter on responding to a leak).
Where else secrets hide
Environment variables are the entry point, not the whole story. Secrets leak from places that look like configuration.
| Location | Typical problem | Safer approach |
|---|---|---|
| Source files | Hard-coded keys and passwords | Read from the environment |
| Test fixtures | Real tokens copied into tests | Use fake values or a mocking library |
| Docker `ENV` and `ARG` lines | Values stored in image layers | Pass secrets at run time or use build secrets |
| Config files like `config.yaml` | Credentials committed with defaults | Reference variable names, load values separately |
| Shell history | `export KEY=...` typed inline | Load from a file or a secret manager |
| Notebooks | Output cells that print keys | Clear outputs before sharing or committing |
| Terraform state | Resource secrets stored in plain text | Use a remote encrypted backend, ignore local state |
Notebooks and Terraform state are easy to miss. State files can contain database passwords even if your .tf files do not.
Limits of environment variables
Environment variables are better than hard-coded secrets, but they are not a vault. Know where they can still be seen:
- Process listings and crash dumps. Other processes running as the same user can often read a process's environment.
- Child processes. Every program you launch inherits the variables, including build scripts and agent-run commands.
- Debug output. Commands such as
env,printenv, andsetprint every value. Framework debug pages often do the same. - Agent shells. If an AI agent runs commands in your terminal session, it runs with your environment. It can print
envand read the output, and that output goes into its context.
That last point matters most for this tutorial. Exporting a production key in the shell where an agent works gives the agent that key. Start the agent from a shell that contains only the variables it needs, ideally low-privilege development values.
env -i PATH="$PATH" HOME="$HOME" PAYMENTS_API_KEY="$DEV_PAYMENTS_KEY" ./run-agent.shThe env -i command starts the program with an empty environment, then adds back only the named variables. Here run-agent.sh stands for whatever launches your tool.
Secret managers
For anything beyond a laptop, load secrets from a dedicated service at start-up instead of from a file. Examples include AWS Secrets Manager, HashiCorp Vault, and your CI system's secret store. The application or its launcher asks the service for the value and holds it in memory.
import json
import boto3
client = boto3.client("secretsmanager")
response = client.get_secret_value(SecretId="prod/payments")
secret = json.loads(response["SecretString"])
api_key = secret["api_key"]This approach gives you access control, an audit trail, and rotation without editing files. The caller authenticates with an identity (such as an IAM role) instead of a stored password. Scoped, short-lived credentials, covered in the next chapter, make that identity safer still.
Do not log the returned value, and do not store it in a global that gets dumped on error.
How it fits together
Only the source code and the template reach the assistant. Real values stay on the right-hand side of the diagram, in the environment.
Common mistakes
- Using a default for a secret.
os.environ.get("KEY", "sk_live_...")puts a real value back into the source. - Committing
.env"just once". History keeps it. Rotate the secret. - Printing the environment while debugging. Pasting that output into a chat sends every variable to the provider.
- Reusing production keys in development. If an assistant or a log exposes the key, production is exposed too. Use separate keys per environment.
- Trusting the assistant to keep a key out of code. An assistant asked to "make this work" may write the key inline. Review diffs, and run a secret scanner before commit.
Putting it into practice
- Search your repository for hard-coded values, then replace each with an environment lookup.
- Create
.env.examplewith fake values and commit it. - Add
.envand related patterns to.gitignoreand to your assistant's ignore file. - Run
git ls-filesto confirm no real secret file is tracked. - Start your assistant from a shell that holds only development credentials.
Exercise
A teammate's code contains token = os.environ.get("API_TOKEN", "sk_live_9f2a..."). Name two separate problems with this line, and give the fix.
Show answer
First, the default is a real credential written into source, so any assistant or person who reads the file sees it, and it is committed to history. Second, the default hides a missing-configuration error, because the program runs with the embedded key instead of failing. The fix is os.environ["API_TOKEN"], which raises a KeyError when the variable is absent. Because the key was already committed, revoke and rotate it.
Exercise
You add .env to .gitignore, but git status still shows changes to .env. Why, and what should you do next?
Show answer
The file was already tracked, and .gitignore does not affect tracked files. Run git rm --cached .env to stop tracking it, commit that change, and treat the secrets in the earlier commits as exposed, so rotate them.
Exercise
Why is it risky to run an AI agent in a terminal where you have exported a production database password?
Show answer
The agent's commands inherit the shell's environment. It can read the password by running a command such as env, or a script it runs can use or print it, and the output enters the agent's context and may be sent to the provider. Start the agent in a shell that has only low-privilege development values.