cfg/bin/docker-credential-vault

70 lines
1.5 KiB
Text
Raw Normal View History

#!/bin/bash
set -euo pipefail
# Usage:
#
# 1) Put this into your ~/.docker/config.json:
# { "credsStore": "vault" }
#
# 2) Optional: Create ~/.config/docker-credential-test with an
# override for the $PREFIX variable which defaults to
# "secret/docker-credential" in case you want to store the
# credentials some place else
#
# 3) Ensure vault is installed and can access the path specified by
# $PREFIX/*
config="${HOME}/.config/docker-credential-test"
req_cmds=(jq vault)
PREFIX=secret/docker-credential
[[ -f $config ]] && source "${config}" || true
function check_command() {
command -v "${1}" >/dev/null || {
echo "Missing tool: ${1}" >&2
exit 1
}
}
function get() {
local hostname="$(cat -s)" # Missing newline at the end, read does not work
vault read -field=data -format=json "${PREFIX}/$(hash_hostname "${hostname}")"
}
function hash_hostname() {
echo "$1" | md5sum | cut -d ' ' -f 1
}
function main() {
for cmd in "${req_cmds[@]}"; do
check_command "${cmd}"
done
case "${1:-help}" in
get) get ;;
store) store ;;
*)
echo "Supported are only 'get' and 'store' arg" >&2
exit 1
;;
esac
}
function store() {
local json="$(cat -s)"
local hostname=$(echo "${json}" | jq -r '.ServerURL')
local username=$(echo "${json}" | jq -r '.Username')
local secret=$(echo "${json}" | jq -r '.Secret')
vault write "${PREFIX}/$(hash_hostname "${hostname}")" \
"ServerURL=${hostname}" \
"Username=${username}" \
"Secret=${secret}"
}
main "$@"