Skip to content

Instantly share code, notes, and snippets.

@malston
Last active January 28, 2022 22:25
Show Gist options
  • Save malston/f91f050948baaf180aabaec8e7ee95ff to your computer and use it in GitHub Desktop.
Save malston/f91f050948baaf180aabaec8e7ee95ff to your computer and use it in GitHub Desktop.
Retrieves credhub credentials by running a remote shell script on opsman vm
#!/usr/bin/env bash
set -o errexit
usage() {
echo "$0 [name of the credential to retrieve]"
echo "Example: $0 /credhub-service-broker/credhub/99f0c44c-1cb5-4c5f-91a8-873090e035aa/credentials"
}
if [ "$#" -lt 1 ]; then
usage
exit 1
fi
NAME=$1
CF_DEPLOYMENT="$(bosh deps --column=name | grep '^cf-' | tr -d '\t\n')"
CREDHUB_SECRET="$(om curl -s -p /api/v0/deployed/products/$CF_DEPLOYMENT/credentials/.uaa.credhub_admin_client_client_credentials | jq -r .credential.value.password)"
JOB_NAME=$(bosh is -p | grep credhub | head -1 | awk '{print $1}')
CREDHUB_IP_ADDRESS=$(om -k curl -s -p /api/v0/deployed/products/$CF_DEPLOYMENT/status | jq -r --arg job "$JOB_NAME" '.status[] | select(."job-name"==$job) | .ips[]')
script_dir=$(mktemp -d)
cat > "$script_dir/retrieve-credhub-creds.sh" <<EOF
#!/usr/bin/env bash
set -o errexit
function urlencode() {
local l=\${#1}
for (( i = 0 ; i < l ; i++ )); do
local c=\${1:i:1}
case "\$c" in
[a-zA-Z0-9.~_-]) printf "%s" "\$c" ;;
' ') printf + ;;
*) printf '%%%.2X' "'\$c"
esac
done
}
CREDHUB_SERVER=https://credhub.service.cf.internal:8844
CREDHUB_CLIENT="credhub_admin_client"
CREDHUB_SECRET="$CREDHUB_SECRET"
CREDHUB_IP_ADDRESS="$CREDHUB_IP_ADDRESS"
NAME=$NAME
ACCESS_TOKEN=\$(curl --cacert /var/tempest/workspaces/default/root_ca_certificate \\
--resolve "uaa.service.cf.internal:8443:$CREDHUB_IP_ADDRESS" \\
-d "client_id=\$CREDHUB_CLIENT&client_secret=\$CREDHUB_SECRET&grant_type=client_credentials&token_format=jwt" \\
https://uaa.service.cf.internal:8443/oauth/token \\
-s -X POST \\
H 'Content-Type: application/x-www-form-urlencoded' \\
-H 'Accept: application/json' | jq -r .access_token)
curl --cacert /var/tempest/workspaces/default/root_ca_certificate \\
--resolve "credhub.service.cf.internal:8844:\$CREDHUB_IP_ADDRESS" \\
"\$CREDHUB_SERVER/api/v1/data?name=\$NAME&current=true" \\
-s -X GET \\
-H 'Host: credhub.service.cf.internal' \\
-H 'Content-Type: application/json' \\
-H "Authorization: Bearer \$ACCESS_TOKEN" | jq -r .data[]?.value
EOF
ssh -i ~/.ssh/om_rsa_key [email protected] -q "bash -s " < "$script_dir/retrieve-credhub-creds.sh"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment