Skip to content

Instantly share code, notes, and snippets.

@kmgnd
Forked from bmhatfield/.zshrc
Last active May 24, 2023 12:10
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmgnd/e04a346a59bcc865f7c2fc60f7e892a3 to your computer and use it in GitHub Desktop.
Save kmgnd/e04a346a59bcc865f7c2fc60f7e892a3 to your computer and use it in GitHub Desktop.
macOS Keychain environment variables
# If you use bash, this technique isn't really zsh specific. Adapt as needed.
source ~/keychain-env.sh
# AWS configuration example, after doing:
# $ keychain-env-add AWS_ACCESS_KEY_ID
# and
# $ keychain-env-add AWS_SECRET_ACCESS_KEY
export AWS_ACCESS_KEY_ID=$(keychain-env-get AWS_ACCESS_KEY_ID);
export AWS_SECRET_ACCESS_KEY=$(keychain-env-get AWS_SECRET_ACCESS_KEY);
### Functions for setting and getting environment variables from the macOS keychain ###
### Adapted from https://www.netmeister.org/blog/keychain-passwords.html ###
# Use: keychain-env-add SECRET_ENV_VAR
function keychain-env-add () {
if [ -z "$1" ] ; then
print "Missing environment variable name"
return 0
fi
read -s "?Enter Value for ${1}: " secret
# Note: if using bash, use `-p` to indicate a prompt string, rather than the leading `?`
( [ -n "$1" ] && [ -n "$secret" ] ) || return 1
security add-generic-password -U -a ${USER} -D "environment variable" -s "${1}" -w "${secret}"
}
# Use: keychain-env-get SECRET_ENV_VAR
function keychain-env-get () {
security find-generic-password -w -a ${USER} -D "environment variable" -s "${1}"
}
# Use: keychain-env-delete SECRET_ENV_VAR
function keychain-env-delete () {
security delete-generic-password -a ${USER} -D "environment variable" -l "${1}" 1>/dev/null
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment