From ae2dc0558e34860805ab62aba0505d6291b94294 Mon Sep 17 00:00:00 2001 From: Knut Ahlers Date: Fri, 19 Aug 2022 14:48:11 +0200 Subject: [PATCH] Add "vault" docker credsStore Signed-off-by: Knut Ahlers --- bin/docker-credential-vault | 69 +++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100755 bin/docker-credential-vault diff --git a/bin/docker-credential-vault b/bin/docker-credential-vault new file mode 100755 index 0000000..2af6e2b --- /dev/null +++ b/bin/docker-credential-vault @@ -0,0 +1,69 @@ +#!/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 "$@"