Sub topic 4
Storing the key in an environment variable
This chapter assumes you can use a terminal, read short Python or JavaScript snippets, and know that an HTTP API accepts requests with credentials attached. You already have a key from your provider console. Here you will move it out of your source code and into the process environment.
What an environment variable is
An environment variable is a named string that the operating system hands to a process when it starts. Every program you run gets its own copy of the variables from the program that launched it. Your shell is the launcher, so a variable set in your shell is visible to the programs you start from it.
Code reads the variable by name. The key is never written in a file that you commit, so the source code can be shared without the secret.
This gives you three benefits:
- The code stays the same across machines. Only the environment changes.
- You can use a different key for development, testing, and production without editing code.
- Most hosting and CI systems have a built-in way to set environment variables, so the same pattern works everywhere.
Environment variables are not encryption. Any process running as your user can read them, and a crash dump or a debug page can reveal them. They move the secret out of the code. They do not make it safe on their own.
Setting a variable in your shell
In Bash or Zsh, the export command sets a variable and marks it for inheritance by child processes.
export LLM_API_KEY="paste-your-key-here"
echo "${#LLM_API_KEY} characters set"The second line prints only the length of the value, so the key never appears on screen. The ${#NAME} syntax expands to the number of characters in the variable.
Without export, the variable exists only in the current shell. Programs you start will not see it. This is a common source of "it is set but my script cannot find it" errors.
Lifetime and scope
A variable set this way lasts until you close that terminal. A new terminal window starts without it. Each of the following has a different scope:
| How it is set | Visible to | Lasts until |
|---|---|---|
| `export NAME=value` in a terminal | That shell and programs started from it | The shell closes |
| `NAME=value command` on one line | Only that one command | The command exits |
| A line in `~/.bashrc` or `~/.zshrc` | Every new interactive shell | You remove the line |
| A CI or hosting setting | The jobs or services that platform runs | You change the setting |
The one-line form is useful for a quick test:
LLM_API_KEY="paste-your-key-here" python app.pyShell history
Typing a key on the command line stores it in your shell history file, for example ~/.bash_history or ~/.zsh_history. That file is plain text, and it can end up in backups or screenshots of your terminal.
Two ways to reduce this risk:
- In Bash or Zsh, start the line with a space. Many setups skip such lines in history. This depends on the
HISTCONTROL=ignorespacesetting in Bash orHIST_IGNORE_SPACEin Zsh, so check that it is on. - Read the key without echoing it, using
read -s.
read -rs -p "LLM API key: " LLM_API_KEY
echo
export LLM_API_KEY
echo "${#LLM_API_KEY} characters set"The -s flag hides what you type, and -r stops backslashes from being treated as escapes. The -p prompt flag is available in Bash. In Zsh, use read -rs "LLM_API_KEY?LLM API key: " instead.
A line in ~/.bashrc makes the key permanent for every shell. That is convenient, but then every program you run inherits it, including ones that have no need for it. For one project, a .env file (covered in the next chapter) limits the exposure better.
Reading the variable in code
Your code should read the key by name and fail early if it is absent. A missing key that turns into an empty string produces confusing authentication errors later, far from the cause.
In Python, os.environ is a dictionary-like object of the current environment.
import os
api_key = os.environ.get("LLM_API_KEY")
if not api_key:
raise RuntimeError("LLM_API_KEY is not set")Using .get() returns None when the name is absent, and the if not api_key check also catches an empty string. Using os.environ["LLM_API_KEY"] instead raises a KeyError right away, which is also acceptable but gives a less readable message.
In Node.js, the same data is in process.env.
const apiKey = process.env.LLM_API_KEY;
if (!apiKey) {
throw new Error("LLM_API_KEY is not set");
}Both snippets do the check once at startup. Doing it at startup means a misconfigured deployment fails at launch instead of on the first user request.
Sending the key in a request
Once the key is loaded, you attach it to each request. Most providers expect an Authorization header with a bearer token, though the exact header name and format are in your provider's documentation.
import os
import requests
api_key = os.environ["LLM_API_KEY"]
response = requests.post(
"https://api.example.com/v1/chat", # placeholder URL: use your provider's documented endpoint
headers={"Authorization": f"Bearer {api_key}"},
json={"prompt": "Say hello"},
timeout=30,
)
print(response.status_code)The URL is a placeholder. Replace it with the endpoint your provider documents. The script prints only the status code, not the key or the request headers. Printing response.request.headers would reveal the key in your terminal and in any log that captures it.
How the key travels
The variable is copied from the parent process to the child at launch. Changing it later in the shell does not change a program that is already running.
Because the diagram syntax must use the exact fence below, here is the flow shown properly.
Common errors
- The variable is set but the program cannot see it. You set it without
export, or in a different terminal window. Runprintenv LLM_API_KEY | wc -cin the same shell to check. A result of 0 or an error means it is not exported there. - The name is spelled differently. Variable names are case-sensitive on Linux and macOS.
LLM_API_KEYandllm_api_keyare two different variables. - Quotes and spaces are part of the value.
export LLM_API_KEY = "abc"fails because of the spaces around=. A trailing newline or space copied from the console also becomes part of the key and causes a rejected request. If you suspect this, compare the length printed by the length check with the length your provider shows or documents. - An IDE or service does not inherit your shell. A program launched from a desktop icon, a systemd service, or a container does not read your
~/.zshrc. Set the variable in that tool's own configuration. - The key appears in logs. Printing
os.environ, logging all request headers, or enabling verbose HTTP debugging can write the key to log files. Log the status code, not the headers. - The key is passed to child processes that do not need it. Every subprocess inherits the full environment by default. If your program runs untrusted commands, pass an explicit, smaller environment to them.
Where environment variables are visible
On Linux, a process's environment can be read from /proc/<pid>/environ by the same user or by root. Tools such as ps eww can show it too. Container inspection commands such as docker inspect show variables set when a container was created. This is why environment variables suit small projects and why larger systems often move to a dedicated secret manager, which a later chapter covers.
Check your understanding
Exercise
You run LLM_API_KEY="abc" in your terminal, then start python app.py, and the script reports that LLMAPIKEY is not set. What went wrong, and what is the fix?
Show answer
Without export, the assignment creates a shell variable that is not passed to child processes, so the Python process never receives it. Fix it by running export LLM_API_KEY="abc", or by putting the assignment on the same line as the command: LLM_API_KEY="abc" python app.py.
Exercise
Why does the chapter's shell example print ${#LLM_API_KEY} instead of $LLM_API_KEY when confirming the key is set?
Show answer
${#LLM_API_KEY} prints only the number of characters in the value, which confirms the variable is set and roughly the right size. Printing $LLM_API_KEY would show the key on screen, in scrollback, and possibly in recorded sessions or screenshots.