Here’s a quick tip for storing secrets like API keys in Apple Keychain on macOS and referencing them in .zshrc without hardcoding them and risking them be exposed while still making them available to your shell.

  1. Add the secret to Apple Keychain:

    security delete-generic-password -a "$USER" -s "Example API Key"
    security add-generic-password -a "$USER" -s "Example API Key" -w YOUR_SECRET_VALUE_HERE
    

    Replace Example API Key with the name for your key and YOUR_SECRET_VALUE_HERE with the actual secret.

  2. Add the following line to your ~/.zshrc:

    export EXAMPLE_API_KEY="$(security find-generic-password -a "$USER" -s "Example API Key" -w)"
    

    Replace EXAMPLE_API_KEY and Example API Key as needed

  3. Reload your shell config:

    source ~/.zshrc
    

Your secret should now be available as an environment variable in your shell without being written to .zshrc in plain text 🎉