• One Tip a Week
  • Posts
  • One Tip a Week: Securely Load Secrets from Your Keychain

One Tip a Week: Securely Load Secrets from Your Keychain

This week's tip of the week is about securely loading sensitive data, like API keys or tokens from your system keychain instead of hardcoding them in your shell config.

If you've ever added something like this to your .zshrc or .bashrc file:

export OPENAI_API_KEY=sk-1234...

You've probably realized that storing API keys in plain text isn't great security practice.

A better way is to store secrets in your system keychain (or credential store) and load them dynamically when your shell starts.

Here's how to do it on each platform:

macOS (using Keychain Access)

# Store it once
security add-generic-password -a $USER -s openai_api_key -w "sk-your-key-here"

# Then in ~/.zshrc or ~/.bashrc
export OPENAI_API_KEY=$(security find-generic-password -a $USER -s openai_api_key -w)

This will pull the key securely from your macOS Keychain each time you open a new shell.

Linux (using Secret Service / libsecret)

First, store your key:

secret-tool store --label="OpenAI API Key" service openai user $USER

Then in your shell config:

export OPENAI_API_KEY=$(secret-tool lookup service openai user $USER)

Windows (using PowerShell Credential Manager)

In PowerShell:

cmdkey /add:openai /user:$env:UserName /pass:sk-your-key-here

Then in your PowerShell profile:

$OPENAI_API_KEY = (cmdkey /list:openai) | Select-String "Password" | ForEach-Object { $_.ToString().Split(':')[1].Trim() }

This setup keeps your sensitive tokens out of source control and away from plain text config files, while still making them easily available to your CLI tools or scripts.

That said, this method is best for local development. Once the variable is exported, it exists in memory and can be read by other processes under your user account. For shared systems or production, use a proper secret manager like HashiCorp Vault, AWS Secrets Manager, or 1Password CLI.

Check out the Apple security command docs or libsecret docs for more details on managing credentials securely.

That's it! Short and sweet. Until the next one!