Skip to content

Instantly share code, notes, and snippets.

@RamonPage
Forked from bmhatfield/.zshrc
Last active August 23, 2021 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RamonPage/90c1ee513421768f72520a9d76d2fa1e to your computer and use it in GitHub Desktop.
Save RamonPage/90c1ee513421768f72520a9d76d2fa1e to your computer and use it in GitHub Desktop.
OSX Keychain Environment Variables
# Requires keychain-environment-variables.sh
#
# AWS configuration example, after doing:
# $ set-keychain-environment-variable AWS_ACCESS_KEY_ID
# provide: "AKIAYOURACCESSKEY"
# $ set-keychain-environment-variable AWS_SECRET_ACCESS_KEY
# provide: "j1/yoursupersecret/password"
# AWS_ACCESS_KEY_ID=$(keychain-environment-variable AWS_ACCESS_KEY_ID);
# AWS_SECRET_ACCESS_KEY=$(keychain-environment-variable AWS_SECRET_ACCESS_KEY);
# If you use bash, this technique isn't really zsh specific. Adapt as needed.
source ~/keychain-environment-variables.sh
set -a # automatically export all variables
source ~/.env
set +a
### Functions for setting and getting environment variables from the OSX keychain ###
### Adapted from https://www.netmeister.org/blog/keychain-passwords.html ###
# Use: keychain-environment-variable SECRET_ENV_VAR
function keychain-environment-variable () {
security find-generic-password -w -a ${USER} -D "environment variable" -s "${1}"
}
# Use: set-keychain-environment-variable SECRET_ENV_VAR
# provide: super_secret_key_abc123
function set-keychain-environment-variable () {
[ -n "$1" ] || print "Missing environment variable name"
# Note: if using bash, use `-p` to indicate a prompt string, rather than the leading `?`
read -s "?Enter Value for ${1}: " secret
( [ -n "$1" ] && [ -n "$secret" ] ) || return 1
security add-generic-password -U -a ${USER} -D "environment variable" -s "${1}" -w "${secret}"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment