Skip to content

Instantly share code, notes, and snippets.

@holmesjr
Created August 1, 2018 23:25
Show Gist options
  • Save holmesjr/062f2870bfc6d189a96e4b885c5b4685 to your computer and use it in GitHub Desktop.
Save holmesjr/062f2870bfc6d189a96e4b885c5b4685 to your computer and use it in GitHub Desktop.
A git credentials helper the uses AWS secrets manager
#!/bin/bash
set -eu
# The function creates global variables with the parsed results.
# It returns 0 if parsing was successful or non-zero otherwise.
#
# [schema://][user[:password]@]host[:port][/path][?[arg1=val1]...][#fragment]
#
# from http://vpalos.com/537/uri-parsing-using-bash-built-in-features/
parse_url() {
local uri="$*"
# safe escaping
uri="${uri//\`/%60}"
uri="${uri//\"/%22}"
# top level parsing
pattern='^(([a-z]{3,5})://)?((([^:\/]+)(:([^@\/]*))?@)?([^:\/?]+)(:([0-9]+))?)(\/[^?]*)?(\?[^#]*)?(#.*)?$'
[[ "$uri" =~ $pattern ]] || return 1;
# component extraction
uri=${BASH_REMATCH[0]}
export uri_schema=${BASH_REMATCH[2]}
export uri_address=${BASH_REMATCH[3]}
export uri_user=${BASH_REMATCH[5]}
export uri_password=${BASH_REMATCH[7]}
export uri_host=${BASH_REMATCH[8]}
export uri_port=${BASH_REMATCH[10]}
export uri_path=${BASH_REMATCH[11]}
export uri_query=${BASH_REMATCH[12]}
export uri_fragment=${BASH_REMATCH[13]}
# path parsing
count=0
path="$uri_path"
pattern='^/+([^/]+)'
while [[ $path =~ $pattern ]]; do
eval "uri_parts[$count]=\"${BASH_REMATCH[1]}\""
path="${path:${#BASH_REMATCH[0]}}"
(( count++ ))
done
# query parsing
count=0
query="$uri_query"
pattern='^[?&]+([^= ]+)(=([^&]*))?'
while [[ $query =~ $pattern ]]; do
eval "uri_args[$count]=\"${BASH_REMATCH[1]}\""
eval "uri_arg_${BASH_REMATCH[1]}=\"${BASH_REMATCH[3]}\""
query="${query:${#BASH_REMATCH[0]}}"
(( count++ ))
done
}
# AWS SM is only in very recent AWS CLI versions, and isn't on Amazon Linux 2 AMIs (as of July 2018)
docker pull infrastructureascode/aws-cli > /dev/null
function get_secret_value() {
local secretId="$1"
# Extract the secret string
local secrets=$(docker run \
infrastructureascode/aws-cli \
aws secretsmanager get-secret-value \
--secret-id "${secretId}" \
--version-stage AWSCURRENT \
--output json \
--region ap-southeast-2 \
--query '{SecretString: SecretString}') #NEED A REGION?
# assume it's a string
echo "${secrets}" | jq -r '.SecretString'
}
secret_id="${1}"
uri=$(get_secret_value "$secret_id" | jq -r '.Cred')
if ! parse_url "$uri" ; then
echo "Failed to parse uri $uri" >&2
exit 1
fi
# https://git-scm.com/docs/git-credential#IOFMT
echo "protocol=${uri_schema}"
echo "host=${uri_host}"
echo "username=${uri_user}"
echo "password=${uri_password}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment