Skip to content

Instantly share code, notes, and snippets.

@Superbil
Forked from bmhatfield/.zshrc
Created November 30, 2022 16:11
Show Gist options
  • Save Superbil/a3b9648210c694bceb15dacbca51d8ae to your computer and use it in GitHub Desktop.
Save Superbil/a3b9648210c694bceb15dacbca51d8ae 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);
### 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