Skip to content

Instantly share code, notes, and snippets.

@erikogan
Forked from bmhatfield/.zshrc
Last active March 4, 2021 05:00
Show Gist options
  • Save erikogan/fbc78145ef0265579355b703646c6884 to your computer and use it in GitHub Desktop.
Save erikogan/fbc78145ef0265579355b703646c6884 to your computer and use it in GitHub Desktop.
OSX Keychain Environment Variables
# I’ve made this fairly zsh-specific. If you’re using bash, you might look at the gist I forked from.
fpath=(~/bin/functions /usr/share/zsh/site-functions /usr/share/zsh/$ZSH_VERSION/functions)
autoload keychain_env_var_{get{,_conditional},set}
# AWS configuration example, after doing:
# $ keychain_env_var_set AWS_ACCESS_KEY_ID
# provide: "AKIAYOURACCESSKEY"
# $ keychain_env_var_set AWS_SECRET_ACCESS_KEY
# provide: "j1/yoursupersecret/password"
keychain_env_var_get_conditional AWS_ACCESS_KEY_ID
keychain_env_var_get_conditional AWS_SECRET_ACCESS_KEY
#!/bin/zsh
# keychain_env_var_get: Set a value in the keychain for a variable set earlier
security find-generic-password -w -a ${USER} -D "environment variable" -s "${1}"
return $?
#!/bin/zsh
# keychain_env_var_get_conditional: Get an environment variable from Keychain only if the item exists
if keychain_env_var_get "${1}" >/dev/null 2>&1 ; then
eval "export ${1}=$(keychain_env_var_get ${1})"
fi
#!/bin/zsh
# keychain_env_var_set: Set a value in the keychain for a variable to be pulled later (at login)
if [ -z "$1" ]; then
echo "Missing environment variable name" >&2
return 1
fi
# 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