Skip to content

Instantly share code, notes, and snippets.

@dln
Last active September 4, 2019 14:49
Show Gist options
  • Select an option

  • Save dln/54ea586b24189b8ebc12f1ae8a2a0b45 to your computer and use it in GitHub Desktop.

Select an option

Save dln/54ea586b24189b8ebc12f1ae8a2a0b45 to your computer and use it in GitHub Desktop.
Run a program with an environment variable containing a secret. Use kernel keyring to cache this value to avoid having to re-enter credentials.
#!/bin/bash
set -eu
purge=0
ttl=600
usage() { echo "Usage: $0 [-t SECONDS] [-f]" 1>&2; exit 1; }
while getopts ":ft:" o; do
case "${o}" in
f)
purge=1
;;
t)
ttl=${OPTARG}
;;
*)
usage
;;
esac
done
shift $((OPTIND-1))
var="$1"
shift
if [ -z "${var}" ]; then
usage
fi
function get_password() {
key="pwenv.${var}"
if [ "${purge}" == "1" ]; then
keyctl purge user ${key} 2>&1 >>/dev/null || true
fi
out=$(systemd-ask-password --accept-cached --keyname="${key}" "${var}:")
key_id=$(keyctl request user ${key} 2>/dev/null)
keyctl timeout $key_id $ttl
echo $out
}
exec env ${var}=$(get_password) "$@"
@dln

dln commented Sep 4, 2019

Copy link
Copy Markdown
Author

Sample usage:

$ pwenv PGPASSWORD psql mydatabase

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment