Skip to content

Instantly share code, notes, and snippets.

@adamvduke
Forked from bmhatfield/.zshrc
Last active November 22, 2016 19:01
Show Gist options
  • Save adamvduke/fe3067116edddda168e02155d9d9695f to your computer and use it in GitHub Desktop.
Save adamvduke/fe3067116edddda168e02155d9d9695f to your computer and use it in GitHub Desktop.
OSX Keychain Environment Variables
# If you use bash, this technique isn't really zsh specific. Adapt as needed.
source ~/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"
export AWS_ACCESS_KEY_ID=$(keychain-environment-variable AWS_ACCESS_KEY_ID);
export AWS_SECRET_ACCESS_KEY=$(keychain-environment-variable AWS_SECRET_ACCESS_KEY);
# https://gist.github.com/bmhatfield/f613c10e360b4f27033761bbee4404fd
### 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 () {
value=$(security find-generic-password -w -a ${USER} -D "environment variable" -s "${1}" 2>/dev/null)
if [[ "$?" == "0" ]]
then
echo $value
else
echo "No value for $1" > /dev/stderr
fi
}
# Use: set-keychain-environment-variable SECRET_ENV_VAR
# provide: super_secret_key_abc123
function set-keychain-environment-variable () {
cur_shell=$(ps -p $$ | awk '$1 != "PID" {print $(NF)}')
[ -n "$1" ] || print "Missing environment variable name"
if [ "$cur_shell" = "-bash" ]; then
read -sp "Enter Value for ${1}: " secret
fi
if [ "$cur_shell" = "zsh" ]; then
read -s "?Enter Value for ${1}: " secret
fi
( [ -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